root/library/bdm/base/user_info.h @ 540

Revision 540, 22.8 kB (checked in by vbarta, 15 years ago)

split UIException into 3

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief UI (user info) class for loading/saving objects from/to configuration files.
4  It is designed with use of libconfig C/C++ Configuration File Library
5  \ref ui_page
6  \author Vaclav Smidl.
7
8  -----------------------------------
9  BDM++ - C++ library for Bayesian Decision Making under Uncertainty
10
11  Using IT++ for numerical operations
12  -----------------------------------
13*/
14
15#ifndef USER_INFO_H
16#define USER_INFO_H
17
18#include <stdio.h>
19#include <string>
20#include <typeinfo>
21#include <map>
22#include <stdexcept>
23
24#include "libconfig/libconfig.h++"
25#include "../bdmroot.h"
26#include "../shared_ptr.h"
27#include "itpp/itbase.h"
28
29
30using std::string;
31using namespace std;
32using namespace libconfig;
33
34namespace bdm {
35
36//! Generic exception for reporting configuration errors
37//!
38//!  \ref ui_page
39class UIException : public std::exception {
40private:
41        //! Error message
42        const string message;
43
44public:
45        /*!
46          \brief The constructor
47          \param message the reason for throwing the exception. Should be a complete English sentence (or a couple sentences), starting with "UIException: ".
48        */
49        UIException ( const string &message ) :
50                message ( message ) {
51        }
52
53        //! Overriden method for reporting the error message
54        virtual const char* what() const throw() {
55                return message.c_str();
56        }
57
58        ~UIException() throw() {};
59
60protected:
61        /*!
62          Formats error messages for derived classes, which use a
63          Setting path in addition to the message.
64        */
65        static string format_message( const string &reason, const string &path );
66};
67
68//! Exception for reporting configuration errors related to some concrete Setting path
69//!
70//!  \ref ui_page
71class UISettingException : public UIException {
72public:
73        //! Use this constructor when you can pass the problematical Setting as a parameter
74        UISettingException ( const string &message, const Setting &element ):
75                UIException ( format_message ( message, string ( element.getPath() ) ) ) {
76        }
77
78        //! This constructor is for other occasions, when only path of problematical Setting is known
79        UISettingException ( const string &message, const string &path ):
80                UIException ( format_message ( message, path ) ) {
81        }
82
83        ~UISettingException() throw() {};
84};
85
86//! Exception for reporting configuration errors in the "class" attribute
87//!
88//!  \ref ui_page
89class UIClassException : public UIException {
90public:
91        //! Use this constructor when you can pass the problematical Setting as a parameter
92        UIClassException ( const string &message, const Setting &element ):
93                UIException ( format_message ( message, string ( element.getPath() ) ) ) {
94        }
95
96        //! This constructor is for other occasions, when only path of problematical Setting is known
97        UIClassException ( const string &message, const string &path ):
98                UIException ( format_message ( message, path ) ) {
99        }
100
101        ~UIClassException() throw() {};
102};
103
104/*!
105@brief This class serves to load and/or save user-infos into/from
106configuration files stored on a hard-disk.
107
108Firstly, save some user-infos into the new UIFile instance. Then,
109call the save method with a filename as its only argument:
110
111\code
112        CAudi audi;
113        UIFile file;
114        UI::save( audi, file, "TT");
115        file.save("cars.cfg");
116\endcode
117
118In the other way round, when loading object from a configuration file,
119the appropriate code looks like this:
120
121\code
122        UIFile file("cars.cfg");
123        CAudi *audi = UI::build<CAudi>(file,"TT");
124\endcode
125
126\ref ui_page
127*/
128class UIFile : public Config {
129public:
130        //! Create empty file instance prepared to store Settings
131        UIFile();
132
133        //! Creates instance and fills it from the configuration file file_name
134        UIFile ( const string &file_name );
135
136        //! Save all the stored Settings into the configuration file file_name
137        void save ( const string &file_name );
138
139        //! This operator allows the ability of substituting Setting parameter by UIFile instance
140        operator Setting&();
141};
142
143/*!
144@brief This class serves to expand links used within configuration files.
145
146Value of any type but string can be linked to some other value of the same type
147defined elsewhere in the current configuration file or even in some different
148configuration file.
149
150Link have three parts, \<name\> : \<path\> \<\@filename\>. Field \<name\> contains the
151name of the new setting, \<path\> is the relative path to the referenced setting, which
152has to be taken from the %root Setting element. The last part \<\@filename\> is optional,
153it contains filename in the case the link should refer to a variable stored in a different
154file. From the previous part \<path\>, it has to be separated by '@'.
155
156\code
157    ...
158        jardovo :
159        {
160          class = "Car";
161          year = 1992;
162          manufacturer = "liaz";
163          kilometers = 1555000;
164        };
165        ondrejovo :
166        {
167          class = "Bike";
168          year = 1996;
169          manufacturer = "author";
170          electricLights = true;
171          matr = ( 2, 2, [ 1.0, 0.0, 0.0, 1.0 ] );
172        };
173
174        #this is the example of local link to another mean of transport
175        elisky = "jardovo";
176
177        ...
178
179        # And this link is external link pointing to the file "other_cars.cfg" stored in the
180        # same directory. In that file, it refers to the local Setting "magic_cars.skubankovo".
181        kati = "magic_cars.skubankovo@other_cars.cfg";
182
183    ...
184\endcode
185
186When you want to expand a possible linked setting "element" within your code, it has to be treated this way:
187
188\code
189        ...
190
191        const SettingResolver link( element );
192
193        ...
194
195        int len = link.result.getLength();
196
197        ...
198\endcode
199
200The whole point is that a resolved link (class member #result, i.e., "link.result" in the previous example) could point
201into a different configuration file. In that case there has to be an UIFile instance managing reading from this
202file. As the libconfig::Config deletes all its Settings when dealocated, UIFile must not be dealocated until all
203the necessary operation on the linked Setting are finished (otherwise, the link #result would be invalid just after
204the UIFile dealocation). And that is exactly the mechanism implemented within SettingResolver class. It assures,
205that the #result Setting reference is valid within the scope of SettingResolver instance.
206
207\ref ui_page
208 */
209class SettingResolver : root {
210private:
211        //! If necessary, this pointer stores an addres of an opened UIFile, else it equals NULL
212        UIFile *file;
213
214        //! This method initialize #result reference, i.e., it executes the main code of SettingResolver class
215        //!
216        //! This code could be also located directly in constructor. The only reason why we made this
217        //! method is the keyword 'const' within the declaration of #result reference . Such a reference
218        //! have to be intialized before any other constructor command, exactly in the way it is implemented now.
219        const Setting &initialize_reference ( UIFile* &file, const Setting &potential_link );
220
221public:
222        //! Reference to a resolved link or to the original Setting in the case it does not contain a link
223        const Setting &result;
224
225        //! If potential_link contains a link to some other setting, it is resolved here. Anyway, the Setting reference #result is prepared for use.
226        SettingResolver ( const Setting &potential_link );
227
228        //! An opened UIFile file is closed here if necessary.
229        ~SettingResolver();
230};
231
232/*!
233@brief UI is an abstract class which collects all the auxiliary functions useful to prepare some concrete
234user-infos.
235
236See static methods 'build', 'get' and 'save'. Writing user-infos with these methods is rather  simple. The
237rest of this class is intended for internal purposes only. Its meaning is to allow pointers to its templated
238descendant ParticularUI<T>.
239
240\ref ui_page
241*/
242class UI {
243private:
244        //! Class with state shared across all its instances ("monostate"), encapsulating two maps, one mapping names to UI instances and the other mapping type_infos to class names
245        //!
246        //! The key property of this class is that it initializes the internal maps on global init,
247        //! before the instance is used for a first time. Therefore, we do not have to care about initialization
248        //! during a call of UIREGISTER macro operating with both these mappings.
249        class MappedUI {
250        private:
251                //! Type definition of mapping which transforms class names to the related UI instances
252                typedef map< const string, const UI* const > StringToUIMap;
253
254                //! Type definition of mapping which transforms RTTI type_infos to the related class names
255                typedef map< const type_info * const, const string > TypeInfoToStringMap;
256
257                //! Immediately initialized instance of type StringToUIMap
258                static StringToUIMap& mapped_strings();
259
260                //! Immediately initialized instance of type TypeInfoToStringMap
261                static TypeInfoToStringMap& mapped_type_infos();
262
263                //! Method for reporting a error when an attempt to operate with an unregistered class occures
264                static void unregistered_class_error ( const string &unregistered_class_name );
265
266        public:
267                //! Add a pair key-userinfo into the internal map
268                static void add_class ( const string &class_name, const type_info * const class_type_info, const UI* const ui );
269
270                //! Search for an userinfo related to the passed class name within the internal map
271                static const UI& retrieve_ui ( const string &class_name );
272
273                //! Search for an class name related to the passed type_info within the internal map
274                static const string& retrieve_class_name ( const type_info* const class_type_info );
275        };
276
277        //! Function assertting that the setting element is of the SettingType type
278        static void assert_type ( const Setting &element, Setting::Type type );
279
280        /*!
281          \brief Method constructing a configured instance
282
283          The returned pointer must be allocated using operator new
284          (it's deleted at the end of its life cycle). The method is
285          implemented in descendant class ParticularUI<T>, which knows
286          the correct type T.
287        */
288        virtual root* new_instance() const = 0;
289
290        //! Method switching from the \a element to its child Setting according the passed \a index, it also does all the necessary error-checking
291        static const Setting& to_child_setting ( const Setting &element, const int index );
292
293        //! Method switching from the \a element to its child Setting according the passed \a name, it also does all the necessary error-checking
294        static const Setting& to_child_setting ( const Setting &element, const string &name );
295
296        //! This method converts a Setting into a matrix
297        static void from_setting ( mat& matrix, const Setting &element );
298        //! This method converts a Setting into an integer vector
299        static void from_setting ( ivec &vector, const Setting &element );
300        //! This method converts a Setting into a string
301        static void from_setting ( string &str, const Setting &element );
302        //! This method converts a Setting into a real vector
303        static void from_setting ( vec &vector, const Setting &element );
304        //! This method converts a Setting into a integer scalar
305        static void from_setting ( int &integer, const Setting &element );
306        //! This method converts a Setting into a real scalar
307        static void from_setting ( double &real, const Setting &element );
308
309        //! This method converts a Setting into a class T descendant
310        template<class T> static void from_setting ( T* &instance, const Setting &element ) {
311                const SettingResolver link ( element );
312                assert_type ( link.result, Setting::TypeGroup );
313
314                // we get a value stored in the "class" attribute
315                string class_name;
316                if ( !link.result.lookupValue ( "class", class_name ) )
317                        throw UIClassException ( "UIException: the obligatory \"class\" identifier is missing.", link.result );
318
319                // then we find a user-info related to this type
320                const UI& related_UI = MappedUI::retrieve_ui ( class_name );
321
322                root *typeless_instance = related_UI.new_instance();
323                it_assert_debug ( typeless_instance, "UI::new_instance failed" );
324
325                instance = dynamic_cast<T*> ( typeless_instance );
326                if ( !instance ) {
327                        delete typeless_instance;
328                        throw UIClassException ( "UIException: class " + class_name + " is not a descendant of the desired output class. Try to call the UI::build<T> function with a different type parameter.", link.result );
329                }
330
331                try {
332                        instance->from_setting ( link.result );
333                } catch ( SettingException sttng_xcptn ) {
334                        string msg = "UIException: method ";
335                        msg += class_name;
336                        msg += ".from_setting(Setting&) has thrown a SettingException.";
337                        throw UISettingException(msg, sttng_xcptn.getPath());
338                }
339        }
340
341        //! This method converts a Setting into a descendant of class
342        //! T, wrapped in an instance of shared_ptr<T> .
343        template<class T>
344        static void from_setting ( shared_ptr<T> &instance, const Setting &element ) {
345                T *tmp_inst = 0;
346                from_setting ( tmp_inst, element );
347                it_assert_debug ( tmp_inst, "UI::from_setting failed" );
348                instance = tmp_inst;
349        }
350
351        //! This methods converts a Setting into a new templated array of type Array<T>
352        template<class T> static void from_setting ( Array<T> &array_to_load, const Setting &element ) {
353                const SettingResolver link ( element );
354
355                assert_type ( link.result, Setting::TypeList );
356
357                int len = link.result.getLength();
358                array_to_load.set_length ( len );
359                if ( len == 0 ) return;
360
361                for ( int i = 0; i < len; i++ )
362                        from_setting ( array_to_load ( i ), link.result[i] );
363        }
364
365        //! This is dummy version of the from_setting method for other, unsupported types. It just throws an exception.
366        //!
367        //! At the moment, this is the only way how to compile the library without obtaining the compiler error c2665.
368        //! The exception can help to find the place where the template is misused and also to correct it.
369        template<class T> static void from_setting ( T &variable_to_load, const Setting &element ) {
370                std::string msg = "UIException: from_setting is not implemented for type ";
371                msg += typeid(T).name();
372                msg += '.';
373                throw UISettingException ( msg, element );
374        }
375
376
377protected:
378        //! Constructor for internal use only, see \sa ParticularUI<T>
379        UI ( const string& class_name, const type_info * const class_type_info ) {
380                MappedUI::add_class ( class_name, class_type_info, this );
381        }
382
383public:
384
385        //! Enum type used to determine whether the data for concrete Settingis is compulsory or optional
386        enum SettingPresence { optional, compulsory } ;
387
388        //! \name Initialization of classes
389        //!@{
390        //! The type T has to be a #bdm::root descendant class
391
392        //! The new instance of type T* is constructed and initialized with values stored in the Setting element[name]
393        //!
394        //! If there is not any sub-element named #name and settingPresence is #optional, an empty shared_ptr<T> is returned. When settingPresence is #compulsory, the returned shared_ptr<T> is never empty (an exception is thrown when the object isn't found).
395        template<class T>
396        static shared_ptr<T> build ( const Setting &element, const string &name, SettingPresence settingPresence = optional ) {
397                if ( !element.exists ( name ) ) {
398                        if ( settingPresence == optional )
399                                return shared_ptr<T>();
400                        else
401                                throw UISettingException ( "UIException: the compulsory Setting named \"" + name + "\" is missing.", element );
402                }
403
404                shared_ptr<T> instance;
405                from_setting<T> ( instance, to_child_setting ( element, name ) );
406                return instance;
407        }
408
409        //! The new instance of type T* is constructed and initialized with values stored in the Setting element[index]
410        //!
411        //! If there is not any sub-element indexed by #index, and settingPresence is #optional, an empty shared_ptr<T> is returned. When settingPresence is #compulsory, the returned shared_ptr<T> is never empty (an exception is thrown when the object isn't found).
412        template<class T>
413        static shared_ptr<T> build ( const Setting &element, const int index, SettingPresence settingPresence = optional ) {
414                if ( element.getLength() <= index ) {
415                        if ( settingPresence == optional )
416                                return shared_ptr<T>();
417                        else {
418                                stringstream stream;
419                                stream << index;
420                                throw UISettingException ( "UIException: the compulsory Setting with the index " + stream.str() + " is missing.", element );
421                        }
422                }
423
424                shared_ptr<T> instance;
425                from_setting<T> ( instance, to_child_setting ( element, index ) );
426                return instance;
427        }
428
429        //!@}
430
431        //! \name Initialization of structures
432        //!@{
433        //! The type T has to be int, double, string, vec, ivec or mat.
434
435        //! The existing instance of type T is initialized with values stored in the Setting element[name]
436        //! If there is not any sub-element named #name, this method returns false.
437        template<class T> static bool get ( T &instance, const Setting &element, const string &name, SettingPresence settingPresence = optional ) {
438                if ( !element.exists ( name ) ) {
439                        if ( settingPresence == optional )
440                                return false;
441                        else
442                                throw UISettingException ( "UIException: the compulsory Setting named \"" + name + "\" is missing.", element );
443                }
444
445                from_setting ( instance, to_child_setting ( element, name ) );
446                return true;
447        }
448
449        //! The existing instance of type T is initialized with values stored in the Setting element[index]
450        //! If there is not any sub-element indexed by #index, this method returns false.
451        template<class T> static bool get ( T &instance, const Setting &element, const int index, SettingPresence settingPresence = optional ) {
452                if ( element.getLength() <= index ) {
453                        if ( settingPresence == optional )
454                                return false;
455                        else {
456                                stringstream stream;
457                                stream << "UIException: the compulsory Setting with the index " << index << " is missing.";
458                                stream << index;
459                                throw UISettingException (stream.str(), element );
460                        }
461                }
462
463                from_setting ( instance, to_child_setting ( element, index ) );
464                return true;
465        }
466
467        //! The existing instance of type T is initialized with values stored in the Setting element directly
468        template<class T> static bool get ( T &instance, const Setting &element ) {
469                from_setting ( instance, element );
470                return true;
471        }
472        //!@}
473
474        //! \name Initialization of arrays Array<T>
475        //!@{
476        //! The type T has to be int, double, string, vec, ivec or mat, or pointer to any root descendant.
477
478        //! The existing array of type T is initialized with values stored in the Setting element[name]
479        //! If there is not any sub-element named #name, this method returns false.
480        template<class T> static bool get ( Array<T> &array_to_load, const Setting &element, const string &name, SettingPresence settingPresence = optional ) {
481                if ( !element.exists ( name ) )
482                        return false;
483
484                from_setting ( array_to_load, to_child_setting ( element, name ) );
485                return true;
486        }
487
488        //! The existing array of type T is initialized with values stored in the Setting element[index]
489        //! If there is not any sub-element indexed by #index, this method returns false.
490        template<class T> static bool get ( Array<T> &array_to_load, const Setting &element, const int index, SettingPresence settingPresence = optional ) {
491                if ( element.getLength() <= index )
492                        return false;
493
494                from_setting ( array_to_load, to_child_setting ( element, index ) );
495                return true;
496        }
497
498        //! The existing array of type T is initialized with values stored in the Setting element
499        template<class T> static bool get ( Array<T> &array_to_load, const Setting &element ) {
500                from_setting ( array_to_load, element );
501                return true;
502        }
503        //!@}
504
505        //! \name Serialization of objects and structures into a new Setting
506        //!@{
507        //! The new child Setting can be accessed either by its name - if some name is passed as a parameter -
508        //! or by its integer index. In that case, the new element is added at the very end of the current list of child Settings.
509
510        //! A root descendant instance is stored in the new child Setting appended to the passed element
511        template< class T> static void save ( const T * const instance, Setting &element, const string &name = "" ) {
512                Setting &set = ( name == "" ) ? element.add ( Setting::TypeGroup )
513                               : element.add ( name, Setting::TypeGroup );
514
515                const string &class_name = MappedUI::retrieve_class_name ( &typeid ( *instance ) );
516
517                // add attribute "class"
518                Setting &type = set.add ( "class", Setting::TypeString );
519                type = class_name;
520
521                try {
522                        instance->to_setting ( set );
523                } catch ( SettingException sttng_xcptn ) {
524                        string msg = "UIException: method ";
525                        msg += class_name;
526                        msg += ".to_setting(Setting&) has thrown a SettingException.";
527                        throw UISettingException(msg, sttng_xcptn.getPath());
528                }
529        }
530
531        template< class T> static void save ( const shared_ptr<T> &instance, Setting &element, const string &name = "" ) {
532                save<T> ( instance.get(), element, name );
533        }
534
535        //! An Array<T> instance is stored in the new child Setting appended to the passed element
536        template<class T> static void save ( const Array<T> &array_to_save, Setting &element, const string &name = "" ) {
537                assert_type ( element, Setting::TypeGroup );
538                Setting &list = ( name == "" ) ? element.add ( Setting::TypeList )
539                                : element.add ( name, Setting::TypeList );
540                for ( int i = 0; i < array_to_save.length(); i++ )
541                        save ( array_to_save ( i ), list );
542        }
543
544        //! A matrix(of type mat) is stored in the new child Setting appended to the passed element
545        static void save ( const mat &matrix, Setting &element, const string &name = "" );
546
547        //! An integer vector (of type ivec) is stored in the new child Setting appended to the passed element
548        static void save ( const ivec &vec, Setting &element, const string &name = "" );
549
550        //! A double vector (of type vec) is stored in the new child Setting appended to the passed element
551        static void save ( const vec &vector, Setting &element, const string &name = "" );
552
553        //! A string is stored in the new child Setting appended to the passed element
554        static void save ( const string &str, Setting &element, const string &name = "" );
555
556        //! An integer is stored in the new child Setting appended to the passed element
557        static void save ( const int &integer, Setting &element, const string &name = "" );
558
559        //! A double is stored in the new child Setting appended to the passed element
560        static void save ( const double &real, Setting &element, const string &name = "" );
561        //!@}
562
563};
564
565
566//! The only UI descendant class which is not intended for direct use. It should be accessed within the UIREGISTER macro only.
567//! \ref ui_page
568template<typename T> class ParticularUI : private UI {
569public:
570        //! Constructor used by the UIREGISTER macro.
571        ParticularUI<T> ( const string &class_name ) : UI ( class_name, &typeid ( T ) ) {};
572
573        //! A method returning a brand new instance of class T, this method is the reason why there have to be a parameterless constructor in class T
574        root* new_instance() const {
575                return new T();
576        }
577};
578
579}
580
581/*!
582  \def UIREGISTER(class_name)
583  \brief Macro for registration of class into map of user-infos, registered class is scriptable using UI static methods
584
585  Argument \a class_name has to be a descendant of root class and also to have a default constructor.
586  This macro should be used in header file, immediately after a class declaration.
587
588  \ref ui_page
589*/
590#ifndef BDMLIB
591#define UIREGISTER(class_name) static bdm::ParticularUI<class_name> UI##class_name(#class_name)
592#else
593#define UIREGISTER(class_name)
594#endif
595
596//! Instrumental macro for UIREGISTER2
597#define QUOTEME(x) #x
598
599/*!
600  \def UIREGISTER2(class_name,template_name)
601  \brief Variant of UIREGISTER for templated classes
602
603  Technical meann of registering UIREGISTER(class_name<template_name>).
604
605  \ref ui_page
606 */
607#ifndef BDMLIB
608#define UIREGISTER2(class_name, temp_name) static bdm::ParticularUI<class_name<temp_name> > UI##class_name##_##temp_name( QUOTEME(class_name<temp_name>) )
609#else
610#define UIREGISTER2(class_name,temp_name)
611#endif
612
613#endif // #ifndef USER_INFO_H
Note: See TracBrowser for help on using the browser.