summaryrefslogtreecommitdiffstats
path: root/src/template.h
blob: ef9792c51eb0367db8dc14a6783f8331dcc4616d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/******************************************************************************
 *
 * Copyright (C) 1997-2014 by Dimitri van Heesch.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation under the terms of the GNU General Public License is hereby
 * granted. No representations are made about the suitability of this software
 * for any purpose. It is provided "as is" without express or implied warranty.
 * See the GNU General Public License for more details.
 *
 * Documents produced by Doxygen are derivative works derived from the
 * input used in their production; they are not affected by this license.
 *
 */

#ifndef TEMPLATE_H
#define TEMPLATE_H

#include <qcstring.h>
#include <qvaluelist.h>

class FTextStream;

class TemplateListIntf;
class TemplateStructIntf;
class TemplateEngine;

/** @defgroup template_api Template API
 *
 *  This is the API for a
 *  <a href="https://docs.djangoproject.com/en/1.6/topics/templates/">Django</a>
 *  compatible template system written in C++.
 *  It is somewhat inspired by Stephen Kelly's
 *  <a href="http://www.gitorious.org/grantlee/pages/Home">Grantlee</a>.
 *
 *  A template is simply a text file.
 *  A template contains \b variables, which get replaced with values when the
 *  template is evaluated, and \b tags, which control the logic of the template.
 *
 *  Variables look like this: `{{ variable }}`
 *  When the template engine encounters a variable, it evaluates that variable and
 *  replaces it with the result. Variable names consist of any combination of
 *  alphanumeric characters and the underscore ("_").
 *  Use a dot (.) to access attributes of a structured variable.
 *
 *  One can modify variables for display by using \b filters, for example:
 *  `{{ value|default:"nothing" }}`
 *
 *  Tags look like this: `{% tag %}`. Tags are more complex than variables:
 *  Some create text in the output, some control flow by performing loops or logic,
 *  and some load external information into the template to be used by later variables.
 *
 *  To comment-out part of a line in a template, use the comment syntax:
 *  `{# comment text #}`.
 *
 *  Supported Django tags:
 *  - `for ... empty ... endfor`
 *  - `if ... else ... endif`
 *  - `block ... endblock`
 *  - `extend`
 *  - `include`
 *  - `with ... endwith`
 *  - `spaceless ... endspaceless`
 *  - `cycle`
 *
 *  Extension tags:
 *  - `create` which instantiates a template and writes the result to a file.
 *     The syntax is `{% create 'filename' from 'template' %}`.
 *  - `recursetree`
 *  - `markers`
 *  - `msg` ... `endmsg`
 *  - `set`
 *
 *  Supported Django filters:
 *  - `default`
 *  - `length`
 *  - `add`
 *  - `divisibleby`
 *
 *  Extension filters:
 *  - `stripPath`
 *  - `nowrap`
 *  - `prepend`
 *  - `append`
 *
 *  @{
 */

/** @brief Variant type which can hold one value of a fixed set of types. */
class TemplateVariant
{
  public:
    /** @brief Helper class to create a delegate that can store a function/method call. */
    class Delegate
    {
      public:
        /** Callback type to use when creating a delegate from a function. */
        typedef TemplateVariant (*StubType)(const void *obj, const QValueList<TemplateVariant> &args);

        Delegate() : m_objectPtr(0) , m_stubPtr(0) {}

        /** Creates a delegate given an object. The method to call is passed as a template parameter */
        template <class T, TemplateVariant (T::*TMethod)(const QValueList<TemplateVariant> &) const>
        static Delegate fromMethod(const T* objectPtr)
        {
          Delegate d;
          d.m_objectPtr = objectPtr;
          d.m_stubPtr   = &methodStub<T, TMethod>;
          return d;
        }
        /** Creates a delegate given an object, and a plain function. */
        static Delegate fromFunction(const void *obj,StubType func)
        {
          Delegate d;
          d.m_objectPtr = obj;
          d.m_stubPtr = func;
          return d;
        }

        /** Invokes the function/method stored in the delegate */
        TemplateVariant operator()(const QValueList<TemplateVariant> &args) const
        {
          return (*m_stubPtr)(m_objectPtr, args);
        }

      private:
        const void* m_objectPtr;
        StubType    m_stubPtr;

        template <class T, TemplateVariant (T::*TMethod)(const QValueList<TemplateVariant> &) const>
        static TemplateVariant methodStub(const void* objectPtr, const QValueList<TemplateVariant> &args)
        {
          T* p = (T*)(objectPtr);
          return (p->*TMethod)(args);
        }
    };

    /** Types of data that can be stored in a TemplateVariant */
    enum Type { None, Bool, Integer, String, Struct, List, Function };

    /** Returns the type of the value stored in the variant */
    Type type() const;

    /** Return a string representation of the type of the value stored in the variant */
    QCString typeAsString() const;

    /** Returns TRUE if the variant holds a valid value, or FALSE otherwise */
    bool isValid() const;

    /** Constructs an invalid variant. */
    TemplateVariant();

    /** Constructs a new variant with a boolean value \a b. */
    explicit TemplateVariant(bool b);

    /** Constructs a new variant with a integer value \a v. */
    TemplateVariant(int v);

    /** Constructs a new variant with a string value \a s. */
    TemplateVariant(const char *s,bool raw=FALSE);

    /** Constructs a new variant with a string value \a s. */
    TemplateVariant(const QCString &s,bool raw=FALSE);

    /** Constructs a new variant with a struct value \a s.
     *  @note. The variant will hold a reference to the object.
     */
    TemplateVariant(TemplateStructIntf *s);

    /** Constructs a new variant with a list value \a l.
     *  @note. The variant will hold a reference to the object.
     */
    TemplateVariant(TemplateListIntf *l);

    /** Constructs a new variant which represents a method call
     *  @param[in] delegate Delegate object to invoke when
     *             calling call() on this variant.
     *  @note Use TemplateVariant::Delegate::fromMethod() and
     *  TemplateVariant::Delegate::fromFunction() to create
     *  Delegate objects.
     */
    TemplateVariant(const Delegate &delegate);

    /** Destroys the Variant object */
    ~TemplateVariant();

    /** Constructs a copy of the variant, \a v,
     *  passed as the argument to this constructor.
     */
    TemplateVariant(const TemplateVariant &v);

    /** Assigns the value of the variant \a v to this variant. */
    TemplateVariant &operator=(const TemplateVariant &v);

    /** Compares this QVariant with v and returns true if they are equal;
     *  otherwise returns false.
     */
    bool operator==(TemplateVariant &other);

    /** Returns the variant as a string. */
    QCString            toString() const;

    /** Returns the variant as a boolean. */
    bool                toBool() const;

    /** Returns the variant as an integer. */
    int                 toInt() const;

    /** Returns the pointer to list referenced by this variant
     *  or 0 if this variant does not have list type.
     */
    TemplateListIntf   *toList() const;

    /** Returns the pointer to struct referenced by this variant
     *  or 0 if this variant does not have struct type.
     */
    TemplateStructIntf *toStruct() const;

    /** Return the result of apply this function with \a args.
     *  Returns an empty string if the variant type is not a function.
     */
    TemplateVariant call(const QValueList<TemplateVariant> &args);

    /** Sets whether or not the value of the Variant should be
     *  escaped or written as-is (raw).
     *  @param[in] b TRUE means write as-is, FALSE means apply escaping.
     */
    void setRaw(bool b);

    /** Returns whether or not the value of the Value is raw.
     *  @see setRaw()
     */
    bool raw() const;

  private:
    class Private;
    Private *p;
};

//------------------------------------------------------------------------

template<class T> class TemplateAutoRef
{
  public:
    TemplateAutoRef(T *obj) : m_obj(obj)
    {
      m_obj->addRef();
    }
   ~TemplateAutoRef()
    {
      m_obj->release();
    }
    T &operator*() const { return *m_obj; }
    T *operator->() const { return m_obj; }
    T *get() const { return m_obj; }

  private:
   T *m_obj;
};

//------------------------------------------------------------------------

/** @brief Abstract read-only interface for a context value of type list.
 *  @note The values of the list are TemplateVariants.
 */
class TemplateListIntf
{
  public:
    /** @brief Abstract interface for a iterator of a list. */
    class ConstIterator
    {
      public:
        /** Destructor for the iterator */
        virtual ~ConstIterator() {}
        /** Moves iterator to the first element in the list */
        virtual void toFirst() = 0;
        /** Moves iterator to the last element in the list */
        virtual void toLast() = 0;
        /** Moves iterator to the next element in the list */
        virtual void toNext() = 0;
        /** Moves iterator to the previous element in the list */
        virtual void toPrev() = 0;
        /* Returns TRUE if the iterator points to a valid element
         * in the list, or FALSE otherwise.
         * If TRUE is returned, the value pointed to be the
         * iterator is assigned to \a v.
         */
        virtual bool current(TemplateVariant &v) const = 0;
    };

    /** Destroys the list */
    virtual ~TemplateListIntf() {}

    /** Returns the number of elements in the list */
    virtual int count() const = 0;

    /** Returns the element at index position \a index. */
    virtual TemplateVariant  at(int index) const = 0;

    /** Creates a new iterator for this list.
     *  @note the user should call delete on the returned pointer.
     */
    virtual TemplateListIntf::ConstIterator *createIterator() const = 0;

    /** Increase object's reference count */
    virtual int addRef() = 0;

    /** Decreases object's referenc count, destroy object if 0 */
    virtual int release() = 0;
};

/** @brief Default implementation of a context value of type list. */
class TemplateList : public TemplateListIntf
{
  public:
    // TemplateListIntf methods
    virtual int  count() const;
    virtual TemplateVariant at(int index) const;
    virtual TemplateListIntf::ConstIterator *createIterator() const;
    virtual int addRef();
    virtual int release();

    /** Creates an instance with ref count set to 0 */
    static TemplateList *alloc();

    /** Appends element \a v to the end of the list */
    virtual void append(const TemplateVariant &v);

  private:
    /** Creates a list */
    TemplateList();
    /** Destroys the list */
   ~TemplateList();

    friend class TemplateListConstIterator;
    class Private;
    Private *p;
};

//------------------------------------------------------------------------

/** @brief Abstract interface for a context value of type struct. */
class TemplateStructIntf
{
  public:
    /** Destroys the struct */
    virtual ~TemplateStructIntf() {}

    /** Gets the value for a field name.
     *  @param[in] name The name of the field.
     */
    virtual TemplateVariant get(const char *name) const = 0;

    /** Increase object's reference count */
    virtual int addRef() = 0;

    /** Decreases object's referenc count, destroy object if 0 */
    virtual int release() = 0;
};


/** @brief Default implementation of a context value of type struct. */
class TemplateStruct : public TemplateStructIntf
{
  public:
    // TemplateStructIntf methods
    virtual TemplateVariant get(const char *name) const;
    virtual int addRef();
    virtual int release();

    /** Creates an instance with ref count set to 0. */
    static TemplateStruct *alloc();

    /** Sets the value the field of a struct
     *  @param[in] name The name of the field.
     *  @param[in] v The value to set.
     */
    virtual void set(const char *name,const TemplateVariant &v);


  private:
    /** Creates a struct */
    TemplateStruct();
    /** Destroys the struct */
    virtual ~TemplateStruct();

    class Private;
    Private *p;
};

//------------------------------------------------------------------------

/** @brief Interface used to escape characters in a string */
class TemplateEscapeIntf
{
  public:
    /** Returns the \a input after escaping certain characters */
    virtual QCString escape(const QCString &input) = 0;
};

//------------------------------------------------------------------------

/** @brief Interface used to remove redundant spaces inside a spaceless block */
class TemplateSpacelessIntf
{
  public:
    /** Returns the \a input after removing redundant whitespace */
    virtual QCString remove(const QCString &input) = 0;
    /** Reset filter state */
    virtual void reset() = 0;
};

//------------------------------------------------------------------------

/** @brief Abstract interface for a template context.
 *
 *  A Context consists of a stack of dictionaries.
 *  A dictionary consists of a mapping of string keys onto TemplateVariant values.
 *  A key is searched starting with the dictionary at the top of the stack
 *  and searching downwards until it is found. The stack is used to create
 *  local scopes.
 *  @note This object must be created by TemplateEngine::createContext()
 */
class TemplateContext
{
  public:
    virtual ~TemplateContext() {}

    /** Push a new scope on the stack. */
    virtual void push() = 0;

    /** Pop the current scope from the stack. */
    virtual void pop() = 0;

    /** Sets a value in the current scope.
     *  @param[in] name The name of the value; the key in the dictionary.
     *  @param[in] v The value associated with the key.
     *  @note When a given key is already present,
     *  its value will be replaced by \a v
     */
    virtual void set(const char *name,const TemplateVariant &v) = 0;

    /** Gets the value for a given key
     *  @param[in] name The name of key.
     *  @returns The value, which can be an invalid variant in case the
     *  key was not found.
     */
    virtual TemplateVariant get(const QCString &name) const = 0;

    /** Returns a pointer to the value corresponding to a given key.
     *  @param[in] name The name of key.
     *  @returns A pointer to the value, or 0 in case the key was not found.
     */
    virtual const TemplateVariant *getRef(const QCString &name) const = 0;

    /** When files are create (i.e. by {% create ... %}) they written
     *  to the directory \a dir.
     */
    virtual void setOutputDirectory(const QCString &dir) = 0;

    /** Sets the interface that will be used for escaping the result
     *  of variable expansion before writing it to the output.
     */
    virtual void setEscapeIntf(const QCString &extension, TemplateEscapeIntf *intf) = 0;

    /** Sets the interface that will be used inside a spaceless block
     *  to remove any redundant whitespace.
     */
    virtual void setSpacelessIntf(TemplateSpacelessIntf *intf) = 0;
};

//------------------------------------------------------------------------

/** @brief Abstract interface for a template.
 *  @note Must be created and is deleted by the TemplateEngine
 */
class Template
{
  public:
    /** Destructor */
    virtual ~Template() {}

    /** Renders a template instance to a stream.
     *  @param[in] ts The text stream to write the results to.
     *  @param[in] c The context containing data that can be used
     *  when instantiating the template.
     */
    virtual void render(FTextStream &ts,TemplateContext *c) = 0;
};

//------------------------------------------------------------------------

/** @brief Engine to create templates and template contexts. */
class TemplateEngine
{
  public:
    /** Create a template engine. */
    TemplateEngine();

    /** Destroys the template engine. */
   ~TemplateEngine();

    /** Creates a new context that can be using to render a template.
     *  @see Template::render()
     */
    TemplateContext *createContext() const;

    /** Destroys a context created via createContext().
     *  @param[in] ctx The context.
     */
    void destroyContext(TemplateContext *ctx);

    /** Creates a new template whole contents are in a file.
     *  @param[in] fileName The name of the file containing the
     *             template data
     *  @param[in] fromLine The line number of the statement that triggered the load
     *  @return the new template, the caller will be the owner.
     */
    Template *loadByName(const QCString &fileName,int fromLine);

    /** Indicates that template \a t is no longer needed. The engine
     *  may decide to delete it.
     */
    void unload(Template *t);

    void printIncludeContext(const char *fileName,int line) const;

  private:
    friend class TemplateNodeBlock;
    void enterBlock(const QCString &fileName,const QCString &blockName,int line);
    void leaveBlock();

    class Private;
    Private *p;
};

/** @} */

#endif