id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28,327
|
host.h
|
openMVG_openMVG/src/nonFree/sift/vl/host.h
|
/** @file host.h
** @brief Host
** @author Andrea Vedaldi
**/
/*
Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
#ifndef VL_HOST_H
#define VL_HOST_H
/** ------------------------------------------------------------------
** @name Configuration options
** @{ */
#if defined __clang__
#define VL_DISABLE_THREADS
#endif
#if defined(__DOXYGEN__)
#define VL_DISABLE_THREADS
#define VL_DISABLE_SSE2
#endif
/** @} */
/** ------------------------------------------------------------------
** @name Defining functions
** @{ */
#if defined(__DOXYGEN__)
#define VL_EXPORT
#define VL_INLINE
#endif
/** @} */
/** ------------------------------------------------------------------
** @name C preprocessor helper macros
** @{ */
/** @brief Convert the argument to a string
**
** @param x value to be stringified.
**
** This macro stringifies the argument @a x by means of the
** <code>#</code> prerpocessor operator.
**
** The standard C preprocessor does not prescan arguments which are
** stringified, so
**
** @code
** #define A B
** char const * str = VL_STRINGIFY(A) ;
** @endcode
**
** initializes <code>str</code> with a pointer to the string
** <code>"A"</code>, which mihgt be unexpected. To fix this issue,
** you can use ::VL_XSTRINGIFY.
**
** @sa ::VL_XSTRINGIFY
**/
#define VL_STRINGIFY(x) # x
/** @brief Expand and then convert the argument to a string
**
** @param x value to be macro-expanded and converted.
**
** This macro macro-expands the argument @a x and stringifies the
** result of the expansion. For instance
**
** @code
** #define A B
** char const * str = VL_STRINGIFY(A) ;
** @endcode
**
** initializes <code>str</code> with a pointer to the string
** <code>"B"</code>.
**
** @sa ::VL_STRINGIFY
**/
#define VL_XSTRINGIFY(x) VL_STRINGIFY(x)
/** @brief Concatenate two arguments into a lexical unit
**
** @param x first argument to be concatenated.
** @param y second argument to be concatenated.
**
** This macro concatenates its arguments into a single lexical unit
** by means of the <code>##</code> preprocessor operator. Notice that
** arguments concatenated by <code>##</code> are not pre-expanded by
** the C preprocessor. To macro-expand the arguments and then
** concatenate them,use ::VL_XCAT.
**
** @see ::VL_XCAT
**/
#define VL_CAT(x,y) x ## y
/** @brief Expand and then concatenate two arguments into a lexical unit
**
** @param x first argument to be concatenated.
** @param y second argument to be concatenated.
**
** This macro is the same as ::VL_CAT, except that the arguments are
** macro expanded before being concatenated.
**
** @see ::VL_CAT
**/
#define VL_XCAT(x,y) VL_CAT(x,y)
/** @brief Expand and then concatenate three arguments into a lexical unit
**
** @param x first argument to be concatenated.
** @param y second argument to be concatenated.
** @param z third argument to be concatenated.
**
** This macro is the same as ::VL_XCAT, except that it has three arguments.
**
** @see ::VL_XCAT
**/
#define VL_XCAT3(x,y,z) VL_XCAT(VL_XCAT(x,y),z)
/** @brief Expand and then concatenate four arguments into a lexical unit
**
** @param x first argument to be concatenated.
** @param y second argument to be concatenated.
** @param z third argument to be concatenated.
** @param u fourth argument to be concatenated.
**
** This macro is the same as ::VL_XCAT, except that it has four arguments.
**
** @see ::VL_XCAT
**/
#define VL_XCAT4(x,y,z,u) VL_XCAT(VL_XCAT3(x,y,z),u)
/** @brief Expand and then concatenate five arguments into a lexical unit
**
** @param x first argument to be concatenated.
** @param y second argument to be concatenated.
** @param z third argument to be concatenated.
** @param u fourth argument to be concatenated.
** @param v fifth argument to be concatenated.
**
** This macro is the same as ::VL_XCAT, except that it has five arguments.
**
** @see ::VL_XCAT
**/
#define VL_XCAT5(x,y,z,u,v) VL_XCAT(VL_XCAT4(x,y,z,u),v)
/** @} */
/** @brief Convert a boolean to "yes" or "no" strings
** @param x boolean to convert.
** A pointer to either the string "yes" (if @a x is true)
** or the string "no".
** @par Example
** @code
** VL_PRINTF("Is x true? %s.", VL_YESNO(x))
** @endcode
**/
#define VL_YESNO(x) ((x)?"yes":"no")
/*
The following macros identify the host OS, architecture and compiler.
They are derived from http://predef.sourceforge.net/
*/
/** @name Identifying the host operating system
** @{ */
#if defined(linux) || \
defined(__linux) || \
defined(__linux__) || \
defined(__DOXYGEN__)
#define VL_OS_LINUX 1
#endif
#if (defined(__APPLE__) & defined(__MACH__)) || \
defined(__DOXYGEN__)
#define VL_OS_MACOSX 1
#endif
#if defined(__WIN32__) || \
defined(_WIN32) || \
defined(__DOXYGEN__)
#define VL_OS_WIN 1
#endif
#if defined(_WIN64) || \
defined(__DOXYGEN__)
#define VL_OS_WIN64 1
#endif
/** @} */
/** @name Identifying the host threading library
** @{ */
#if defined(VL_OS_MACOSX) || defined(VL_OS_LINUX) || \
defined(__DOXYGEN__)
#define VL_THREADS_POSIX 1
#endif
#if defined(VL_OS_WIN) || defined(VL_OS_WIN64) || \
defined(__DOXYGEN__)
#define VL_THREADS_WIN 1
#endif
/** @} */
/** @name Identifying the host compiler
** @{ */
#if defined(__GNUC__) || defined(__DOXYGEN__)
# if defined(__GNUC_PATCHLEVEL__)
# define VL_COMPILER_GNUC (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
# else
# define VL_COMPILER_GNUC (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100)
# endif
#endif
#if defined(_MSC_VER) || defined(__DOXYGEN__)
#define VL_COMPILER_MSC _MSC_VER
#endif
#if defined(__LCC__) || defined(__DOXYGEN__)
#warning "LCC support is experimental!"
#define VL_COMPILER_LCC 1
#endif
/** @} */
/** @name Identifying the host CPU architecture
** @{ */
#if defined(i386) || \
defined(__i386__) || \
defined(__DOXYGEN__)
#define VL_ARCH_IX86 300
#elif defined(__i486__)
#define VL_ARCH_IX86 400
#elif defined(__i586__)
#define VL_ARCH_IX86 500
#elif defined(__i686__)
#define VL_ARCH_IX86 600
#elif defined(_M_IX86)
#define VL_ARCH_IX86 _M_IX86
#endif
#if defined(_M_X64) || \
defined(__amd64__) || \
defined(__amd64) || \
defined(__x86_64) || \
defined(__x86_64)
#define VL_ARCH_X64
#endif
#if defined(__ia64__) || \
defined(_IA64) || \
defined(__IA64) || \
defined(__ia64) || \
defined(_M_IA64) || \
defined(__DOXYGEN__)
#define VL_ARCH_IA64
#endif
/** @} */
/** @name Identifying the host data model
** @{ */
#if defined(__LLP64__) || \
defined(__LLP64) || \
defined(__LLP64) || \
(defined(VL_COMPILER_MSC) & defined(VL_OS_WIN64)) || \
(defined(VL_COMPILER_LCC) & defined(VL_OS_WIN64)) || \
defined(__DOXYGEN__)
#define VL_COMPILER_LLP64
#endif
#if defined(__LP64__) || \
defined(__LP64) || \
defined(__LP64) || \
(defined(VL_OS_MACOSX) & defined(VL_ARCH_IA64)) || \
defined(__DOXYGEN__)
#define VL_COMPILER_LP64
#endif
#if (!defined(VL_COMPILER_LLP64) & !defined(VL_COMPILER_LP64)) || \
defined(__DOXYGEN__)
#define VL_COMPILER_ILP32
#endif
/** @} */
/** @name Identifying the host endianness
** @{ */
#if defined(__LITTLE_ENDIAN__) || \
defined(VL_ARCH_IX86) || \
defined(VL_ARCH_IA64) || \
defined(VL_ARCH_X64) || \
defined(__DOXYGEN__)
#define VL_ARCH_LITTLE_ENDIAN
#endif
#if defined(__DOXYGEN__) || \
!defined(VL_ARCH_LITTLE_ENDIAN)
#define VL_ARCH_BIG_ENDIAN
#endif
/** @} */
#if defined(VL_COMPILER_MSC) & ! defined(__DOXYGEN__)
# define VL_UNUSED
# define VL_INLINE static __inline
#if _MSC_VER < 1900
# define snprintf _snprintf
#endif
# define isnan _isnan
# ifdef VL_BUILD_DLL
# ifdef __cplusplus
# define VL_EXPORT extern "C" __declspec(dllexport)
# else
# define VL_EXPORT extern __declspec(dllexport)
# endif
# else
# ifdef __cplusplus
# define VL_EXPORT extern "C" //__declspec(dllimport)
# else
# define VL_EXPORT extern //__declspec(dllimport)
# endif
# endif
#endif
#if defined(VL_COMPILER_LCC) & ! defined(__DOXYGEN__)
# define VL_UNUSED
# define VL_INLINE static __inline
# define snprintf _snprintf
# define isnan _isnan
VL_INLINE float fabsf(float x) { return (float) fabs((double) x) ; }
# ifdef VL_BUILD_DLL
# define VL_EXPORT extern __declspec(dllexport)
# else
# define VL_EXPORT extern
# endif
#endif
#if defined(VL_COMPILER_GNUC) & ! defined(__DOXYGEN__)
# define VL_UNUSED __attribute__((unused))
# define VL_INLINE static __inline__
# ifdef VL_BUILD_DLL
# ifdef __cplusplus
# define VL_EXPORT __attribute__((visibility ("default"))) extern "C"
# else
# define VL_EXPORT __attribute__((visibility ("default"))) extern
# endif
# else
# ifdef __cplusplus
# define VL_EXPORT extern "C"
# else
# define VL_EXPORT extern
# endif
# endif
#endif
# if defined(VL_OS_MACOSX)
# undef VL_EXPORT
# define VL_EXPORT extern
#endif
VL_EXPORT char * vl_static_configuration_to_string_copy () ;
/** ------------------------------------------------------------------
** @name Atomic data types
** @{
**/
#define VL_TRUE 1 /**< @brief @c true (1) constant */
#define VL_FALSE 0 /**< @brief @c false (0) constant */
#if defined(VL_COMPILER_LP64) || defined(VL_COMPILER_LLP64)
typedef long long vl_int64 ; /**< @brief Signed 64-bit integer. */
typedef int vl_int32 ; /**< @brief Signed 32-bit integer. */
typedef short vl_int16 ; /**< @brief Signed 16-bit integer. */
typedef char vl_int8 ; /**< @brief Signed 8-bit integer. */
typedef long long unsigned vl_uint64 ; /**< @brief Unsigned 64-bit integer. */
typedef int unsigned vl_uint32 ; /**< @brief Unsigned 32-bit integer. */
typedef short unsigned vl_uint16 ; /**< @brief Unsigned 16-bit integer. */
typedef char unsigned vl_uint8 ; /**< @brief Unsigned 8-bit integer. */
typedef int vl_int ; /**< @brief Same as @c int. */
typedef unsigned int vl_uint ; /**< @brief Same as <code>unsigned int</code>. */
typedef int vl_bool ; /**< @brief Boolean. */
typedef vl_int64 vl_intptr ; /**< @brief Integer holding a pointer. */
typedef vl_uint64 vl_uintptr ; /**< @brief Unsigned integer holding a pointer. */
typedef vl_uint64 vl_size ; /**< @brief Unsigned integer holding the size of a memory block. */
typedef vl_int64 vl_index ; /**< @brief Signed version of ::vl_size and ::vl_uindex */
typedef vl_uint64 vl_uindex ; /**< @brief Same as ::vl_size */
#endif
#if defined(VL_COMPILER_ILP32)
#ifdef VL_COMPILER_MSC
typedef __int64 vl_int64 ;
#else
typedef long long vl_int64 ;
#endif
typedef int vl_int32 ;
typedef short vl_int16 ;
typedef char vl_int8 ;
#ifdef VL_COMPILER_MSC
typedef __int64 unsigned vl_uint64 ;
#else
typedef long long unsigned vl_uint64 ;
#endif
typedef int unsigned vl_uint32 ;
typedef short unsigned vl_uint16 ;
typedef char unsigned vl_uint8 ;
typedef int vl_int ;
typedef unsigned int vl_uint ;
typedef int vl_bool ;
typedef vl_int32 vl_intptr ;
typedef vl_uint32 vl_uintptr ;
typedef vl_uint32 vl_size ;
typedef vl_int32 vl_index ;
typedef vl_uint32 vl_uindex ;
#endif
/** @} */
/** ------------------------------------------------------------------
** @name Printing the atomic data types
** @{ */
/* Lengths only: */
/** @def VL_FL_INT64
** @brief @c printf length flag for ::vl_int64 and ::vl_uint64.
**/
/** @def VL_FL_INT32
** @brief @c printf length flag for ::vl_int32 and ::vl_uint32.
**/
/** @def VL_FL_INT16
** @brief @c printf length flag for ::vl_int16 and ::vl_uint16.
**/
/** @def VL_FL_INT8
** @brief @c printf length flag for ::vl_int8 and ::vl_uint8.
**/
/** @def VL_FL_INDEX
** @brief @c printf length flag for ::vl_index and ::vl_uindex
**/
#ifdef VL_COMPILER_MSC
#define VL_FL_INT64 "I64"
#else
#define VL_FL_INT64 "ll"
#endif
#define VL_FL_INT32 ""
#define VL_FL_INT16 "h"
#define VL_FL_INT8 "hh"
#if defined(VL_COMPILER_LP64) || defined(VL_COMPILER_LLP64)
#define VL_FL_INDEX VL_FL_INT64
#endif
#if defined(VL_COMPILER_ILP32)
#define VL_FL_INDEX VL_FL_INT32
#endif
/* Formats (but not conversions!): */
/** @def VL_FMT_SIZE
** @brief @c printf flag for ::vl_size
**/
/** @def VL_FMT_INDEX
** @brief @c printf flag for ::vl_index
**/
/** @def VL_FMT_UINDEX
** @brief @c printf flag for ::vl_uindex
**/
/** @def VL_FMT_INTPTR
** @brief @c printf flag for ::vl_intptr
**/
/** @def VL_FMT_UINTPTR
** @brief @c printf flag for ::vl_uintptr
**/
#define VL_FMT_INDEX VL_FL_INDEX "d"
#define VL_FMT_INTPTR VL_FMT_INDEX
#define VL_FMT_UINDEX VL_FL_INDEX "u"
#define VL_FMT_SIZE VL_FMT_UINDEX
#define VL_FMT_UINTPTR VL_FMT_UINDEX
/** @} */
/** ------------------------------------------------------------------
** @name Atomic data types limits
** @{ */
/** @brief Largest integer (math constant) */
#define VL_BIG_INT 0x7FFFFFFFL
/** @brief Smallest integer (math constant) */
#define VL_SMALL_INT (- VL_BIG_INT - 1)
/** @brief Largest unsigned integer (math constant) */
#define VL_BIG_UINT 0xFFFFFFFFUL
/** @} */
/** ------------------------------------------------------------------
** @name Endianness detection and conversion
** @{
**/
VL_INLINE void vl_swap_host_big_endianness_8 (void *dst, void* src) ;
VL_INLINE void vl_swap_host_big_endianness_4 (void *dst, void* src) ;
VL_INLINE void vl_swap_host_big_endianness_2 (void *dst, void* src) ;
/** @} */
/** ------------------------------------------------------------------
** @name Obtaining host info at run time
** @{ */
typedef struct _VlX86CpuInfo
{
union {
char string [0x20] ;
vl_uint32 words [0x20 / 4] ;
} vendor ;
vl_bool hasSSE42 ;
vl_bool hasSSE41 ;
vl_bool hasSSE3 ;
vl_bool hasSSE2 ;
vl_bool hasSSE ;
vl_bool hasMMX ;
} VlX86CpuInfo ;
void _vl_x86cpu_info_init (VlX86CpuInfo *self) ;
char * _vl_x86cpu_info_to_string_copy (VlX86CpuInfo const *self) ;
/** @} */
/** ------------------------------------------------------------------
** @brief Host <-> big endian transformation for 8-bytes value
**
** @param dst destination 8-byte buffer.
** @param src source 8-byte bufffer.
** @see @ref host-arch-endianness.
**/
VL_INLINE void
vl_swap_host_big_endianness_8 (void *dst, void* src)
{
char *dst_ = (char*) dst ;
char *src_ = (char*) src ;
#if defined(VL_ARCH_BIG_ENDIAN)
dst_ [0] = src_ [0] ;
dst_ [1] = src_ [1] ;
dst_ [2] = src_ [2] ;
dst_ [3] = src_ [3] ;
dst_ [4] = src_ [4] ;
dst_ [5] = src_ [5] ;
dst_ [6] = src_ [6] ;
dst_ [7] = src_ [7] ;
#else
dst_ [0] = src_ [7] ;
dst_ [1] = src_ [6] ;
dst_ [2] = src_ [5] ;
dst_ [3] = src_ [4] ;
dst_ [4] = src_ [3] ;
dst_ [5] = src_ [2] ;
dst_ [6] = src_ [1] ;
dst_ [7] = src_ [0] ;
#endif
}
/** ------------------------------------------------------------------
** @brief Host <-> big endian transformation for 4-bytes value
**
** @param dst destination 4-byte buffer.
** @param src source 4-byte bufffer.
** @sa @ref host-arch-endianness.
**/
VL_INLINE void
vl_swap_host_big_endianness_4 (void *dst, void* src)
{
char *dst_ = (char*) dst ;
char *src_ = (char*) src ;
#if defined(VL_ARCH_BIG_ENDIAN)
dst_ [0] = src_ [0] ;
dst_ [1] = src_ [1] ;
dst_ [2] = src_ [2] ;
dst_ [3] = src_ [3] ;
#else
dst_ [0] = src_ [3] ;
dst_ [1] = src_ [2] ;
dst_ [2] = src_ [1] ;
dst_ [3] = src_ [0] ;
#endif
}
/** ------------------------------------------------------------------
** @brief Host <-> big endian transformation for 2-bytes value
**
** @param dst destination 2-byte buffer.
** @param src source 2-byte bufffer.
** @see @ref host-arch-endianness.
**/
VL_INLINE void
vl_swap_host_big_endianness_2 (void *dst, void* src)
{
char *dst_ = (char*) dst ;
char *src_ = (char*) src ;
#if defined(VL_ARCH_BIG_ENDIAN)
dst_ [0] = src_ [0] ;
dst_ [1] = src_ [1] ;
#else
dst_ [0] = src_ [1] ;
dst_ [1] = src_ [0] ;
#endif
}
/* VL_HOST_H */
#endif
| 16,494
|
C++
|
.h
| 546
| 28.208791
| 108
| 0.606462
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| false
| false
| false
| false
| false
| false
|
28,329
|
imopv.h
|
openMVG_openMVG/src/nonFree/sift/vl/imopv.h
|
/** @file imopv.h
** @brief Vectorized image operations
** @author Andrea Vedaldi
**/
/*
Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
#ifndef VL_IMPOV_H
#define VL_IMPOV_H
#include "generic.h"
/** @name Image convolution flags
** @{ */
#define VL_PAD_BY_ZERO (0x0 << 0) /**< @brief Pad with zeroes. */
#define VL_PAD_BY_CONTINUITY (0x1 << 0) /**< @brief Pad by continuity. */
#define VL_PAD_MASK (0x3) /**< @brief Padding field selector. */
#define VL_TRANSPOSE (0x1 << 2) /**< @brief Transpose result. */
/** @} */
/** @name Image convolution
** @{ */
VL_EXPORT
void vl_imconvcol_vf (float* dst, vl_size dst_stride,
float const* src,
vl_size src_width, vl_size src_height, vl_size src_stride,
float const* filt, vl_index filt_begin, vl_index filt_end,
int step, unsigned int flags) ;
VL_EXPORT
void vl_imconvcol_vd (double* dst, vl_size dst_stride,
double const* src,
vl_size src_width, vl_size src_height, vl_size src_stride,
double const* filt, vl_index filt_begin, vl_index filt_end,
int step, unsigned int flags) ;
VL_EXPORT
void vl_imconvcoltri_f (float * dest, vl_size destStride,
float const * image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride,
vl_size filterSize,
vl_size step, int unsigned flags) ;
VL_EXPORT
void vl_imconvcoltri_d (double * dest, vl_size destStride,
double const * image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride,
vl_size filterSize,
vl_size step, int unsigned flags) ;
/** @} */
/** @name Integral image
** @{ */
VL_EXPORT
void vl_imintegral_f (float * integral, vl_size integralStride,
float const * image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride) ;
VL_EXPORT
void vl_imintegral_d (double * integral, vl_size integralStride,
double const * image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride) ;
VL_EXPORT
void vl_imintegral_i32 (vl_int32 * integral, vl_size integralStride,
vl_int32 const * image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride) ;
VL_EXPORT
void vl_imintegral_ui32 (vl_uint32 * integral, vl_size integralStride,
vl_uint32 const * image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride) ;
/** @} */
/** @name Distance transform */
/** @{ */
VL_EXPORT void
vl_image_distance_transform_d (double const * image,
vl_size numColumns,
vl_size numRows,
vl_size columnStride,
vl_size rowStride,
double * distanceTransform,
vl_uindex * indexes,
double coeff,
double offset) ;
VL_EXPORT void
vl_image_distance_transform_f (float const * image,
vl_size numColumns,
vl_size numRows,
vl_size columnStride,
vl_size rowStride,
float * distanceTransform,
vl_uindex * indexes,
float coeff,
float offset) ;
/** @} */
/* ---------------------------------------------------------------- */
/** @name Image smoothing */
/** @{ */
VL_EXPORT void
vl_imsmooth_f (float *smoothed, vl_size smoothedStride,
float const *image, vl_size width, vl_size height, vl_size stride,
double sigmax, double sigmay) ;
VL_EXPORT void
vl_imsmooth_d (double *smoothed, vl_size smoothedStride,
double const *image, vl_size width, vl_size height, vl_size stride,
double sigmax, double sigmay) ;
/** @} */
/* ---------------------------------------------------------------- */
/** @name Image gradients */
/** @{ */
VL_EXPORT void
vl_imgradient_polar_f (float* amplitudeGradient, float* angleGradient,
vl_size gradWidthStride, vl_size gradHeightStride,
float const* image,
vl_size imageWidth, vl_size imageHeight,
vl_size imageStride);
VL_EXPORT void
vl_imgradient_polar_d (double* amplitudeGradient, double* angleGradient,
vl_size gradWidthStride, vl_size gradHeightStride,
double const* image,
vl_size imageWidth, vl_size imageHeight,
vl_size imageStride);
VL_EXPORT void
vl_imgradient_f (float* xGradient, float* yGradient,
vl_size gradWidthStride, vl_size gradHeightStride,
float const *image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride);
VL_EXPORT void
vl_imgradient_d(double* xGradient, double* yGradient,
vl_size gradWidthStride, vl_size gradHeightStride,
double const *image,
vl_size imageWidth, vl_size imageHeight, vl_size imageStride);
VL_EXPORT void
vl_imgradient_polar_f_callback(float const *sourceImage,
int sourceImageWidth, int sourceImageHeight,
float *dstImage,
int dstWidth, int dstHeight,
int octave, int level,
void *params);
/** @} */
/* VL_IMOPV_H */
#endif
| 6,075
|
C++
|
.h
| 136
| 32.036765
| 88
| 0.540179
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
28,330
|
random.h
|
openMVG_openMVG/src/nonFree/sift/vl/random.h
|
/** @file random.h
** @brief Random number generator
** @author Andrea Vedaldi
**/
/*
Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
#ifndef VL_RANDOM_H
#define VL_RANDOM_H
#include "host.h"
/** @brief Random numbber generator state */
typedef struct _VlRand {
vl_uint32 mt [624] ;
vl_size mti ;
} VlRand ;
/** @name Setting and reading the state
**
** @{ */
VL_EXPORT void vl_rand_init (VlRand * self) ;
VL_EXPORT void vl_rand_seed (VlRand * self, vl_uint32 s) ;
VL_EXPORT void vl_rand_seed_by_array (VlRand * self,
vl_uint32 const key [],
vl_size keySize) ;
/** @} */
/** @name Generate random numbers
**
** @{ */
VL_INLINE vl_uint64 vl_rand_uint64 (VlRand * self) ;
VL_INLINE vl_int64 vl_rand_int63 (VlRand * self) ;
VL_EXPORT vl_uint32 vl_rand_uint32 (VlRand * self) ;
VL_INLINE vl_int32 vl_rand_int31 (VlRand * self) ;
VL_INLINE double vl_rand_real1 (VlRand * self) ;
VL_INLINE double vl_rand_real2 (VlRand * self) ;
VL_INLINE double vl_rand_real3 (VlRand * self) ;
VL_INLINE double vl_rand_res53 (VlRand * self) ;
VL_INLINE vl_uindex vl_rand_uindex (VlRand * self, vl_uindex range) ;
/** @} */
/* ---------------------------------------------------------------- */
/** @brief Generate a random index in a given range
** @param self random number generator.
** @param range range.
** @return an index sampled uniformly at random in the interval [0, @c range - 1]
**
** @remark Currently, this function uses a simple algorithm that
** may yield slightly biased samples if @c range is not a power of
** two.
**/
VL_INLINE vl_uindex
vl_rand_uindex (VlRand * self, vl_uindex range)
{
if (range <= 0xffffffff) {
/* 32-bit version */
return (vl_rand_uint32 (self) % (vl_uint32)range) ;
} else {
/* 64-bit version */
return (vl_rand_uint64 (self) % range) ;
}
}
/** @brief Generate a random UINT64
** @param self random number generator.
** @return a random number in [0, 0xffffffffffffffff].
**/
VL_INLINE vl_uint64
vl_rand_uint64 (VlRand * self)
{
vl_uint64 a = vl_rand_uint32 (self) ;
vl_uint64 b = vl_rand_uint32 (self) ;
return (a << 32) | b ;
}
/** @brief Generate a random INT63
** @param self random number generator.
** @return a random number in [0, 0x7fffffffffffffff].
**/
VL_INLINE vl_int64
vl_rand_int63 (VlRand * self)
{
return (vl_int64)(vl_rand_uint64 (self) >> 1) ;
}
/** @brief Generate a random INT31
** @param self random number generator.
** @return a random number in [0, 0x7fffffff].
**/
VL_INLINE vl_int32
vl_rand_int31 (VlRand * self)
{
return (vl_int32)(vl_rand_uint32 (self) >> 1) ;
}
/** @brief Generate a random number in [0,1]
** @param self random number generator.
** @return a random number.
**/
VL_INLINE double
vl_rand_real1 (VlRand * self)
{
return vl_rand_uint32(self)*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/** @brief Generate a random number in [0,1)
** @param self random number generator.
** @return a random number.
**/
VL_INLINE double
vl_rand_real2 (VlRand * self)
{
return vl_rand_uint32(self)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/** @brief Generate a random number in (0,1)
** @param self random number generator.
** @return a random number.
**/
VL_INLINE double
vl_rand_real3 (VlRand * self)
{
return (((double)vl_rand_uint32(self)) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/** @brief Generate a random number in [0,1) with 53-bit resolution
** @param self random number generator.
** @return a random number.
**/
VL_INLINE double
vl_rand_res53 (VlRand * self)
{
vl_uint32
a = vl_rand_uint32(self) >> 5,
b = vl_rand_uint32(self) >> 6 ;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0) ;
}
/* VL_RANDOM_H */
#endif
| 3,962
|
C++
|
.h
| 134
| 27.126866
| 82
| 0.657113
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| false
| false
| false
|
28,331
|
mathop_sse2.h
|
openMVG_openMVG/src/nonFree/sift/vl/mathop_sse2.h
|
/** @file mathop_sse2.h
** @brief mathop for sse2
** @author Andrea Vedaldi
**/
/*
Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
/* ---------------------------------------------------------------- */
#ifndef VL_MATHOP_SSE2_H_INSTANTIATING
#define VL_MATHOP_SSE2_H_INSTANTIATING
#ifndef VL_MATHOP_SSE2_H
#define VL_MATHOP_SSE2_H
#undef FLT
#define FLT VL_TYPE_DOUBLE
#include "mathop_sse2.h"
#undef FLT
#define FLT VL_TYPE_FLOAT
#include "mathop_sse2.h"
/* VL_MATHOP_SSE2_H */
#endif
/* ---------------------------------------------------------------- */
/* VL_MATHOP_SSE2_H_INSTANTIATING */
#else
#ifndef VL_DISABLE_SSE2
#include "generic.h"
#include "float.th"
VL_EXPORT T
VL_XCAT(_vl_distance_l2_sse2_, SFX)
(vl_size dimension, T const * X, T const * Y) ;
VL_EXPORT T
VL_XCAT(_vl_distance_l1_sse2_, SFX)
(vl_size dimension, T const * X, T const * Y) ;
VL_EXPORT T
VL_XCAT(_vl_distance_chi2_sse2_, SFX)
(vl_size dimension, T const * X, T const * Y) ;
VL_EXPORT T
VL_XCAT(_vl_kernel_l2_sse2_, SFX)
(vl_size dimension, T const * X, T const * Y) ;
VL_EXPORT T
VL_XCAT(_vl_kernel_l1_sse2_, SFX)
(vl_size dimension, T const * X, T const * Y) ;
VL_EXPORT T
VL_XCAT(_vl_kernel_chi2_sse2_, SFX)
(vl_size dimension, T const * X, T const * Y) ;
/* ! VL_DISABLE_SSE2 */
#endif
/* VL_MATHOP_SSE2_INSTANTIATING */
#endif
| 1,487
|
C++
|
.h
| 51
| 27.745098
| 70
| 0.652327
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,332
|
mathop.h
|
openMVG_openMVG/src/nonFree/sift/vl/mathop.h
|
/** @file mathop.h
** @brief Math operations
** @author Andrea Vedaldi
**/
/*
Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
#ifndef VL_MATHOP_H
#define VL_MATHOP_H
#include "generic.h"
#include <math.h>
/** @brief Logarithm of 2 (math constant)*/
#define VL_LOG_OF_2 0.693147180559945
/** @brief Pi (math constant) */
#define VL_PI 3.141592653589793
/** @brief IEEE single precision epsilon (math constant)
**
** <code>1.0F + VL_EPSILON_F</code> is the smallest representable
** single precision number greater than @c 1.0F. Numerically,
** ::VL_EPSILON_F is equal to @f$ 2^{-23} @f$.
**
**/
#define VL_EPSILON_F 1.19209290E-07F
/** @brief IEEE double precision epsilon (math constant)
**
** <code>1.0 + VL_EPSILON_D</code> is the smallest representable
** double precision number greater than @c 1.0. Numerically,
** ::VL_EPSILON_D is equal to @f$ 2^{-52} @f$.
**/
#define VL_EPSILON_D 2.220446049250313e-16
/*
For the code below: An ANSI C compiler takes the two expressions,
LONG_VAR and CHAR_VAR, and implicitly casts them to the type of the
first member of the union. Refer to K&R Second Edition Page 148,
last paragraph.
*/
/** @internal @brief IEEE single precision quiet NaN constant */
static union { vl_uint32 raw ; float value ; }
const vl_nan_f =
{ 0x7FC00000UL } ;
/** @internal @brief IEEE single precision infinity constant */
static union { vl_uint32 raw ; float value ; }
const vl_infinity_f =
{ 0x7F800000UL } ;
/** @internal @brief IEEE double precision quiet NaN constant */
static union { vl_uint64 raw ; double value ; }
const vl_nan_d =
#ifdef VL_COMPILER_MSC
{ 0x7FF8000000000000ui64 } ;
#else
{ 0x7FF8000000000000ULL } ;
#endif
/** @internal @brief IEEE double precision infinity constant */
static union { vl_uint64 raw ; double value ; }
const vl_infinity_d =
#ifdef VL_COMPILER_MSC
{ 0x7FF0000000000000ui64 } ;
#else
{ 0x7FF0000000000000ULL } ;
#endif
/** @brief IEEE single precision NaN (not signaling) */
#define VL_NAN_F (vl_nan_f.value)
/** @brief IEEE single precision positive infinity (not signaling) */
#define VL_INFINITY_F (vl_infinity_f.value)
/** @brief IEEE double precision NaN (not signaling) */
#define VL_NAN_D (vl_nan_d.value)
/** @brief IEEE double precision positive infinity (not signaling) */
#define VL_INFINITY_D (vl_infinity_d.value)
/* ---------------------------------------------------------------- */
/** @brief Fast <code>mod(x, 2 * VL_PI)</code>
**
** @param x input value.
** @return <code>mod(x, 2 * VL_PI)</code>
**
** The function is optimized for small absolute values of @a x.
**
** The result is guaranteed to be not smaller than 0. However, due to
** finite numerical precision and rounding errors, the result can be
** equal to 2 * VL_PI (for instance, if @c x is a very small negative
** number).
**/
VL_INLINE float
vl_mod_2pi_f (float x)
{
while (x > (float)(2 * VL_PI)) x -= (float) (2 * VL_PI) ;
while (x < 0.0F) x += (float) (2 * VL_PI);
return x ;
}
/** @brief Fast <code>mod(x, 2 * VL_PI)</code>
** @see vl_mod_2pi_f
**/
VL_INLINE double
vl_mod_2pi_d (double x)
{
while (x > 2.0 * VL_PI) x -= 2 * VL_PI ;
while (x < 0.0) x += 2 * VL_PI ;
return x ;
}
/** @brief Floor and convert to integer
** @param x argument.
** @return Similar to @c (int) floor(x)
**/
VL_INLINE long int
vl_floor_f (float x)
{
long int xi = (long int) x ;
if (x >= 0 || (float) xi == x) return xi ;
else return xi - 1 ;
}
/** @brief Floor and convert to integer
** @see vl_floor_f
**/
VL_INLINE long int
vl_floor_d (double x)
{
long int xi = (long int) x ;
if (x >= 0 || (double) xi == x) return xi ;
else return xi - 1 ;
}
/** @brief Ceil and convert to integer
** @param x argument.
** @return @c lceilf(x)
**/
VL_INLINE long int
vl_ceil_f (float x)
{
#ifdef VL_COMPILER_GNUC
return (long int) __builtin_ceilf(x) ;
#else
return (long int) ceilf(x) ;
#endif
}
/** @brief Ceil and convert to integer
** @see vl_ceil_f
**/
VL_INLINE long int
vl_ceil_d (double x)
{
#ifdef VL_COMPILER_GNUC
return __builtin_ceil(x) ;
#else
return (long int) ceil(x) ;
#endif
}
/** @brief Round
** @param x argument.
** @return @c lroundf(x)
** This function is either the same or similar to C99 @c lroundf().
**/
VL_INLINE long int
vl_round_f (float x)
{
#ifdef VL_COMPILER_GNUC
return __builtin_lroundf(x) ;
#elif VL_COMPILER_MSC
if (x >= 0.0F) {
return vl_floor_f(x + 0.5F) ;
} else {
return vl_ceil_f(x - 0.5F) ;
}
#else
return lroundf(x) ;
#endif
}
/** @brief Round
** @param x argument.
** @return @c lround(x)
** This function is either the same or similar to C99 @c lround().
**/
VL_INLINE long int
vl_round_d (double x)
{
#ifdef VL_COMPILER_GNUC
return __builtin_lround(x) ;
#elif VL_COMPILER_MSC
if (x >= 0.0) {
return vl_floor_d(x + 0.5) ;
} else {
return vl_ceil_d(x - 0.5) ;
}
#else
return lround(x) ;
#endif
}
/** @brief Fast @c abs(x)
** @param x argument.
** @return @c abs(x)
**/
VL_INLINE float
vl_abs_f (float x)
{
#ifdef VL_COMPILER_GNUC
return __builtin_fabsf (x) ;
#else
return fabsf(x) ;
#endif
}
/** @brief Fast @c abs(x)
** @sa vl_abs_f
**/
VL_INLINE double
vl_abs_d (double x)
{
#ifdef VL_COMPILER_GNUC
return __builtin_fabs (x) ;
#else
return fabs(x) ;
#endif
}
VL_INLINE double
vl_log2_d (double x)
{
#ifdef VL_COMPILER_GNUC
return __builtin_log2(x) ;
#elif VL_COMPILER_MSC
return log(x) / 0.693147180559945 ;
#else
return log2(x) ;
#endif
}
VL_INLINE float
vl_log2_f (float x)
{
#ifdef VL_COMPILER_GNUC
return __builtin_log2f (x) ;
#elif VL_COMPILER_MSC
return logf(x) / 0.6931472F ;
#else
return log2(x) ;
#endif
}
/** ------------------------------------------------------------------
** @brief Fast @c atan2 approximation
** @param y argument.
** @param x argument.
**
** The function computes a relatively rough but fast approximation of
** @c atan2(y,x).
**
** @par Algorithm
**
** The algorithm approximates the function @f$ f(r)=atan((1-r)/(1+r))
** @f$, @f$ r \in [-1,1] @f$ with a third order polynomial @f$
** f(r)=c_0 + c_1 r + c_2 r^2 + c_3 r^3 @f$. To fit the polynomial
** we impose the constraints
**
** @f{eqnarray*}
** f(+1) &=& c_0 + c_1 + c_2 + c_3 = atan(0) = 0,\\
** f(-1) &=& c_0 - c_1 + c_2 - c_3 = atan(\infty) = \pi/2,\\
** f(0) &=& c_0 = atan(1) = \pi/4.
** @f}
**
** The last degree of freedom is fixed by minimizing the @f$
** l^{\infty} @f$ error, which yields
**
** @f[
** c_0=\pi/4, \quad
** c_1=-0.9675, \quad
** c_2=0, \quad
** c_3=0.1821,
** @f]
**
** with maximum error of 0.0061 radians at 0.35 degrees.
**
** @return Approximation of @c atan2(y,x).
**/
VL_INLINE float
vl_fast_atan2_f (float y, float x)
{
float angle, r ;
float const c3 = 0.1821F ;
float const c1 = 0.9675F ;
float abs_y = vl_abs_f (y) + VL_EPSILON_F ;
if (x >= 0) {
r = (x - abs_y) / (x + abs_y) ;
angle = (float) (VL_PI / 4) ;
} else {
r = (x + abs_y) / (abs_y - x) ;
angle = (float) (3 * VL_PI / 4) ;
}
angle += (c3*r*r - c1) * r ;
return (y < 0) ? - angle : angle ;
}
/** @brief Fast @c atan2 approximation
** @sa vl_fast_atan2_f
**/
VL_INLINE double
vl_fast_atan2_d (double y, double x)
{
double angle, r ;
double const c3 = 0.1821 ;
double const c1 = 0.9675 ;
double abs_y = vl_abs_d (y) + VL_EPSILON_D ;
if (x >= 0) {
r = (x - abs_y) / (x + abs_y) ;
angle = VL_PI / 4 ;
} else {
r = (x + abs_y) / (abs_y - x) ;
angle = 3 * VL_PI / 4 ;
}
angle += (c3*r*r - c1) * r ;
return (y < 0) ? - angle : angle ;
}
/** ------------------------------------------------------------------
** @brief Fast @c resqrt approximation
** @param x argument.
** @return approximation of @c resqrt(x).
**
** The function quickly computes an approximation of @f$ x^{-1/2}
** @f$.
**
** @par Algorithm
**
** The goal is to compute @f$ y = x^{-1/2} @f$, which we do by
** finding the solution of @f$ 0 = f(y) = y^{-2} - x @f$ by two Newton
** steps. Each Newton iteration is given by
**
** @f[
** y \leftarrow
** y - \frac{f(y)}{\frac{df(y)}{dy}} =
** y + \frac{1}{2} (y-xy^3) =
** \frac{y}{2} \left( 3 - xy^2 \right)
** @f]
**
** which yields a simple polynomial update rule.
**
** The clever bit (attributed to either J. Carmack or G. Tarolli) is
** the way an initial guess @f$ y \approx x^{-1/2} @f$ is chosen.
**
** @see <a href="http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf">Inverse Sqare Root</a>.
**
**/
VL_INLINE float
vl_fast_resqrt_f (float x)
{
/* 32-bit version */
union {
float x ;
vl_int32 i ;
} u ;
float xhalf = (float) 0.5 * x ;
/* convert floating point value in RAW integer */
u.x = x ;
/* gives initial guess y0 */
u.i = 0x5f3759df - (u.i >> 1);
/*u.i = 0xdf59375f - (u.i>>1);*/
/* two Newton steps */
u.x = u.x * ( (float) 1.5 - xhalf*u.x*u.x) ;
u.x = u.x * ( (float) 1.5 - xhalf*u.x*u.x) ;
return u.x ;
}
/** @brief Fast @c resqrt approximation
** @sa vl_fast_resqrt_d
**/
VL_INLINE double
vl_fast_resqrt_d (double x)
{
/* 64-bit version */
union {
double x ;
vl_int64 i ;
} u ;
double xhalf = (double) 0.5 * x ;
/* convert floating point value in RAW integer */
u.x = x ;
/* gives initial guess y0 */
#ifdef VL_COMPILER_MSC
u.i = 0x5fe6ec85e7de30dai64 - (u.i >> 1) ;
#else
u.i = 0x5fe6ec85e7de30daLL - (u.i >> 1) ;
#endif
/* two Newton steps */
u.x = u.x * ( (double) 1.5 - xhalf*u.x*u.x) ;
u.x = u.x * ( (double) 1.5 - xhalf*u.x*u.x) ;
return u.x ;
}
/** ------------------------------------------------------------------
** @brief Fast @c sqrt approximation
** @param x argument.
** @return approximation of @c sqrt(x).
**
** The function computes a cheap approximation of @c sqrt(x).
**
** @par Floating-point algorithm
**
** For the floating point cases, the function uses ::vl_fast_resqrt_f
** (or ::vl_fast_resqrt_d) to compute <code>x *
** vl_fast_resqrt_f(x)</code>.
**
** @par Integer algorithm
**
** We seek for the largest integer @e y such that @f$ y^2 \leq x @f$.
** Write @f$ y = w + b_k 2^k + z @f$ where the binary expansion of the
** various variable is
**
** @f[
** x = \sum_{i=0}^{n-1} 2^i a_i, \qquad
** w = \sum_{i=k+1}^{m-1} 2^i b_i, \qquad
** z = \sum_{i=0}^{k-1} 2^i b_i.
** @f]
**
** Assume @e w known. Expanding the square and using the fact that
** @f$ b_k^2=b_k @f$, we obtain the following constraint for @f$ b_k
** @f$ and @e z:
**
** @f[
** x - w^2 \geq 2^k ( 2 w + 2^k ) b_k + z (z + 2wz + 2^{k+1}z b_k)
** @f]
**
** A necessary condition for @f$ b_k = 1 @f$ is that this equation is
** satisfied for @f$ z = 0 @f$ (as the second term is always
** non-negative). In fact, this condition is also sufficient, since
** we are looking for the @e largest solution @e y.
**
** This yields the following iterative algorithm. First, note that if
** @e x is stored in @e n bits, where @e n is even, then the integer
** square root does not require more than @f$ m = n / 2 @f$ bit to be
** stored. Thus initially, @f$ w = 0 @f$ and @f$ k = m - 1 = n/2 - 1
** @f$. Then, at each iteration the equation is tested, determining
** @f$ b_{m-1}, b_{m-2}, ... @f$ in this order.
**/
VL_INLINE float
vl_fast_sqrt_f (float x)
{
return (x < 1e-8) ? 0 : x * vl_fast_resqrt_f (x) ;
}
/** @brief Fast @c sqrt approximation
** @sa vl_fast_sqrt_f
**/
VL_INLINE double
vl_fast_sqrt_d (float x)
{
return (x < 1e-8) ? 0 : x * vl_fast_resqrt_d (x) ;
}
/** @brief Fast @c sqrt approximation
** @sa vl_fast_sqrt_f
**/
VL_INLINE vl_uint32 vl_fast_sqrt_ui32 (vl_uint32 x) ;
/** @brief Fast @c sqrt approximation
** @sa vl_fast_sqrt_f
**/
VL_INLINE vl_uint16 vl_fast_sqrt_ui16 (vl_uint16 x) ;
/** @brief Fast @c sqrt approximation
** @sa vl_fast_sqrt_f
**/
VL_INLINE vl_uint8 vl_fast_sqrt_ui8 (vl_uint8 x) ;
#define VL_FAST_SQRT_UI(T,SFX) \
VL_INLINE T \
vl_fast_sqrt_ ## SFX (T x) \
{ \
T y = 0 ; /* w / 2^k */ \
T tmp = 0 ; \
int twok ; \
\
for (twok = 8 * sizeof(T) - 2 ; \
twok >= 0 ; twok -= 2) { \
y <<= 1 ; /* y = 2 * y */ \
tmp = (2*y + 1) << twok ; \
if (x >= tmp) { \
x -= tmp ; \
y += 1 ; \
} \
} \
return y ; \
}
VL_FAST_SQRT_UI(vl_uint32,ui32)
VL_FAST_SQRT_UI(vl_uint16,ui16)
VL_FAST_SQRT_UI(vl_uint8,ui8)
/* ---------------------------------------------------------------- */
/* Vector distances and similarities */
/* ---------------------------------------------------------------- */
/** @typedef VlFloatVectorComparisonFunction
** @brief Pointer to a function to compare vectors of floats
**/
typedef float (*VlFloatVectorComparisonFunction)(vl_size dimension, float const * X, float const * Y) ;
/** @typedef VlDoubleVectorComparisonFunction
** @brief Pointer to a function to compare vectors of doubles
**/
typedef double (*VlDoubleVectorComparisonFunction)(vl_size dimension, double const * X, double const * Y) ;
/** @brief Vector comparison types */
enum _VlVectorComparisonType {
VlDistanceL1, /**< l1 distance (squared intersection metric) */
VlDistanceL2, /**< squared l2 distance */
VlDistanceChi2, /**< squared Chi2 distance */
VlDistanceHellinger, /**< squared Hellinger's distance */
VlDistanceJS, /**< squared Jensen-Shannon distance */
VlKernelL1, /**< intersection kernel */
VlKernelL2, /**< l2 kernel */
VlKernelChi2, /**< Chi2 kernel */
VlKernelHellinger, /**< Hellinger's kernel */
VlKernelJS /**< Jensen-Shannon kernel */
} ;
/** @brief Vector comparison types */
typedef enum _VlVectorComparisonType VlVectorComparisonType ;
/** @brief Get the symbolic name of a vector comparison type
** @param type vector comparison type.
** @return data symbolic name.
**/
VL_INLINE char const *
vl_get_vector_comparison_type_name (int type)
{
switch (type) {
case VlDistanceL1 : return "l1" ;
case VlDistanceL2 : return "l2" ;
case VlDistanceChi2 : return "chi2" ;
case VlKernelL1 : return "kl1" ;
case VlKernelL2 : return "kl2" ;
case VlKernelChi2 : return "kchi2" ;
default: return NULL ;
}
}
VL_EXPORT VlFloatVectorComparisonFunction
vl_get_vector_comparison_function_f (VlVectorComparisonType type) ;
VL_EXPORT VlDoubleVectorComparisonFunction
vl_get_vector_comparison_function_d (VlVectorComparisonType type) ;
VL_EXPORT void
vl_eval_vector_comparison_on_all_pairs_f (float * result, vl_size dimension,
float const * X, vl_size numDataX,
float const * Y, vl_size numDataY,
VlFloatVectorComparisonFunction function) ;
VL_EXPORT void
vl_eval_vector_comparison_on_all_pairs_d (double * result, vl_size dimension,
double const * X, vl_size numDataX,
double const * Y, vl_size numDataY,
VlDoubleVectorComparisonFunction function) ;
/* ---------------------------------------------------------------- */
/* Numerical analysis */
/* ---------------------------------------------------------------- */
VL_EXPORT void
vl_svd2 (double* S, double *U, double *V, double const *M) ;
VL_EXPORT void
vl_lapack_dlasv2 (double *smin,
double *smax,
double *sv,
double *cv,
double *su,
double *cu,
double f,
double g,
double h) ;
VL_EXPORT int
vl_solve_linear_system_3 (double * x, double const * A, double const *b) ;
VL_EXPORT int
vl_solve_linear_system_2 (double * x, double const * A, double const *b) ;
VL_EXPORT int
vl_gaussian_elimination (double * A, vl_size numRows, vl_size numColumns) ;
/* VL_MATHOP_H */
#endif
| 17,128
|
C++
|
.h
| 551
| 28.030853
| 107
| 0.563865
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,333
|
MainWindow.hpp
|
openMVG_openMVG/src/openMVG_Samples/describe_and_match_GUI/MainWindow.hpp
|
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2017 Romuald Perrot.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_SAMPLES_FEATURES_PAIR_DEMO_MAIN_WINDOW_HPP
#define OPENMVG_SAMPLES_FEATURES_PAIR_DEMO_MAIN_WINDOW_HPP
#include "openMVG/features/feature.hpp"
#include "openMVG/features/image_describer.hpp"
#include "openMVG/matching/matcher_type.hpp"
#include "openMVG/matching_image_collection/Matcher_Regions.hpp"
#include "ImageView.hpp"
#include <QAction>
#include <QCheckBox>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QGraphicsEllipseItem>
#include <QGraphicsItem>
#include <QGraphicsLineItem>
#include <QGraphicsScene>
#include <QLabel>
#include <QMainWindow>
#include <QMenu>
#include <QPixmap>
#include <QPushButton>
#include <memory>
namespace features_pair_demo
{
/**
* @brief Main class
*/
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
/**
* @brief Constructor
*/
MainWindow();
public slots:
/**
* @brief Action to be done when user wants to load the first image
*/
void onOpenImage1( void );
/**
* @brief Action to be done when user wants to load the second image
*/
void onOpenImage2( void );
/**
* @brief Action to be done when user wants to compute features and matching bewteen image pairs
*/
void onComputeMatching( void );
/**
* @brief Action to be executed when user move image on the interface
*/
void onMoveSomething( void );
/**
* @brief Action to be executed when user wants to export the final computation to an image
*/
void onExportImage( void );
/**
* @brief Action to be executed when user request closing of image 1
*/
void onCloseImage1( void );
/**
* @brief Action to be executed when user request closing of image 2
*/
void onCloseImage2( void );
/**
* @brief Action to be executed when user request closing both images
*/
void onCloseAll( void );
/**
* @brief Action to be executed when user request to quit the application
*/
void onQuit( void );
/**
* @brief Action to be executed when user request clearing the computation
*/
void onClearComputation( void );
private:
/**
* @brief Set elements enabled/disabled based on currently loaded elements
*/
void UpdateActivation( void );
/**
* @brief Build all interface widgets
*/
void BuildInterface();
/**
* @brief Build all menu items
*/
void BuildMenus();
/**
* @brief Make connections between interface elements
*/
void MakeConnections();
/**
* @brief Fill comboboxes with all feature types and feature presets
*/
void PopulateFeatureType();
/**
* @brief Fill comboboxes with all matching types
*/
void PopulateMatchingType();
/**
* @brief remove previous computation (internal data)
*/
void ClearFeaturesandMatch();
/**
* @brief remove previous computation on the view (only view data, not internal ones)
*/
void ClearFeaturesAndMatchItems();
/**
* @brief Redraw match lines at the correct position (i.e. :after image move)
*/
void MoveMatchLines();
/**
* @brief Get feature preset from interface
* @return descriptor preset given the interface choice
*/
openMVG::features::EDESCRIBER_PRESET GetFeaturePreset( void );
/**
* @brief Get describer instance based on the choices made in the interface
* @param preset Current preset
* @return An image describer
*/
std::unique_ptr<openMVG::features::Image_describer> GetFeatureDescriber( const openMVG::features::EDESCRIBER_PRESET preset );
/**
* @brief Get Matcher type
* @return current matcher type based on the choices made in the interface
*/
openMVG::matching::EMatcherType GetMatcherType( void );
QLabel *m_labelFeatureName;
QComboBox *m_comboFeatureName;
QLabel *m_labelFeatureMode;
QComboBox *m_comboFeatureMode;
QCheckBox *m_checkUpright;
QLabel *m_matchingType;
QComboBox *m_comboMatchingName;
QLabel *m_labelDistanceThreshold;
QDoubleSpinBox *m_spinDistThreshold;
QPushButton *m_loadImage1;
QPushButton *m_loadImage2;
QPushButton *m_computeMatching;
QPushButton *m_exportResult;
QGraphicsScene *m_scn;
ImageView *m_view;
std::string m_image1Path;
QPixmap *m_pixmap1;
QGraphicsItem *m_pixmap1Item;
std::string m_image2Path;
QPixmap *m_pixmap2;
QGraphicsItem *m_pixmap2Item;
std::vector<openMVG::features::PointFeature> m_feats1;
std::vector<QGraphicsEllipseItem *> m_ellipsesFeat1;
std::vector<openMVG::features::PointFeature> m_feats2;
std::vector<QGraphicsEllipseItem *> m_ellipsesFeat2;
openMVG::matching::IndMatches m_matches;
std::vector<QGraphicsLineItem *> m_lineMatch;
// menus items
QMenu *m_fileMenu;
QMenu *m_processingMenu;
QAction *m_fileOpenImage1;
QAction *m_fileOpenImage2;
QAction *m_fileCloseImage1;
QAction *m_fileCloseImage2;
QAction *m_fileCloseAll;
QAction *m_fileExportImage;
QAction *m_fileQuit;
QAction *m_processingComputeMatch;
QAction *m_processingClearMatch;
};
} // namespace features_pair_demo
#endif
| 5,237
|
C++
|
.h
| 175
| 27.091429
| 127
| 0.746063
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,334
|
ImageView.hpp
|
openMVG_openMVG/src/openMVG_Samples/describe_and_match_GUI/ImageView.hpp
|
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2017 Romuald Perrot.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENMVG_SAMPLES_FEATURES_PAIR_DEMO_IMAGE_VIEW_HPP
#define OPENMVG_SAMPLES_FEATURES_PAIR_DEMO_IMAGE_VIEW_HPP
#include <QGraphicsView>
namespace features_pair_demo
{
// Subclass of qgraphicsview used to provide additional fonctionnalities (zooming with mouse wheel)
class ImageView : public QGraphicsView
{
public:
/**
* @brief ctr
* @param scn the scene to render in this widget
* @param parent The parent widget
*/
ImageView( QGraphicsScene *scn, QWidget *parent = nullptr );
/**
* @brief handling of the zoom effect
* @param event Container used to answer the mouse wheel informations
*/
virtual void wheelEvent( QWheelEvent *event );
private:
};
} // namespace features_pair_demo
#endif
| 1,046
|
C++
|
.h
| 29
| 33.965517
| 99
| 0.760675
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,335
|
MainWindow.hh
|
openMVG_openMVG/src/openMVG_Samples/image_undistort_gui/MainWindow.hh
|
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2017 Romuald Perrot.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef _OPENMVG_SAMPLE_IMAGE_UNDISTORT_GUI_MAIN_WINDOW_HH_
#define _OPENMVG_SAMPLE_IMAGE_UNDISTORT_GUI_MAIN_WINDOW_HH_
#include "openMVG/image/image_container.hpp"
#include "openMVG/image/pixel_types.hpp"
#include <QAction>
#include <QCheckBox>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QGraphicsView>
#include <QLabel>
#include <QMainWindow>
#include <QMenu>
#include <QPushButton>
namespace image_undistort_gui
{
/**
* @brief Main class of the GUI interface
*/
class MainWindow : public QMainWindow
{
public:
/**
* @brief Constructor
* @param parent Parent widget of this window
*/
MainWindow( QWidget *parent = nullptr );
public slots:
/**
* @brief Action to be executed when user want to open an image
*/
void onOpenImage( void );
/**
* @brief Action to be executed when user want to undistort an image
*/
void onProcessImage( void );
/**
* @brief Action to be executed when user want to export an undistorted image
*/
void onExportImage( void );
/**
* @brief Action to be executed when user select an intrinsic type
*/
void onSelectIntrinsicType( void );
/**
* @brief Action to be executed when user check/uncheck the grid checkbox
*/
void onChangeCheckBox( void );
/**
* @brief action to be executed when user select no distorsion menu item
*/
void onMenuSelectNoDist( void );
/**
* @brief action to be executed when user select radial 1 menu item
*/
void onMenuSelectRadial1( void );
/**
* @brief action to be executed when user select radial 3 menu item
*/
void onMenuSelectRadial3( void );
/**
* @brief action to be executed when user select brown menu item
*/
void onMenuSelectBrown( void );
/**
* @brief action to be executed when user select fisheye menu item
*/
void onMenuSelectFisheye( void );
/**
* @brief action to be executed when user select quit menu item
*/
void onQuit( void );
private:
static const int STATE_INITIAL;
static const int STATE_HAS_INPUT;
static const int STATE_HAS_COMPUTED_DISTORTION;
int m_current_state;
/**
* @brief Fill intrinsic values in the combobox
*/
void FillIntrinsicTypes( void );
/**
* @brief Build virtual image representing a regular grid
*/
void BuildGrid( void );
/**
* @brief update interface based on internal state
*/
void UpdateInterface( void );
/**
* @brief Build Interface widgets
*/
void BuildInterface();
/**
* @brief Create menus items
*/
void BuildMenus();
/**
* @brief Make connections between interface items and slots
*/
void MakeConnections();
QPushButton *m_open_image;
QCheckBox *m_check_use_grid; // use a grid instead of an image
QLabel *m_intrinsic_label;
QComboBox *m_intrinsic_type; // Pinhole | pinhole radial 1 | pinhole radial 2 | pinhole radial 3 | pinhole brown | pinhole fisheye
// Focal
QLabel *m_label_fov;
QDoubleSpinBox *m_fov_spin;
// Center point
QLabel *m_label_ppx;
QDoubleSpinBox *m_ppx;
QLabel *m_label_ppy;
QDoubleSpinBox *m_ppy;
// Radial/fisheye
QLabel *m_label_k1;
QDoubleSpinBox *m_k1;
QLabel *m_label_k2;
QDoubleSpinBox *m_k2;
QLabel *m_label_k3;
QDoubleSpinBox *m_k3;
QLabel *m_label_k4;
QDoubleSpinBox *m_k4;
// Tangential
QLabel *m_label_t1;
QDoubleSpinBox *m_t1;
QLabel *m_label_t2;
QDoubleSpinBox *m_t2;
// Process
QPushButton *m_process;
QPushButton *m_exportResult;
// Display
QGraphicsView *m_view_old;
QGraphicsView *m_view_new;
QGraphicsScene *m_scene_old;
QGraphicsScene *m_scene_new;
// in/out images
openMVG::image::Image<openMVG::image::RGBColor> m_inputImage;
openMVG::image::Image<openMVG::image::RGBColor> m_outputImage;
// Menu items
QMenu *m_fileMenu;
QAction *m_quit_act;
QMenu *m_inputMenu;
QAction *m_open_image_act;
QAction *m_use_grid_act;
QMenu *m_intrinsicMenu;
QAction *m_no_dist_act;
QAction *m_radial_k1_act;
QAction *m_radial_k3_act;
QAction *m_brown_act;
QAction *m_fisheye_act;
QMenu *m_processMenu;
QAction *m_process_act;
QAction *m_export_act;
Q_OBJECT
};
} // namespace image_undistort_gui
#endif
| 4,480
|
C++
|
.h
| 161
| 24.869565
| 132
| 0.71986
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,336
|
QImageInterface.hh
|
openMVG_openMVG/src/openMVG_Samples/image_undistort_gui/QImageInterface.hh
|
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2017 Romuald Perrot.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef _OPENMVG_SAMPLE_IMAGE_UNDISTORT_GUI_QIMAGE_INTERFACE_HH_
#define _OPENMVG_SAMPLE_IMAGE_UNDISTORT_GUI_QIMAGE_INTERFACE_HH_
#include "openMVG/image/image_container.hpp"
#include "openMVG/image/pixel_types.hpp"
#include <QImage>
namespace image_undistort_gui
{
/**
* @brief Build a QImage from an openMVG (RGB) image
* @param img Input image
* @return a QImage corresponding to the input image
* @note this makes a deep copy of the image
*/
QImage openMVGImageToQImage( const openMVG::image::Image<openMVG::image::RGBColor> &img );
/**
* @brief Build a QImage from an openMVG (grayscale) image
* @param img Input image
* @return a QImage corresponding to the input image
* @note this makes a deep copy of the image
*/
QImage openMVGImageToQImage( const openMVG::image::Image<unsigned char> &img );
/**
* @brief Convert a QImage to an openMVG image
* @param img Input image
* @return openMVG image corresponding to this image
* @note this makes a deep copy
*/
openMVG::image::Image<openMVG::image::RGBColor> QImageToOpenMVGImage( const QImage &img );
} // namespace image_undistort_gui
#endif
| 1,467
|
C++
|
.h
| 35
| 39.4
| 90
| 0.74525
|
openMVG/openMVG
| 5,671
| 1,671
| 273
|
MPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,338
|
par.cpp
|
doxygen_doxygen/examples/par.cpp
|
/*! \class Par_Test
* Normal text.
*
* \par User defined paragraph:
* Contents of the paragraph.
*
* \par
* New paragraph under the same heading.
*
* \note
* This note consists of two paragraphs.
* This is the first paragraph.
*
* \par
* And this is the second paragraph.
*
* More normal text.
*/
class Par_Test {};
| 337
|
C++
|
.cpp
| 19
| 15.631579
| 40
| 0.68254
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,339
|
restypedef.cpp
|
doxygen_doxygen/examples/restypedef.cpp
|
/*! \file restypedef.cpp
* An example of resolving typedefs.
*/
/*! \struct CoordStruct
* A coordinate pair.
*/
struct CoordStruct
{
/*! The x coordinate */
float x;
/*! The y coordinate */
float y;
};
/*! Creates a type name for CoordStruct */
typedef CoordStruct Coord;
/*!
* This function returns the addition of \a c1 and \a c2, i.e:
* (c1.x+c2.x,c1.y+c2.y)
*/
Coord add(Coord c1,Coord c2)
{
}
| 418
|
C++
|
.cpp
| 22
| 17.090909
| 62
| 0.671756
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
28,341
|
include.cpp
|
doxygen_doxygen/examples/include.cpp
|
/*! A test class. */
class Include_Test
{
public:
/// a member function
void example();
};
/*! \page pag_example
* \dontinclude include_test.cpp
* Our main function starts like this:
* \skip main
* \until {
* First we create an object \c t of the Include_Test class.
* \skipline Include_Test
* Then we call the example member function
* \line example
* After that our little test routine ends.
* \line }
*/
| 442
|
C++
|
.cpp
| 19
| 20.947368
| 61
| 0.67619
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,342
|
example.cpp
|
doxygen_doxygen/examples/example.cpp
|
/** A Example_Test class.
* More details about this class.
*/
class Example_Test
{
public:
/** An example member function.
* More details about this function.
*/
void example();
};
void Example_Test::example() {}
/** \example example_test.cpp
* This is an example of how to use the Example_Test class.
* More details about this example.
*/
| 370
|
C++
|
.cpp
| 16
| 20.375
| 59
| 0.683761
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,344
|
author.cpp
|
doxygen_doxygen/examples/author.cpp
|
/*!
* \brief Pretty nice class.
* \details This class is used to demonstrate a number of section commands.
* \author John Doe
* \author Jan Doe
* \version 4.1a
* \date 1990-2011
* \pre First initialize the system.
* \bug Not all memory is freed when deleting an object of this class.
* \warning Improper use can crash your application
* \copyright GNU Public License.
*/
class SomeNiceClass {};
| 450
|
C++
|
.cpp
| 13
| 32.692308
| 78
| 0.663616
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,348
|
overload.cpp
|
doxygen_doxygen/examples/overload.cpp
|
class Overload_Test
{
public:
void drawRect(int,int,int,int);
void drawRect(const Rect &r);
};
void Overload_Test::drawRect(int x,int y,int w,int h) {}
void Overload_Test::drawRect(const Rect &r) {}
/*! \class Overload_Test
* \brief A short description.
*
* More text.
*/
/*! \fn void Overload_Test::drawRect(int x,int y,int w,int h)
* This command draws a rectangle with a left upper corner at ( \a x , \a y ),
* width \a w and height \a h.
*/
/*!
* \overload void Overload_Test::drawRect(const Rect &r)
*/
| 539
|
C++
|
.cpp
| 20
| 24.5
| 78
| 0.669261
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
28,349
|
tag.cpp
|
doxygen_doxygen/examples/tag.cpp
|
/*! A class that is inherited from the external class Test.
*/
class Tag : public Example_Test
{
public:
/*! an overloaded member. */
void example();
};
| 164
|
C++
|
.cpp
| 8
| 18.125
| 59
| 0.677419
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,350
|
templ.cpp
|
doxygen_doxygen/examples/templ.cpp
|
/*! A template class */
template<class T,int i=100> class Test
{
public:
Test();
Test(const Test &);
};
/*! complete specialization */
template<> class Test<void *,200>
{
public:
Test();
};
/*! A partial template specialization */
template<class T> class Test<T *> : public Test<void *,200>
{
public:
Test();
};
/*! The constructor of the template class*/
template<class T,int i> Test<T,i>::Test() {}
/*! The copy constructor */
template<class T,int i> Test<T,i>::Test(const Test &t) {}
/*! The constructor of the partial specialization */
template<class T> Test<T *>::Test() {}
/*! The constructor of the specialization */
template<> Test<void *,200>::Test() {}
| 693
|
C++
|
.cpp
| 27
| 23.555556
| 59
| 0.667173
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
28,351
|
autolink.cpp
|
doxygen_doxygen/examples/autolink.cpp
|
/*! \file autolink.cpp
Testing automatic link generation.
A link to a member of the Autolink_Test class: Autolink_Test::member,
More specific links to the each of the overloaded members:
Autolink_Test::member(int) and Autolink_Test#member(int,int)
A link to a protected member variable of Autolink_Test: Autolink_Test#var,
A link to the global enumeration type #GlobEnum.
A link to the define #ABS(x).
A link to the destructor of the Autolink_Test class: Autolink_Test::~Autolink_Test,
A link to the typedef ::B.
A link to the enumeration type Autolink_Test::EType
A link to some enumeration values Autolink_Test::Val1 and ::GVal2
*/
/*!
Since this documentation block belongs to the class Autolink_Test no link to
Autolink_Test is generated.
Two ways to link to a constructor are: #Autolink_Test and Autolink_Test().
Links to the destructor are: #~Autolink_Test and ~Autolink_Test().
A link to a member in this class: member().
More specific links to the each of the overloaded members:
member(int) and member(int,int).
A link to the variable #var.
A link to the global typedef ::B.
A link to the global enumeration type #GlobEnum.
A link to the define ABS(x).
A link to a variable \link #var using another text\endlink as a link.
A link to the enumeration type #EType.
A link to some enumeration values: \link Autolink_Test::Val1 Val1 \endlink and ::GVal1.
And last but not least a link to a file: autolink.cpp.
\sa Inside a see also section any word is checked, so EType,
Val1, GVal1, ~Autolink_Test and member will be replaced by links in HTML.
*/
class Autolink_Test
{
public:
Autolink_Test(); //!< constructor
~Autolink_Test(); //!< destructor
void member(int); /**< A member function. Details. */
void member(int,int); /**< An overloaded member function. Details */
/** An enum type. More details */
enum EType {
Val1, /**< enum value 1 */
Val2 /**< enum value 2 */
};
protected:
int var; /**< A member variable */
};
/*! details. */
Autolink_Test::Autolink_Test() { }
/*! details. */
Autolink_Test::~Autolink_Test() { }
/*! A global variable. */
int globVar;
/*! A global enum. */
enum GlobEnum {
GVal1, /*!< global enum value 1 */
GVal2 /*!< global enum value 2 */
};
/*!
* A macro definition.
*/
#define ABS(x) (((x)>0)?(x):-(x))
typedef Autolink_Test B;
/*! \fn typedef Autolink_Test B
* A type definition.
*/
| 2,651
|
C++
|
.cpp
| 66
| 35.424242
| 89
| 0.659019
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,354
|
037_msc.cpp
|
doxygen_doxygen/testing/037_msc.cpp
|
// objective: test the \msc and \endmsc commands
// check: class_sender.xml
// check: class_receiver.xml
// check: 037__msc_8cpp.xml
/** \file
* A bit more complex msc diagram, with also parallel events.
* \msc
* Sender_1,Receiver_1,Sender1_1,
* Sender,Receiver,Sender1,
* Sender_2,Receiver_2,Sender1_2;
*
* Sender_1->Receiver_1 [label="Command()", URL="\ref Receiver::Command()"],
* Sender1_1<-Receiver_1 [label="Ack()", URL="\ref Sender::Ack()", ID="1"];
*
* Sender->Receiver [label="Command()", URL="\ref Receiver::Command()"];
* Sender1<-Receiver [label="Ack()", URL="\ref Sender::Ack()", ID="1"];
* Sender_2->Receiver_2 [label="Command()", URL="\ref Receiver::Command()"],
* Sender1_2<-Receiver_2 [label="Ack()", URL="\ref Sender::Ack()", ID="1"];
* \endmsc
*/
/** Sender class. Can be used to send a command to the server.
* The receiver will acknowledge the command by calling Ack().
* \msc
* Sender,Receiver;
* Sender->Receiver [label="Command()", URL="\ref Receiver::Command()"];
* Sender<-Receiver [label="Ack()", URL="\ref Ack()", ID="1"];
* \endmsc
*/
class Sender
{
public:
/** Acknowledgment from server */
void Ack(bool ok);
};
/** Receiver class. Can be used to receive and execute commands.
* After execution of a command, the receiver will send an acknowledgment
* \msc
* Receiver,Sender;
* Receiver<-Sender [label="Command()", URL="\ref Command()"];
* Receiver->Sender [label="Ack()", URL="\ref Sender::Ack()", ID="1"];
* \endmsc
*/
class Receiver
{
public:
/** Executable a command on the server */
void Command(int commandId);
};
| 1,629
|
C++
|
.cpp
| 48
| 31.8125
| 76
| 0.650824
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,355
|
068_ref_varargs.cpp
|
doxygen_doxygen/testing/068_ref_varargs.cpp
|
// objective: test \ref command with function variadic arguments '...'
// check: 068__ref__varargs_8cpp.xml
/** \file
* See \ref func(int,...) "the function" for more info.
* See the \ref Test "test" class.
*/
/** A function
*/
void func(int p);
/** Overloaded function taking variadic arguments
*/
void func(int p, ...);
/** A test */
class Test
{
};
| 363
|
C++
|
.cpp
| 16
| 21.125
| 70
| 0.658892
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,357
|
026_exception.cpp
|
doxygen_doxygen/testing/026_exception.cpp
|
// objective: test the \exception, \param, and \tparam commands
// check: class_test.xml
#include <stdexcept>
/** A Test class.
* More details about this class.
* @tparam T A template parameter.
*/
template<class T> class Test
{
public:
/** An example member function.
* \param p1 First parameter.
* \param p2 Second parameter.
* \exception std::out_of_range parameter is out of range.
* \retval 0 if p1 and p2 are equal
* \retval -1 if p1 is smaller than p2
* \retval 1 if p1 is bigger than p2
*/
int example(int p1,int p2) throw(std::out_of_range);
};
| 614
|
C++
|
.cpp
| 20
| 27.2
| 64
| 0.659359
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,358
|
073_typed_enum.cpp
|
doxygen_doxygen/testing/073_typed_enum.cpp
|
// objective: test underlying type and strongness for an enum
// check: 073__typed__enum_8cpp.xml
/** \file */
/** @brief A strongly-typed enum */
enum class E: unsigned short {};
/** @brief Strongly types enum when values that has the same name as the enum */
enum class Mem : unsigned char {
Bottom = 0,
NotMem = 1U << 0,
Ptr = 1U << 1,
Lval = 1U << 2,
Mem = Ptr | Lval,
Top = NotMem | Mem,
};
enum {
Unnamed1
};
enum {
Unnamed2
};
| 466
|
C++
|
.cpp
| 20
| 21.25
| 80
| 0.637188
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,359
|
083_decl_def.cpp
|
doxygen_doxygen/testing/083_decl_def.cpp
|
// objective: test for declaration and definition order independence: def first
// check: namespace_n.xml
// config: INPUT = $INPUTDIR/083_decl_def.cpp $INPUTDIR/decl_def.h
#include "test.h"
/** Namespace */
namespace N
{
/** Detailed docs. */
int var;
/** Detailed docs. */
void foo(int param)
{
}
}
| 305
|
C++
|
.cpp
| 14
| 20.5
| 79
| 0.721254
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,360
|
064_castoperator.cpp
|
doxygen_doxygen/testing/064_castoperator.cpp
|
// objective: test linking to the cast operator with and without const
// check: struct_foo.xml
/**
* @brief Foo
*
* - No autolink for operator int()
* - @ref operator int()
* - @ref operator int() "title"
* - Foo::operator int()
* - @ref Foo::operator int()
* - @ref Foo::operator int() "title"
*
* - No autolink for operator int() const
* - @ref operator int() const
* - @ref operator int() const "title"
* - Foo::operator int() const
* - @ref Foo::operator int() const
* - @ref Foo::operator int() const "title"
*/
struct Foo {
/** @brief Conversion to int */
operator int();
/** @brief Conversion to int const */
operator int() const;
};
| 666
|
C++
|
.cpp
| 25
| 24.68
| 70
| 0.642746
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,361
|
096_namespace_inheritance.cpp
|
doxygen_doxygen/testing/096_namespace_inheritance.cpp
|
// objective: test inheritance over namespace works the same in C++ and Fortran (see test 095)
// check: structm1_1_1t1.xml
// check: structm1_1_1t2.xml
// check: structm1_1_1t3.xml
// check: structm2_1_1t3.xml
// check: structm3_1_1t4.xml
// check: namespacem1.xml
// check: namespacem2.xml
// check: namespacem3.xml
namespace m1
{
struct t1
{
};
struct t2: public t1
{
};
struct t3: public t2
{
};
}
namespace m2
{
using namespace m1;
struct t3: public t2
{
};
}
namespace m3
{
using m2::t1;
struct t4: public t1
{
};
}
| 563
|
C++
|
.cpp
| 35
| 13.914286
| 94
| 0.68906
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,363
|
070_ref_variadic_template.cpp
|
doxygen_doxygen/testing/070_ref_variadic_template.cpp
|
// objective: test \ref command with a variadic template function
// check: 070__ref__variadic__template_8cpp.xml
/** \file
*
* @attention
* @parblock
* At the time of writing, the part between \<\> is totally ignored:
* %func<Args...>(Args... args) is interpreted as %func(Args... args).
*
* Beware that a function parameter with either a \& or \* operator,
* e.g. 'const Args&... args', requires \\link and \\ref to specify
* such parameter as verbatim, i.e. 'const Args&... args'. At the
* time of writing, the form %func(const Args&...) will fail, unless
* the function parameter was declared just as 'const Args&...'.
* @endparblock
*
* \ref Test::func(int,Args...)const "variadic template method"
*
* References to the variadic template function overloads:
* @li \ref func(int,Args&... args) "First overload"
* @li \ref func(int,Args&&... args) "Second overload"
* @li \ref func(int,const Args&... args) "Third overload"
* @li \ref func(int,const Args&&... args) "Fourth overload"
* @li \ref func(int,Args*... args) "Fifth overload"
* @li \ref func(int,Args**... args) "Sixth overload"
* @li \ref func(int,const Args*... args) "Seventh overload"
* @li \ref func(int,const Args**... args) "Eighth overload"
* @li \ref func(int,Args...) "Ninth overload"
*
* The following are interpreted the same:
* @li \ref func(int,const Args&... args) "without template argument"
* @li \ref func<Args...>(int,const Args&... args) "with template argument"
*
* See the \ref Test "test" class.
*/
/** A function
*/
void func(int p);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args&&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args&&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args*... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args**... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args*... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args**... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args... args);
/** A test */
class Test
{
public:
/** A variadic template method
*/
template <typename... Args>
void func(int p, Args... args) const;
};
| 2,752
|
C++
|
.cpp
| 83
| 31.385542
| 78
| 0.67181
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,365
|
080_extract_private_virtual.cpp
|
doxygen_doxygen/testing/080_extract_private_virtual.cpp
|
// objective: allow linking to private virtual functions
// check: class_interface.xml
// config: EXTRACT_PRIV_VIRTUAL = YES
/** @brief An interface */
class Interface {
public:
/**
* @brief Load things.
*
* Calls @ref doLoad().
*/
void load();
private:
/**
* @brief Pure virtual implementation for @ref load()
*
* Details.
*/
virtual void doLoad() = 0;
/**
* @brief Non-pure virtual function
*
* Details.
*/
virtual void doOtherStuff();
/* Undocumented, should not appear in the docs */
virtual void doSomethingUndocumented();
/** @brief A non-virtual private function, not extracted */
void someUtility();
};
| 720
|
C++
|
.cpp
| 30
| 19.366667
| 63
| 0.620438
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,366
|
071_enum_in_anon_ns.cpp
|
doxygen_doxygen/testing/071_enum_in_anon_ns.cpp
|
// objective: test that enum values in anonymous namespaces produce no warning
// check: namespace_a_namespace_1_1_0d130315250316227335362355006121037335073327177063.xml
namespace ANamespace { namespace {
enum class Boolean {
False,
True,
FileNotFound
};
}}
| 273
|
C++
|
.cpp
| 9
| 27.666667
| 90
| 0.796935
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,367
|
057_inlinenamespace.cpp
|
doxygen_doxygen/testing/057_inlinenamespace.cpp
|
// objective: test inline namespaces
// check: namespacelibrary.xml
// check: namespacelibrary_1_1v1.xml
// check: namespacelibrary_1_1v2.xml
/// the main namespace
namespace library
{
/// the first namespace
namespace v1
{
/// the class
class foo {
public:
/// member of the class
void member();
};
/// a method
void func();
/// a namespace
namespace NS {}
}
/// the inline namespace
inline namespace v2
{
/// the class
class foo {
public:
/// member of the class
void member();
};
/// a method
void func();
/// a namespace
namespace NS {}
}
}
| 758
|
C++
|
.cpp
| 36
| 14.138889
| 36
| 0.51595
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,369
|
067_link_varargs.cpp
|
doxygen_doxygen/testing/067_link_varargs.cpp
|
// objective: test \link command with function variadic arguments '...'
// check: 067__link__varargs_8cpp.xml
/** \file
* See \link func(int,...) the function\endlink for more info.
* See the \link Test test\endlink class.
*/
/** A function
*/
void func(int p);
/** Overloaded function taking variadic arguments
*/
void func(int p, ...);
/** A test */
class Test
{
};
| 379
|
C++
|
.cpp
| 16
| 22.125
| 71
| 0.679666
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,371
|
022_dot.cpp
|
doxygen_doxygen/testing/022_dot.cpp
|
// objective: test the \dot and \enddot commands
// check: indexpage.xml
// config: HAVE_DOT = YES
// config: DOTFILE_DIRS = $INPUTDIR
/*! class B */
class B {};
/*! class C */
class C {};
/*! \mainpage
Class relations expressed via an inline dot graph:
\dot
digraph example {
node [shape=record, fontname=Helvetica, fontsize=10];
b [ label="class B" URL="\ref B"];
c [ label="class C" URL="\ref C"];
b -> c [ arrowhead="open", style="dashed" ];
}
\enddot
*/
| 470
|
C++
|
.cpp
| 19
| 23.157895
| 55
| 0.662946
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,372
|
058_strong_enum.cpp
|
doxygen_doxygen/testing/058_strong_enum.cpp
|
// objective: test strong enum values with the same name in different contexts
// check: class_class.xml
// check: classns_1_1_class.xml
// check: classns2_1_1_class.xml
/**
* \file 058_strong_enum.cpp
* \brief Main file
*/
namespace ns {
/**
* \namespace ns
* \brief A namespace
*/
class Class
{
public:
enum class Enum1 {
Flag,
};
enum class Enum2 {
Flag,
};
};
/**
* \class Class
* \brief A class
*/
/**
* \enum Class::Enum1
* \brief A first enum class in ns
*
* \var Class::Enum1::Flag
* \brief A flag of Enum1 in ns
*/
/**
* \enum Class::Enum2
* \brief A second enum class in ns
*
* \var Class::Enum2::Flag
* \brief A flag of Enum2 in ns
*/
} /* namespace ns */
namespace ns2 {
/**
* \namespace ns2
* \brief A namespace
*/
class Class
{
public:
enum class Enum1 {
Flag,
};
enum class Enum2 {
Flag,
};
};
/**
* \class Class
* \brief A class
*/
/**
* \enum Class::Enum1
* \brief A first enum class in ns2
*
* \var Class::Enum1::Flag
* \brief A flag of Enum1 in ns2
*/
/**
* \enum Class::Enum2
* \brief A second enum class in ns2
*
* \var Class::Enum2::Flag
* \brief A flag of Enum2 in ns2
*/
} /* namespace ns2 */
class Class
{
public:
enum class Enum1 {
Flag,
};
enum class Enum2 {
Flag,
};
};
/**
* \class Class
* \brief A class
*/
/**
* \enum Class::Enum1
* \brief A first enum class in global scope
*
* \var Class::Enum1::Flag
* \brief A flag of Enum1 in global scope
*/
/**
* \enum Class::Enum2
* \brief A second enum class in global scope
*
* \var Class::Enum2::Flag
* \brief A flag of Enum2 in global scope
*/
| 1,620
|
C++
|
.cpp
| 104
| 13.615385
| 78
| 0.65328
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,373
|
103_include.cpp
|
doxygen_doxygen/testing/103_include.cpp
|
// objective: test if #include inside a class body will include the results as-is
// check: class_test.xml
/// Test clasx
class Test
{
#include "members.ci"
};
| 161
|
C++
|
.cpp
| 7
| 21.857143
| 81
| 0.745098
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,375
|
074_ref.cpp
|
doxygen_doxygen/testing/074_ref.cpp
|
// objective: test \ref command in combination with const
// check: struct_foo.xml
// check: namespacens.xml
#include <initializer_list>
/** @brief Foo class.
*
* @see @ref Foo::Foo() constructor for details.
* @see @ref Foo constant.
* @see @ref operator<<(int) "less than operator".
* @see @ref operator<<(int) const "const less than operator".
* @see @ref operator()(int) "call operator".
* @see @ref operator()(int) const "const call operator".
* @see @ref operator&=(const Foo&) "and equal operator".
* @see @ref operator&=(const Foo&) const "const and equal operator".
* @see @ref operator->*(int *) "member pointer operator".
*/
struct Foo {
/** Constructor */
Foo();
/**
* @brief Fun of two
*
* - fun() const
* - @ref fun() const
* - @ref fun() const "title"
*/
static Foo fun(Foo a, Foo b);
/** overloaded less than operator */
Foo& operator<< (int i);
/** overloaded const less than operator */
const Foo& operator<< (int i) const;
/** overloaded call operator */
int operator()(int i);
/** overloaded call operator */
int operator()(int i) const;
/** and equal operator */
Foo& operator&=(const Foo& rhs);
/** and equal operator */
const Foo& operator&=(const Foo& rhs) const;
/** Member pointer operator */
int* operator->*(int *p);
/** @brief Fun with itself */
Foo fun() const;
};
/**
@brief A namespace
- Link to an UDL w/o spaces: @link operator""_op @endlink
- Link to an UDL with spaces: @link operator""_oq @endlink
- Link to a function with spaces: @ref foo(std::initializer_list< int* >)
- Link to a function w/o spaces: @ref foo(std::initializer_list<int*>)
*/
namespace ns {
/** @brief An operator */
int operator""_op(unsigned long long);
/** @brief Another operator */
int operator "" _oq(unsigned long long);
/** @brief Function */
void foo(std::initializer_list<int*>);
}
| 1,893
|
C++
|
.cpp
| 59
| 29.644068
| 73
| 0.657866
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,376
|
082_decl_def.cpp
|
doxygen_doxygen/testing/082_decl_def.cpp
|
// objective: test for declaration and definition order independence: decl first
// check: namespace_n.xml
// config: INPUT = $INPUTDIR/decl_def.h $INPUTDIR/082_decl_def.cpp
#include "test.h"
/** Namespace */
namespace N
{
/** Detailed docs. */
int var;
/** Detailed docs. */
void foo(int param)
{
}
}
| 306
|
C++
|
.cpp
| 14
| 20.571429
| 80
| 0.722222
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,377
|
069_link_variadic_template.cpp
|
doxygen_doxygen/testing/069_link_variadic_template.cpp
|
// objective: test \link command with a variadic template function
// check: 069__link__variadic__template_8cpp.xml
/** \file
*
* @attention
* @parblock
* At the time of writing, the part between \<\> is totally ignored:
* %func<Args...>(Args... args) is interpreted as %func(Args... args).
*
* Beware that a function parameter with either a \& or \* operator,
* e.g. 'const Args&... args', requires \\link and \\ref to specify
* such parameter as verbatim, i.e. 'const Args&... args'. At the
* time of writing, the form %func(const Args&...) will fail, unless
* the function parameter was declared just as 'const Args&...'.
* @endparblock
*
* \link Test::func(int,Args...)const variadic template method\endlink
*
* Links to the variadic template function overloads:
* @li \link func(int,Args&... args) First overload\endlink
* @li \link func(int,Args&&... args) Second overload\endlink
* @li \link func(int,const Args&... args) Third overload\endlink
* @li \link func(int,const Args&&... args) Fourth overload\endlink
* @li \link func(int,Args*... args) Fifth overload\endlink
* @li \link func(int,Args**... args) Sixth overload\endlink
* @li \link func(int,const Args*... args) Seventh overload\endlink
* @li \link func(int,const Args**... args) Eighth overload\endlink
* @li \link func(int,Args...) Ninth overload\endlink
*
* The following are interpreted the same:
* @li \link func(int,const Args&... args) without template argument\endlink
* @li \link func<Args...>(int,const Args&... args) with template argument\endlink
*
* See the \link Test test\endlink class.
*/
/** A function
*/
void func(int p);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args&&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args&&... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args*... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args**... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args*... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, const Args**... args);
/** A variadic template function overload
*/
template <typename... Args>
void func(int p, Args... args);
/** A test */
class Test
{
public:
/** A variadic template method
*/
template <typename... Args>
void func(int p, Args... args) const;
};
| 2,840
|
C++
|
.cpp
| 83
| 32.445783
| 85
| 0.687067
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,378
|
075_argmatch.cpp
|
doxygen_doxygen/testing/075_argmatch.cpp
|
// objective: test argument matching in particular for unnamed types
// check: struct_foo.xml
/** @brief Foo */
struct Foo {
void foo(float value);
void foo(unsigned value);
void foo(unsigned long);
void foo(signed long);
void foo(const struct Foo);
void foo(const char * const, const double param2);
void foo(void(*fptr)(int x,int));
};
/** @brief Float */
void Foo::foo(float) {}
/** @brief Unsigned int */
void Foo::foo(unsigned value) {}
/** @brief Unnamed unsigned long */
void Foo::foo(unsigned long) {}
/** @brief Unnamed signed long */
void Foo::foo(signed long) {}
/** @brief Unnamed struct foo */
void Foo::foo(const struct Foo) {}
/** @brief Unnamed const pointer */
void Foo::foo(const char * const, const double param2) {}
/** @brief Function pointer */
void Foo::foo(void(*fptr)(int y,int z)) {}
| 845
|
C++
|
.cpp
| 26
| 30.153846
| 68
| 0.679803
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,379
|
104_typedef_merging.cpp
|
doxygen_doxygen/testing/104_typedef_merging.cpp
|
// objective: test typedef deduplication that properly considers scopes
// check: namespace_root.xml
// check: namespace_root_1_1_sub.xml
// check: struct_root_1_1_sub_1_1_struct.xml
namespace Root {
/** @brief A typedef */
typedef int Int;
/* Documentation comes later */
using Float = float;
namespace Sub {
/* Documentation comes later */
typedef double Double;
/** @brief A struct */
struct Struct {
/** @brief A typedef that doesn't get merged with the one in Sub */
typedef double Double;
};
/** @relatedalso Struct
* @brief A typedef in Sub that doesn't get merged with the one in Root
*/
typedef int Int;
/** @relatedalso Struct
* @brief A using declaration in Sub doesn't get merged with the one in Root
*/
using Float = float;
/** @brief Another typedef in Sub, not related to @ref Struct */
typedef double Double;
}
/** @brief A using declaration */
using Float = float;
/* Documentation comes later */
typedef bool BoolShouldNotBecomeFunction;
/** @brief Another struct */
struct AnotherStruct {};
/** @relatedalso AnotherStruct
* @brief A typedef that shouldn't become a function
*/
typedef bool BoolShouldNotBecomeFunction;
}
| 1,197
|
C++
|
.cpp
| 39
| 28.230769
| 78
| 0.727511
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,381
|
039_name.cpp
|
doxygen_doxygen/testing/039_name.cpp
|
// objective: test the \name and \short commands
// check: class_test.xml
/** \short A Test class.
*
* More details about this class.
*/
class Test
{
public:
/** \name A group of functions.
* \{
*/
/** foo function */
void foo();
/** bar function */
void bar();
/** \} */
/** ungrouped function */
void ungrouped();
};
| 373
|
C++
|
.cpp
| 20
| 15.05
| 48
| 0.560345
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,382
|
054_parblock.cpp
|
doxygen_doxygen/testing/054_parblock.cpp
|
// objective: test the \parblock command
// check: 054__parblock_8cpp.xml
/** @file */
/**
call by target-specific code to manage resources required by the client.
@param[in] client ID of client requesting resource.
@param[out] resource Requested resource
@param[in] parblock @parblock This is a test for the \@parblock
command.
A list if values for the parblock param:
- Item 1. This is short one-line description.
- Item 2. This is a long bullet item;
sometimes they wrap on multiple lines like this
one.
This is the second paragraph description for the
\@parblock parameter. Always end the text inside
the \@parblock command with an \@endparblock
command.
@endparblock
@param[out] test This is a test parameter for this function to see if
it is included in the parameter table
@param[in] p
@parblock First paragraph of the param description.
Second paragraph of the param description.
@endparblock
*/
void function(int client,int *resource,int parblock,int *test,int p);
/**
call by target-specific code to manage resources required by the client.
@param[in] client ID of client requesting resource.
@param[out] resource Requested resource
@param[in] parblock @parblock This is a test for the \@parblock
command.
A list if values for the parblock param:
- Item 1. This is short one-line description.
- Item 2. This is a long bullet item;
sometimes they wrap on multiple lines like this
one.
This is the second paragraph description for the
\@parblock parameter. Always end the text inside
the \@parblock command with an \@endparblock
command.
@endparblock
@param[out] test This is a test parameter for this function to see if
it is included in the parameter table
@param[in] p @parblock
First paragraph of the param description.
Second paragraph of the param description.
@endparblock
*/
void function_2(int client,int *resource,int parblock,int *test,int p);
| 2,555
|
C++
|
.cpp
| 51
| 36.196078
| 75
| 0.580192
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,383
|
060_details.cpp
|
doxygen_doxygen/testing/060_details.cpp
|
// objective: test the <details> and <summary> commands
// check: class_details_c_s_style.xml
// check: class_details_nested.xml
// check: class_details_summary_at_top.xml
// check: class_details_summary_at_bottom.xml
// check: class_details_without_summary.xml
// check: class_details_multi_summary.xml
/**
* Before details.
* <details>
* <summary>Summary on top</summary>
* Details body
* </details>
* After details.
*/
class DetailsSummaryAtTop {};
/**
* Before details.
* <details>
* Details body without summary
* </details>
* After details.
*/
class DetailsWithoutSummary {};
/**
* Before details.
* <details>
* Details body
* <summary>Summary at the bottom</summary>
* </details>
* After details.
*/
class DetailsSummaryAtBottom {};
/**
* <summary>Summary C# style</summary>
* Details below
*/
class DetailsCSStyle {};
/**
* Nested details
* <details>
* <summary>Summary at top</summary>
* Some text
* <details>
* More details.
* <summary>Nested summary at bottom</summary>
* </details>
* </details>
*/
class DetailsNested {};
/**
* Multiple summary sections
* <details>
* <summary>First summary</summary>
* More details.
* <summary>Second summary</summary>
* More details.
* <summary>Third summary</summary>
* Last part.
* </details>
*/
class DetailsMultiSummary {};
| 1,338
|
C++
|
.cpp
| 62
| 19.790323
| 55
| 0.70315
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,384
|
085_tooltip.cpp
|
doxygen_doxygen/testing/085_tooltip.cpp
|
// objective: test tooltip in XHTML
// check: 085__tooltip_8cpp.xml
// config: SOURCE_BROWSER=YES
/** \file */
#include <stdio.h>
/** \brief the unit */
FILE *unit = NULL;
/** a general open macro */
#define FOPEN_MACRO(fn ,mod) \
if ((unit = fopen(fn, mod)) == NULL) \
{ \
msg(OPEN_ERR,strerror(errno)); \
}
/** a general close macro */
#define FCLOSE_MACRO \
if (fclose(unit) != 0) \
{ \
msg(CLOSE_ERR,strerror(errno)); \
}
| 568
|
C++
|
.cpp
| 19
| 27.684211
| 40
| 0.485348
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,385
|
more_100_d.cpp
|
doxygen_doxygen/testing/more_100_d.cpp
|
namespace NS
{
enum ED {
ED1,
ED2
};
}
/**
* @namespace NS
*
* @ingroup D
*
* Namespace NS.
*/
/**
* @defgroup D D
*/
namespace NS
{
/**
* @enum ED
*
* @ingroup D
*
* Enum ED.
*/
/**
* @var ED ED::ED1
*
* Enumerator ED1.
*/
/**
* @var ED ED::ED2
*
* Enumerator ED2.
*/
}
| 310
|
C++
|
.cpp
| 37
| 6.324324
| 18
| 0.522388
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,386
|
059_template.cpp
|
doxygen_doxygen/testing/059_template.cpp
|
// objective: test if A<B>::C within backticks is properly handled
// check: struct_n_1_1allocator__traits.xml
namespace N
{
/**
* @brief Uniform interface to all allocator types.
*/
template<typename _Alloc> struct allocator_traits
{
/**
* @brief The allocator's const pointer type.
*
*
* `Alloc::const_pointer` if that type exists, otherwise
* `pointer_traits<pointer>::rebind<const value_type>`.
*
*/
using const_pointer = typename _Ptr<__c_pointer, const value_type>::type;
};
}
| 542
|
C++
|
.cpp
| 20
| 23.3
| 77
| 0.659004
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,387
|
047_return.cpp
|
doxygen_doxygen/testing/047_return.cpp
|
// objective: test the \result, \return, and \returns commands
// check: 047__return_8cpp.xml
/** \file */
/** Test function 1.
* \result A integer.
*/
int func1();
/** Test function 2.
* \return A integer.
*/
int func2();
/** Test function 3.
* \returns A integer.
*/
int func3();
| 296
|
C++
|
.cpp
| 15
| 18
| 62
| 0.641304
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,388
|
041_overload.cpp
|
doxygen_doxygen/testing/041_overload.cpp
|
// objective: test the \overload command
// check: class_test.xml
class Rect;
class Point;
class Test
{
public:
void drawRect(int,int,int,int);
void drawRect(const Rect &r);
void drawRect(const Point &topLeft,const Point &bottomRight);
};
void Test::drawRect(int x,int y,int w,int h) {}
void Test::drawRect(const Rect &r) {}
/*! \overload
*
* More text.
*/
void Test::drawRect(const Point &topLeft,const Point &bottomRight) {}
/*! \class Test
* \brief A short description.
*
* More text.
*/
/*! \fn void Test::drawRect(int x,int y,int w,int h)
* This command draws a rectangle with a left upper corner at ( \a x , \a y ),
* width \a w and height \a h.
*/
/*!
* \overload void Test::drawRect(const Rect &r)
*/
| 748
|
C++
|
.cpp
| 30
| 22.733333
| 78
| 0.676471
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,389
|
example_test.cpp
|
doxygen_doxygen/testing/example_test.cpp
|
/** The main function */
void main()
{
const char* a = "Some special character here: ";
Test t;
t.example();
}
| 121
|
C++
|
.cpp
| 7
| 15.142857
| 52
| 0.625
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,390
|
046_related.cpp
|
doxygen_doxygen/testing/046_related.cpp
|
// objective: test the \related, \relatedalso, \see, and \sa commands
// check: class_test.xml
// check: 046__related_8cpp.xml
/** @file */
/** A test class
* @see Test::method()
*/
class Test
{
public:
/** A method */
void method();
};
/*!
* A function.
* \related Test
* \sa another()
*/
void function();
/*!
* Another function
* \relatedalso Test
*/
void another();
| 395
|
C++
|
.cpp
| 24
| 14.416667
| 69
| 0.626703
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,391
|
009_bug.cpp
|
doxygen_doxygen/testing/009_bug.cpp
|
// objective: test the \bug, \deprecated, \todo, \test, and \xrefitem commands
// check: class_bug.xml
// check: class_deprecated.xml
// check: class_todo.xml
// check: class_test.xml
// check: class_reminder.xml
// check: bug.xml
// check: deprecated.xml
// check: todo.xml
// check: test.xml
// check: reminders.xml
// config: ALIASES = "reminder=\xrefitem reminders \"Reminder\" \"Reminders\""
/** \bug Class bug. */
class Bug
{
public:
/** Description
* \bug Function bug
* - list item 1 in bug
* - list item 2 in bug
*
* More text.
*/
void foo();
};
/** \deprecated This class is deprecated */
class Deprecated
{
public:
/** Do deprecated things.
* \deprecated No not use this function anymore.
*/
void deprecated();
};
/** \todo This still needs to be done. */
class Todo
{
public:
/** \todo more things to do here */
void todo();
};
/** \test This is part of testing */
class Test
{
public:
/** \test more things to test. */
void test();
};
/** \reminder A reminder */
class Reminder
{
public:
/** \reminder Need to rework this before the next release. */
void reminder();
};
| 1,187
|
C++
|
.cpp
| 55
| 18.781818
| 78
| 0.638222
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,392
|
defgen.cpp
|
doxygen_doxygen/src/defgen.cpp
|
/******************************************************************************
*
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include <stdlib.h>
#include "portable.h"
#include "defgen.h"
#include "doxygen.h"
#include "message.h"
#include "config.h"
#include "classlist.h"
#include "util.h"
#include "defargs.h"
#include "outputgen.h"
#include "dot.h"
#include "dotclassgraph.h"
#include "arguments.h"
#include "memberlist.h"
#include "namespacedef.h"
#include "filedef.h"
#include "filename.h"
#include "dir.h"
#include "textstream.h"
#define DEF_DB(x)
static inline void writeDEFString(TextStream &t,const QCString &s)
{
t << '\'';
if (!s.isEmpty())
{
const char* p=s.data();
char c = 0;
while ((c = *(p++)))
{
if (c == '\'') t << '\\';
t << c;
}
}
t << '\'';
}
static void generateDEFForMember(const MemberDef *md,
TextStream &t,
const Definition *def,
const QCString &prefix)
{
QCString memPrefix;
// + declaration
// - reimplements
// - reimplementedBy
// - exceptions
// - const/volatile specifiers
// - examples
// + source definition
// - source references
// - source referenced by
// - include code
if (md->memberType()==MemberType::EnumValue) return;
QCString scopeName;
if (md->getClassDef())
scopeName=md->getClassDef()->name();
else if (md->getNamespaceDef())
scopeName=md->getNamespaceDef()->name();
t << " " << prefix << "-member = {\n";
memPrefix = " ";
memPrefix.append( prefix );
memPrefix.append( "-mem-" );
QCString memType;
bool isFunc=FALSE;
switch (md->memberType())
{
case MemberType::Define: memType="define"; break;
case MemberType::EnumValue: ASSERT(0); break;
case MemberType::Property: memType="property"; break;
case MemberType::Event: memType="event"; break;
case MemberType::Variable: memType="variable"; break;
case MemberType::Typedef: memType="typedef"; break;
case MemberType::Enumeration: memType="enum"; break;
case MemberType::Interface: memType="interface"; break;
case MemberType::Service: memType="service"; break;
case MemberType::Sequence: memType="sequence"; break;
case MemberType::Dictionary: memType="dictionary"; break;
case MemberType::Function: memType="function"; isFunc=TRUE; break;
case MemberType::Signal: memType="signal"; isFunc=TRUE; break;
case MemberType::Friend: memType="friend"; isFunc=TRUE; break;
case MemberType::DCOP: memType="dcop"; isFunc=TRUE; break;
case MemberType::Slot: memType="slot"; isFunc=TRUE; break;
}
t << memPrefix << "kind = '" << memType << "';\n";
t << memPrefix << "id = '"
<< md->getOutputFileBase() << "_1" << md->anchor()
<< "';\n";
t << memPrefix << "virt = ";
switch (md->virtualness())
{
case Specifier::Normal: t << "normal;\n"; break;
case Specifier::Virtual: t << "virtual;\n"; break;
case Specifier::Pure: t << "pure-virtual;\n"; break;
default: ASSERT(0);
}
t << memPrefix << "prot = ";
switch(md->protection())
{
case Protection::Public: t << "public;\n"; break;
case Protection::Protected: t << "protected;\n"; break;
case Protection::Private: t << "private;\n"; break;
case Protection::Package: t << "package;\n"; break;
}
if (md->memberType()!=MemberType::Define &&
md->memberType()!=MemberType::Enumeration
)
{
QCString typeStr = replaceAnonymousScopes(md->typeString());
t << memPrefix << "type = <<_EnD_oF_dEf_TeXt_\n" << typeStr << "\n"
<< "_EnD_oF_dEf_TeXt_;\n";
}
t << memPrefix << "name = '" << md->name() << "';\n";
if (isFunc) //function
{
const ArgumentList &defAl = md->argumentList();
ArgumentList declAl = *stringToArgumentList(md->getLanguage(),md->argsString());
QCString fcnPrefix = " " + memPrefix + "param-";
auto defIt = defAl.begin();
for (const Argument &a : declAl)
{
const Argument *defArg = nullptr;
if (defIt!=defAl.end())
{
defArg = &(*defIt);
++defIt;
}
t << memPrefix << "param = {\n";
if (!a.attrib.isEmpty())
{
t << fcnPrefix << "attributes = ";
writeDEFString(t,a.attrib);
t << ";\n";
}
if (!a.type.isEmpty())
{
t << fcnPrefix << "type = <<_EnD_oF_dEf_TeXt_\n"
<< a.type << "\n_EnD_oF_dEf_TeXt_;\n";
}
if (!a.name.isEmpty())
{
t << fcnPrefix << "declname = ";
writeDEFString(t,a.name);
t << ";\n";
}
if (defArg && !defArg->name.isEmpty() && defArg->name!=a.name)
{
t << fcnPrefix << "defname = ";
writeDEFString(t,defArg->name);
t << ";\n";
}
if (!a.array.isEmpty())
{
t << fcnPrefix << "array = ";
writeDEFString(t,a.array);
t << ";\n";
}
if (!a.defval.isEmpty())
{
t << fcnPrefix << "defval = <<_EnD_oF_dEf_TeXt_\n"
<< a.defval << "\n_EnD_oF_dEf_TeXt_;\n";
}
t << " }; /*" << fcnPrefix << "-param */\n";
}
}
else if ( md->memberType()==MemberType::Define
&& md->argsString()!=nullptr)
{
QCString defPrefix = " " + memPrefix + "def-";
for (const Argument &a : md->argumentList())
{
t << memPrefix << "param = {\n";
t << defPrefix << "name = '" << a.type << "';\n";
t << " }; /*" << defPrefix << "-param */\n";
}
}
if (!md->initializer().isEmpty())
{
t << memPrefix << "initializer = <<_EnD_oF_dEf_TeXt_\n"
<< md->initializer() << "\n_EnD_oF_dEf_TeXt_;\n";
}
// TODO: exceptions, const volatile
if (md->memberType()==MemberType::Enumeration) // enum
{
for (const auto &emd : md->enumFieldList())
{
t << memPrefix << "enum = { enum-name = " << emd->name() << ';';
if (!emd->initializer().isEmpty())
{
t << " enum-value = ";
writeDEFString(t,emd->initializer());
t << ';';
}
t << " };\n";
}
}
t << memPrefix << "desc-file = '" << md->getDefFileName() << "';\n";
t << memPrefix << "desc-line = '" << md->getDefLine() << "';\n";
t << memPrefix << "briefdesc = <<_EnD_oF_dEf_TeXt_\n"
<< md->briefDescription() << "\n_EnD_oF_dEf_TeXt_;\n";
t << memPrefix << "documentation = <<_EnD_oF_dEf_TeXt_\n"
<< md->documentation() << "\n_EnD_oF_dEf_TeXt_;\n";
//printf("md->getReferencesMembers()=%p\n",md->getReferencesMembers());
QCString refPrefix = " " + memPrefix + "ref-";
auto refList = md->getReferencesMembers();
for (const auto &rmd : refList)
{
if (rmd->getStartBodyLine()!=-1 && rmd->getBodyDef())
{
t << memPrefix << "referenceto = {\n";
t << refPrefix << "id = '"
<< rmd->getBodyDef()->getOutputFileBase()
<< "_1" // encoded ':' character (see util.cpp:convertNameToFile)
<< rmd->anchor() << "';\n";
t << refPrefix << "line = '"
<< rmd->getStartBodyLine() << "';\n";
QCString scope = rmd->getScopeString();
QCString name = rmd->name();
if (!scope.isEmpty() && scope!=def->name())
{
name.prepend(scope+"::");
}
t << refPrefix << "name = ";
writeDEFString(t,name);
t << ';' << "\n };\n";
}
}
auto refByList = md->getReferencedByMembers();
for (const auto &rmd : refByList)
{
if (rmd->getStartBodyLine()!=-1 && rmd->getBodyDef())
{
t << memPrefix << "referencedby = {\n";
t << refPrefix << "id = '"
<< rmd->getBodyDef()->getOutputFileBase()
<< "_1" // encoded ':' character (see util.cpp:convertNameToFile)
<< rmd->anchor() << "';\n";
t << refPrefix << "line = '"
<< rmd->getStartBodyLine() << "';\n";
QCString scope = rmd->getScopeString();
QCString name = rmd->name();
if (!scope.isEmpty() && scope!=def->name())
{
name.prepend(scope+"::");
}
t << refPrefix << "name = ";
writeDEFString(t,name);
t << ';' << "\n };\n";
}
}
t << " }; /* " << prefix << "-member */\n";
}
static void generateDEFClassSection(const ClassDef *cd,
TextStream &t,
const MemberList *ml,
const QCString &kind)
{
if (cd && ml && !ml->empty())
{
t << " cp-section = {\n";
t << " sec-kind = '" << kind << "';\n";
for (const auto &md : *ml)
{
generateDEFForMember(md,t,cd,"sec");
}
t << " }; /* cp-section */\n";
}
}
static void generateDEFForClass(const ClassDef *cd,TextStream &t)
{
// + brief description
// + detailed description
// - template arguments
// - include files
// + inheritance diagram
// + list of direct super classes
// + list of direct sub classes
// + collaboration diagram
// - list of all members
// + user defined member sections
// + standard member sections
// + detailed member documentation
// - examples
if (cd->isReference()) return; // skip external references.
if (cd->name().find('@')!=-1) return; // skip anonymous compounds.
if (cd->templateMaster()!=nullptr) return; // skip generated template instances.
t << cd->compoundTypeString() << " = {\n";
t << " cp-id = '" << cd->getOutputFileBase() << "';\n";
t << " cp-name = '" << cd->name() << "';\n";
for (const auto &bcd : cd->baseClasses())
{
t << " cp-ref = {\n" << " ref-type = base;\n";
t << " ref-id = '"
<< bcd.classDef->getOutputFileBase() << "';\n";
t << " ref-prot = ";
switch (bcd.prot)
{
case Protection::Public: t << "public;\n"; break;
case Protection::Package: // package scope is not possible
case Protection::Protected: t << "protected;\n"; break;
case Protection::Private: t << "private;\n"; break;
}
t << " ref-virt = ";
switch(bcd.virt)
{
case Specifier::Normal: t << "non-virtual;"; break;
case Specifier::Virtual: t << "virtual;"; break;
case Specifier::Pure: t << "pure-virtual;"; break;
}
t << "\n };\n";
}
for (const auto &bcd : cd->subClasses())
{
t << " cp-ref = {\n" << " ref-type = derived;\n";
t << " ref-id = '"
<< bcd.classDef->getOutputFileBase() << "';\n";
t << " ref-prot = ";
switch (bcd.prot)
{
case Protection::Public: t << "public;\n"; break;
case Protection::Package: // packet scope is not possible!
case Protection::Protected: t << "protected;\n"; break;
case Protection::Private: t << "private;\n"; break;
}
t << " ref-virt = ";
switch (bcd.virt)
{
case Specifier::Normal: t << "non-virtual;"; break;
case Specifier::Virtual: t << "virtual;"; break;
case Specifier::Pure: t << "pure-virtual;"; break;
}
t << "\n };\n";
}
size_t numMembers = 0;
for (const auto &ml : cd->getMemberLists())
{
if (!ml->listType().isDetailed())
{
numMembers+=ml->size();
}
}
if (numMembers>0)
{
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PubTypes()),"public-type");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::Interfaces()),"interfaces");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::Services()),"services");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PubMethods()),"public-func");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PubAttribs()),"public-attrib");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PubSlots()),"public-slot");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::Signals()),"signal");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::DcopMethods()),"dcop-func");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::Properties()),"property");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PubStaticMethods()),"public-static-func");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PubStaticAttribs()),"public-static-attrib");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::ProTypes()),"protected-type");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::ProMethods()),"protected-func");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::ProAttribs()),"protected-attrib");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::ProSlots()),"protected-slot");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::ProStaticMethods()),"protected-static-func");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::ProStaticAttribs()),"protected-static-attrib");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PriTypes()),"private-type");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PriMethods()),"private-func");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PriAttribs()),"private-attrib");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PriSlots()),"private-slot");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PriStaticMethods()),"private-static-func");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::PriStaticAttribs()),"private-static-attrib");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::Friends()),"signal");
generateDEFClassSection(cd,t,cd->getMemberList(MemberListType::Related()),"related");
}
t << " cp-filename = '" << cd->getDefFileName() << "';\n";
t << " cp-fileline = '" << cd->getDefLine() << "';\n";
t << " cp-briefdesc = <<_EnD_oF_dEf_TeXt_\n"
<< cd->briefDescription() << "\n_EnD_oF_dEf_TeXt_;\n";
t << " cp-documentation = <<_EnD_oF_dEf_TeXt_\n"
<< cd->documentation() << "\n_EnD_oF_dEf_TeXt_;\n";
DotClassGraph inheritanceGraph(cd,GraphType::Inheritance);
if (!inheritanceGraph.isTrivial())
{
t << " cp-inheritancegraph = <<_EnD_oF_dEf_TeXt_\n";
inheritanceGraph.writeDEF(t);
t << "\n_EnD_oF_dEf_TeXt_;\n";
}
DotClassGraph collaborationGraph(cd,GraphType::Collaboration);
if (!collaborationGraph.isTrivial())
{
t << " cp-collaborationgraph = <<_EnD_oF_dEf_TeXt_\n";
collaborationGraph.writeDEF(t);
t << "\n_EnD_oF_dEf_TeXt_;\n";
}
t << "}; /* " << cd->compoundTypeString() << " */\n";
}
static void generateDEFSection(const Definition *d,
TextStream &t,
const MemberList *ml,
const QCString &kind)
{
if (ml && !ml->empty())
{
t << " " << kind << " = {\n";
for (const auto &md : *ml)
{
generateDEFForMember(md,t,d,kind);
}
t << " };\n";
}
}
static void generateDEFForNamespace(const NamespaceDef *nd,TextStream &t)
{
if (nd->isReference()) return; // skip external references
t << " namespace = {\n";
t << " ns-id = '" << nd->getOutputFileBase() << "';\n";
t << " ns-name = ";
writeDEFString(t,nd->name());
t << ";\n";
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecDefineMembers()),"define");
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecProtoMembers()),"prototype");
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecTypedefMembers()),"typedef");
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecSequenceMembers()),"sequence");
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecDictionaryMembers()),"dictionary");
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecEnumMembers()),"enum");
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecFuncMembers()),"func");
generateDEFSection(nd,t,nd->getMemberList(MemberListType::DecVarMembers()),"var");
t << " ns-filename = '" << nd->getDefFileName() << "';\n";
t << " ns-fileline = '" << nd->getDefLine() << "';\n";
t << " ns-briefdesc = <<_EnD_oF_dEf_TeXt_\n"
<< nd->briefDescription() << "\n_EnD_oF_dEf_TeXt_;\n";
t << " ns-documentation = <<_EnD_oF_dEf_TeXt_\n"
<< nd->documentation() << "\n_EnD_oF_dEf_TeXt_;\n";
t << " };\n";
}
static void generateDEFForFile(const FileDef *fd,TextStream &t)
{
if (fd->isReference()) return; // skip external references
t << "file = {\n";
t << " file-id = '" << fd->getOutputFileBase() << "';\n";
t << " file-name = ";
writeDEFString(t,fd->name());
t << ";\n";
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecDefineMembers()),"define");
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecProtoMembers()),"prototype");
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecTypedefMembers()),"typedef");
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecSequenceMembers()),"sequence");
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecDictionaryMembers()),"dictionary");
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecEnumMembers()),"enum");
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecFuncMembers()),"func");
generateDEFSection(fd,t,fd->getMemberList(MemberListType::DecVarMembers()),"var");
t << " file-full-name = '" << fd->getDefFileName() << "';\n";
t << " file-first-line = '" << fd->getDefLine() << "';\n";
t << " file-briefdesc = <<_EnD_oF_dEf_TeXt_\n"
<< fd->briefDescription() << "\n_EnD_oF_dEf_TeXt_;\n";
t << " file-documentation = <<_EnD_oF_dEf_TeXt_\n"
<< fd->documentation() << "\n_EnD_oF_dEf_TeXt_;\n";
t << "}; /* file */\n";
}
void generateDEF()
{
QCString outputDirectory = Config_getString(OUTPUT_DIRECTORY)+"/def";
Dir defDir(outputDirectory.str());
if (!defDir.exists() && !defDir.mkdir(outputDirectory.str()))
{
err("Could not create def directory in %s\n",qPrint(outputDirectory));
return;
}
QCString fileName=outputDirectory+"/doxygen.def";
std::ofstream f = Portable::openOutputStream(fileName);
if (!f.is_open())
{
err("Cannot open file %s for writing!\n",qPrint(fileName));
return;
}
TextStream t(&f);
t << "AutoGen Definitions dummy;\n";
if (Doxygen::classLinkedMap->size()+
Doxygen::inputNameLinkedMap->size()+
Doxygen::namespaceLinkedMap->size()>0)
{
for (const auto &cd : *Doxygen::classLinkedMap)
{
generateDEFForClass(cd.get(),t);
}
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
generateDEFForFile(fd.get(),t);
}
}
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
generateDEFForNamespace(nd.get(),t);
}
}
else
{
t << "dummy_value = true;\n";
}
}
| 19,249
|
C++
|
.cpp
| 512
| 33.029297
| 114
| 0.611028
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,393
|
doxygen.cpp
|
doxygen_doxygen/src/doxygen.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2015 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.
*
*/
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <sys/stat.h>
#include <algorithm>
#include <unordered_map>
#include <memory>
#include <cinttypes>
#include <chrono>
#include <clocale>
#include <locale>
#include "version.h"
#include "doxygen.h"
#include "scanner.h"
#include "entry.h"
#include "index.h"
#include "indexlist.h"
#include "message.h"
#include "config.h"
#include "util.h"
#include "pre.h"
#include "tagreader.h"
#include "dot.h"
#include "msc.h"
#include "docparser.h"
#include "dirdef.h"
#include "outputlist.h"
#include "declinfo.h"
#include "htmlgen.h"
#include "latexgen.h"
#include "mangen.h"
#include "language.h"
#include "debug.h"
#include "htmlhelp.h"
#include "qhp.h"
#include "sitemap.h"
#include "ftvhelp.h"
#include "defargs.h"
#include "rtfgen.h"
#include "sqlite3gen.h"
#include "xmlgen.h"
#include "docbookgen.h"
#include "defgen.h"
#include "perlmodgen.h"
#include "reflist.h"
#include "pagedef.h"
#include "commentcnv.h"
#include "cmdmapper.h"
#include "searchindex_js.h"
#include "parserintf.h"
#include "htags.h"
#include "pycode.h"
#include "pyscanner.h"
#include "fortrancode.h"
#include "fortranscanner.h"
#include "xmlcode.h"
#include "sqlcode.h"
#include "lexcode.h"
#include "lexscanner.h"
#include "code.h"
#include "portable.h"
#include "vhdljjparser.h"
#include "vhdldocgen.h"
#include "vhdlcode.h"
#include "eclipsehelp.h"
#include "cite.h"
#include "markdown.h"
#include "arguments.h"
#include "memberlist.h"
#include "layout.h"
#include "groupdef.h"
#include "classlist.h"
#include "namespacedef.h"
#include "filename.h"
#include "membername.h"
#include "membergroup.h"
#include "docsets.h"
#include "formula.h"
#include "settings.h"
#include "fileparser.h"
#include "emoji.h"
#include "plantuml.h"
#include "stlsupport.h"
#include "threadpool.h"
#include "clangparser.h"
#include "symbolresolver.h"
#include "regex.h"
#include "aliases.h"
#include "fileinfo.h"
#include "dir.h"
#include "conceptdef.h"
#include "trace.h"
#include "moduledef.h"
#include "stringutil.h"
#include <sqlite3.h>
#if USE_LIBCLANG
#include <clang/Basic/Version.h>
#endif
// provided by the generated file resources.cpp
extern void initResources();
#if !defined(_WIN32) || defined(__CYGWIN__)
#include <signal.h>
#define HAS_SIGNALS
#endif
// globally accessible variables
ClassLinkedMap *Doxygen::classLinkedMap = nullptr;
ClassLinkedMap *Doxygen::hiddenClassLinkedMap = nullptr;
ConceptLinkedMap *Doxygen::conceptLinkedMap = nullptr;
NamespaceLinkedMap *Doxygen::namespaceLinkedMap = nullptr;
MemberNameLinkedMap *Doxygen::memberNameLinkedMap = nullptr;
MemberNameLinkedMap *Doxygen::functionNameLinkedMap = nullptr;
FileNameLinkedMap *Doxygen::inputNameLinkedMap = nullptr;
GroupLinkedMap *Doxygen::groupLinkedMap = nullptr;
PageLinkedMap *Doxygen::pageLinkedMap = nullptr;
PageLinkedMap *Doxygen::exampleLinkedMap = nullptr;
StringUnorderedSet Doxygen::inputPaths;
FileNameLinkedMap *Doxygen::includeNameLinkedMap = nullptr; // include names
FileNameLinkedMap *Doxygen::exampleNameLinkedMap = nullptr; // examples
FileNameLinkedMap *Doxygen::imageNameLinkedMap = nullptr; // images
FileNameLinkedMap *Doxygen::dotFileNameLinkedMap = nullptr; // dot files
FileNameLinkedMap *Doxygen::mscFileNameLinkedMap = nullptr; // msc files
FileNameLinkedMap *Doxygen::diaFileNameLinkedMap = nullptr; // dia files
FileNameLinkedMap *Doxygen::plantUmlFileNameLinkedMap = nullptr;// plantuml files
NamespaceAliasInfoMap Doxygen::namespaceAliasMap; // all namespace aliases
StringMap Doxygen::tagDestinationMap; // all tag locations
StringUnorderedSet Doxygen::tagFileSet; // all tag file names
StringUnorderedSet Doxygen::expandAsDefinedSet; // all macros that should be expanded
MemberGroupInfoMap Doxygen::memberGroupInfoMap; // dictionary of the member groups heading
std::unique_ptr<PageDef> Doxygen::mainPage;
std::unique_ptr<NamespaceDef> Doxygen::globalNamespaceDef;
NamespaceDefMutable *Doxygen::globalScope;
bool Doxygen::parseSourcesNeeded = FALSE;
SearchIndexIntf Doxygen::searchIndex;
SymbolMap<Definition>*Doxygen::symbolMap;
ClangUsrMap *Doxygen::clangUsrMap = nullptr;
Cache<std::string,LookupInfo> *Doxygen::typeLookupCache;
Cache<std::string,LookupInfo> *Doxygen::symbolLookupCache;
DirLinkedMap *Doxygen::dirLinkedMap;
DirRelationLinkedMap Doxygen::dirRelations;
ParserManager *Doxygen::parserManager = nullptr;
QCString Doxygen::htmlFileExtension;
bool Doxygen::suppressDocWarnings = FALSE;
QCString Doxygen::filterDBFileName;
IndexList *Doxygen::indexList;
QCString Doxygen::spaces;
bool Doxygen::generatingXmlOutput = FALSE;
DefinesPerFileList Doxygen::macroDefinitions;
bool Doxygen::clangAssistedParsing = FALSE;
QCString Doxygen::verifiedDotPath;
InputFileEncodingList Doxygen::inputFileEncodingList;
std::mutex Doxygen::countFlowKeywordsMutex;
std::mutex Doxygen::addExampleMutex;
StaticInitMap Doxygen::staticInitMap;
// locally accessible globals
static std::multimap< std::string, const Entry* > g_classEntries;
static StringVector g_inputFiles;
static OutputList *g_outputList = nullptr; // list of output generating objects
static StringSet g_usingDeclarations; // used classes
static bool g_successfulRun = FALSE;
static bool g_dumpSymbolMap = FALSE;
// keywords recognized as compounds
static const StringUnorderedSet g_compoundKeywords =
{ "template class", "template struct", "class", "struct", "union", "interface", "exception" };
void clearAll()
{
g_inputFiles.clear();
//g_excludeNameDict.clear();
//delete g_outputList; g_outputList=nullptr;
Doxygen::classLinkedMap->clear();
Doxygen::hiddenClassLinkedMap->clear();
Doxygen::conceptLinkedMap->clear();
Doxygen::namespaceLinkedMap->clear();
Doxygen::pageLinkedMap->clear();
Doxygen::exampleLinkedMap->clear();
Doxygen::inputNameLinkedMap->clear();
Doxygen::includeNameLinkedMap->clear();
Doxygen::exampleNameLinkedMap->clear();
Doxygen::imageNameLinkedMap->clear();
Doxygen::dotFileNameLinkedMap->clear();
Doxygen::mscFileNameLinkedMap->clear();
Doxygen::diaFileNameLinkedMap->clear();
Doxygen::plantUmlFileNameLinkedMap->clear();
Doxygen::tagDestinationMap.clear();
SectionManager::instance().clear();
CitationManager::instance().clear();
Doxygen::mainPage.reset();
FormulaManager::instance().clear();
}
class Statistics
{
public:
Statistics() {}
void begin(const char *name)
{
msg("%s", name);
stats.emplace_back(name,0);
startTime = std::chrono::steady_clock::now();
}
void end()
{
std::chrono::steady_clock::time_point endTime = std::chrono::steady_clock::now();
stats.back().elapsed = static_cast<double>(std::chrono::duration_cast<
std::chrono::microseconds>(endTime - startTime).count())/1000000.0;
warn_flush();
}
void print()
{
bool restore=FALSE;
if (Debug::isFlagSet(Debug::Time))
{
Debug::clearFlag(Debug::Time);
restore=TRUE;
}
msg("----------------------\n");
for (const auto &s : stats)
{
msg("Spent %.6f seconds in %s",s.elapsed,s.name);
}
if (restore) Debug::setFlag(Debug::Time);
}
private:
struct stat
{
const char *name;
double elapsed;
//stat() : name(nullptr),elapsed(0) {}
stat(const char *n, double el) : name(n),elapsed(el) {}
};
std::vector<stat> stats;
std::chrono::steady_clock::time_point startTime;
} g_s;
static void addMemberDocs(const Entry *root,MemberDefMutable *md, const QCString &funcDecl,
const ArgumentList *al,bool over_load,TypeSpecifier spec);
static void findMember(const Entry *root,
const QCString &relates,
const QCString &type,
const QCString &args,
QCString funcDecl,
bool overloaded,
bool isFunc
);
enum FindBaseClassRelation_Mode
{
TemplateInstances,
DocumentedOnly,
Undocumented
};
static bool findClassRelation(
const Entry *root,
Definition *context,
ClassDefMutable *cd,
const BaseInfo *bi,
const TemplateNameMap &templateNames,
/*bool insertUndocumented*/
FindBaseClassRelation_Mode mode,
bool isArtificial
);
//----------------------------------------------------------------------------
static Definition *findScopeFromQualifiedName(NamespaceDefMutable *startScope,const QCString &n,
FileDef *fileScope,const TagInfo *tagInfo);
static void resolveTemplateInstanceInType(const Entry *root,const Definition *scope,const MemberDef *md);
static void addPageToContext(PageDef *pd,Entry *root)
{
if (root->parent()) // add the page to it's scope
{
QCString scope = root->parent()->name;
if (root->parent()->section.isPackageDoc())
{
scope=substitute(scope,".","::");
}
scope = stripAnonymousNamespaceScope(scope);
scope+="::"+pd->name();
Definition *d = findScopeFromQualifiedName(Doxygen::globalScope,scope,nullptr,root->tagInfo());
if (d)
{
pd->setPageScope(d);
}
}
}
static void addRelatedPage(Entry *root)
{
GroupDef *gd=nullptr;
for (const Grouping &g : root->groups)
{
if (!g.groupname.isEmpty() && (gd=Doxygen::groupLinkedMap->find(g.groupname))) break;
}
//printf("---> addRelatedPage() %s gd=%p\n",qPrint(root->name),gd);
QCString doc=root->doc+root->inbodyDocs;
PageDef *pd = addRelatedPage(root->name,root->args,doc,
root->docFile,
root->docLine,
root->startLine,
root->sli,
gd,root->tagInfo(),
FALSE,
root->lang
);
if (pd)
{
pd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
pd->addSectionsToDefinition(root->anchors);
pd->setLocalToc(root->localToc);
addPageToContext(pd,root);
}
}
static void buildGroupListFiltered(const Entry *root,bool additional, bool includeExternal)
{
if (root->section.isGroupDoc() && !root->name.isEmpty() &&
((!includeExternal && root->tagInfo()==nullptr) ||
( includeExternal && root->tagInfo()!=nullptr))
)
{
AUTO_TRACE("additional={} includeExternal={}",additional,includeExternal);
if ((root->groupDocType==Entry::GROUPDOC_NORMAL && !additional) ||
(root->groupDocType!=Entry::GROUPDOC_NORMAL && additional))
{
GroupDef *gd = Doxygen::groupLinkedMap->find(root->name);
AUTO_TRACE_ADD("Processing group '{}':'{}' gd={}", root->type,root->name,(void*)gd);
if (gd)
{
if ( !gd->hasGroupTitle() )
{
gd->setGroupTitle( root->type );
}
else if ( root->type.length() > 0 && root->name != root->type && gd->groupTitle() != root->type )
{
warn( root->fileName,root->startLine,
"group %s: ignoring title \"%s\" that does not match old title \"%s\"",
qPrint(root->name), qPrint(root->type), qPrint(gd->groupTitle()) );
}
gd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
gd->setDocumentation( root->doc, root->docFile, root->docLine );
gd->setInbodyDocumentation( root->inbodyDocs, root->inbodyFile, root->inbodyLine );
gd->addSectionsToDefinition(root->anchors);
gd->setRefItems(root->sli);
gd->setLanguage(root->lang);
if (root->groupDocType==Entry::GROUPDOC_NORMAL)
{
root->commandOverrides.apply_groupGraph([&](bool b) { gd->overrideGroupGraph(b); });
}
}
else
{
if (root->tagInfo())
{
gd = Doxygen::groupLinkedMap->add(root->name,
std::unique_ptr<GroupDef>(
createGroupDef(root->fileName,root->startLine,root->name,root->type,root->tagInfo()->fileName)));
gd->setReference(root->tagInfo()->tagName);
}
else
{
gd = Doxygen::groupLinkedMap->add(root->name,
std::unique_ptr<GroupDef>(
createGroupDef(root->fileName,root->startLine,root->name,root->type)));
}
gd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
// allow empty docs for group
gd->setDocumentation(!root->doc.isEmpty() ? root->doc : QCString(" "),root->docFile,root->docLine,FALSE);
gd->setInbodyDocumentation( root->inbodyDocs, root->inbodyFile, root->inbodyLine );
gd->addSectionsToDefinition(root->anchors);
gd->setRefItems(root->sli);
gd->setLanguage(root->lang);
if (root->groupDocType==Entry::GROUPDOC_NORMAL)
{
root->commandOverrides.apply_groupGraph([&](bool b) { gd->overrideGroupGraph(b); });
}
}
}
}
for (const auto &e : root->children()) buildGroupListFiltered(e.get(),additional,includeExternal);
}
static void buildGroupList(const Entry *root)
{
// --- first process only local groups
// first process the @defgroups blocks
buildGroupListFiltered(root,FALSE,FALSE);
// then process the @addtogroup, @weakgroup blocks
buildGroupListFiltered(root,TRUE,FALSE);
// --- then also process external groups
// first process the @defgroups blocks
buildGroupListFiltered(root,FALSE,TRUE);
// then process the @addtogroup, @weakgroup blocks
buildGroupListFiltered(root,TRUE,TRUE);
}
static void findGroupScope(const Entry *root)
{
if (root->section.isGroupDoc() && !root->name.isEmpty() &&
root->parent() && !root->parent()->name.isEmpty())
{
GroupDef *gd = Doxygen::groupLinkedMap->find(root->name);
if (gd)
{
QCString scope = root->parent()->name;
if (root->parent()->section.isPackageDoc())
{
scope=substitute(scope,".","::");
}
scope = stripAnonymousNamespaceScope(scope);
scope+="::"+gd->name();
Definition *d = findScopeFromQualifiedName(Doxygen::globalScope,scope,nullptr,root->tagInfo());
if (d)
{
gd->setGroupScope(d);
}
}
}
for (const auto &e : root->children()) findGroupScope(e.get());
}
static void organizeSubGroupsFiltered(const Entry *root,bool additional)
{
if (root->section.isGroupDoc() && !root->name.isEmpty())
{
AUTO_TRACE("additional={}",additional);
if ((root->groupDocType==Entry::GROUPDOC_NORMAL && !additional) ||
(root->groupDocType!=Entry::GROUPDOC_NORMAL && additional))
{
GroupDef *gd = Doxygen::groupLinkedMap->find(root->name);
if (gd)
{
AUTO_TRACE_ADD("adding {} to group {}",root->name,gd->name());
addGroupToGroups(root,gd);
}
}
}
for (const auto &e : root->children()) organizeSubGroupsFiltered(e.get(),additional);
}
static void organizeSubGroups(const Entry *root)
{
//printf("Defining groups\n");
// first process the @defgroups blocks
organizeSubGroupsFiltered(root,FALSE);
//printf("Additional groups\n");
// then process the @addtogroup, @weakgroup blocks
organizeSubGroupsFiltered(root,TRUE);
}
//----------------------------------------------------------------------
static void buildFileList(const Entry *root)
{
if ((root->section.isFileDoc() || (root->section.isFile() && Config_getBool(EXTRACT_ALL))) &&
!root->name.isEmpty() && !root->tagInfo() // skip any file coming from tag files
)
{
bool ambig = false;
FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,root->name,ambig);
if (!fd || ambig)
{
bool save_ambig = ambig;
// use the directory of the file to see if the described file is in the same
// directory as the describing file.
QCString fn = root->fileName;
int newIndex=fn.findRev('/');
if (newIndex<0)
{
fn = root->name;
}
else
{
fn = fn.left(newIndex)+"/"+root->name;
}
fd=findFileDef(Doxygen::inputNameLinkedMap,fn,ambig);
if (!fd) ambig = save_ambig;
}
//printf("**************** root->name=%s fd=%p\n",qPrint(root->name),(void*)fd);
if (fd && !ambig)
{
//printf("Adding documentation!\n");
// using FALSE in setDocumentation is small hack to make sure a file
// is documented even if a \file command is used without further
// documentation
fd->setDocumentation(root->doc,root->docFile,root->docLine,FALSE);
fd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
fd->addSectionsToDefinition(root->anchors);
fd->setRefItems(root->sli);
root->commandOverrides.apply_includeGraph ([&](bool b) { fd->overrideIncludeGraph(b); });
root->commandOverrides.apply_includedByGraph([&](bool b) { fd->overrideIncludedByGraph(b); });
for (const Grouping &g : root->groups)
{
GroupDef *gd=nullptr;
if (!g.groupname.isEmpty() && (gd=Doxygen::groupLinkedMap->find(g.groupname)))
{
if (!gd->containsFile(fd))
{
gd->addFile(fd);
fd->makePartOfGroup(gd);
//printf("File %s: in group %s\n",qPrint(fd->name()),qPrint(gd->name()));
}
}
else if (!gd && g.pri == Grouping::GROUPING_INGROUP)
{
warn(root->fileName, root->startLine,
"Found non-existing group '%s' for the command '%s', ignoring command",
qPrint(g.groupname), Grouping::getGroupPriName( g.pri )
);
}
}
}
else
{
QCString text(4096, QCString::ExplicitSize);
text.sprintf("the name '%s' supplied as "
"the argument in the \\file statement ",
qPrint(root->name));
if (ambig) // name is ambiguous
{
text+="matches the following input files:\n";
text+=showFileDefMatches(Doxygen::inputNameLinkedMap,root->name);
text+="\n";
text+="Please use a more specific name by "
"including a (larger) part of the path!";
}
else // name is not an input file
{
text+="is not an input file";
}
warn(root->fileName,root->startLine,"%s", qPrint(text));
}
}
for (const auto &e : root->children()) buildFileList(e.get());
}
template<class DefMutable>
static void addIncludeFile(DefMutable *cd,FileDef *ifd,const Entry *root)
{
if (
(!root->doc.stripWhiteSpace().isEmpty() ||
!root->brief.stripWhiteSpace().isEmpty() ||
Config_getBool(EXTRACT_ALL)
) && root->protection!=Protection::Private
)
{
//printf(">>>>>> includeFile=%s\n",qPrint(root->includeFile));
bool local=Config_getBool(FORCE_LOCAL_INCLUDES);
QCString includeFile = root->includeFile;
if (!includeFile.isEmpty() && includeFile.at(0)=='"')
{
local = TRUE;
includeFile=includeFile.mid(1,includeFile.length()-2);
}
else if (!includeFile.isEmpty() && includeFile.at(0)=='<')
{
local = FALSE;
includeFile=includeFile.mid(1,includeFile.length()-2);
}
bool ambig = false;
FileDef *fd=nullptr;
// see if we need to include a verbatim copy of the header file
//printf("root->includeFile=%s\n",qPrint(root->includeFile));
if (!includeFile.isEmpty() &&
(fd=findFileDef(Doxygen::inputNameLinkedMap,includeFile,ambig))==nullptr
)
{ // explicit request
QCString text;
text.sprintf("the name '%s' supplied as "
"the argument of the \\class, \\struct, \\union, or \\include command ",
qPrint(includeFile)
);
if (ambig) // name is ambiguous
{
text+="matches the following input files:\n";
text+=showFileDefMatches(Doxygen::inputNameLinkedMap,root->includeFile);
text+="\n";
text+="Please use a more specific name by "
"including a (larger) part of the path!";
}
else // name is not an input file
{
text+="is not an input file";
}
warn(root->fileName,root->startLine, "%s", qPrint(text));
}
else if (includeFile.isEmpty() && ifd &&
// see if the file extension makes sense
guessSection(ifd->name()).isHeader())
{ // implicit assumption
fd=ifd;
}
// if a file is found, we mark it as a source file.
if (fd)
{
QCString iName = !root->includeName.isEmpty() ?
root->includeName : includeFile;
if (!iName.isEmpty()) // user specified include file
{
if (iName.at(0)=='<') local=FALSE; // explicit override
else if (iName.at(0)=='"') local=TRUE;
if (iName.at(0)=='"' || iName.at(0)=='<')
{
iName=iName.mid(1,iName.length()-2); // strip quotes or brackets
}
if (iName.isEmpty())
{
iName=fd->name();
}
}
else if (!Config_getList(STRIP_FROM_INC_PATH).empty())
{
iName=stripFromIncludePath(fd->absFilePath());
}
else // use name of the file containing the class definition
{
iName=fd->name();
}
if (fd->generateSourceFile()) // generate code for header
{
cd->setIncludeFile(fd,iName,local,!root->includeName.isEmpty());
}
else // put #include in the class documentation without link
{
cd->setIncludeFile(nullptr,iName,local,TRUE);
}
}
}
}
QCString stripTemplateSpecifiers(const QCString &s)
{
size_t l = s.length();
int count=0;
int round=0;
QCString result;
for (size_t i=0;i<l;i++)
{
char c=s.at(i);
if (c=='(') round++;
else if (c==')' && round>0) round--;
else if (c=='<' && round==0) count++;
if (count==0)
{
result+=c;
}
if (c=='>' && round==0 && count>0) count--;
}
//printf("stripTemplateSpecifiers(%s)=%s\n",qPrint(s),qPrint(result));
return result;
}
/*! returns the Definition object belonging to the first \a level levels of
* full qualified name \a name. Creates an artificial scope if the scope is
* not found and set the parent/child scope relation if the scope is found.
*/
[[maybe_unused]]
static Definition *buildScopeFromQualifiedName(const QCString &name_,SrcLangExt lang,const TagInfo *tagInfo)
{
QCString name = stripTemplateSpecifiers(name_);
name.stripPrefix("::");
int level = name.contains("::");
//printf("buildScopeFromQualifiedName(%s) level=%d\n",qPrint(name),level);
int i=0, p=0, l=0;
Definition *prevScope=Doxygen::globalScope;
QCString fullScope;
while (i<level)
{
int idx=getScopeFragment(name,p,&l);
if (idx==-1) return prevScope;
QCString nsName = name.mid(idx,l);
if (nsName.isEmpty()) return prevScope;
if (!fullScope.isEmpty()) fullScope+="::";
fullScope+=nsName;
NamespaceDef *nd=Doxygen::namespaceLinkedMap->find(fullScope);
DefinitionMutable *innerScope = toDefinitionMutable(nd);
ClassDef *cd=nullptr;
if (nd==nullptr) cd = getClass(fullScope);
if (nd==nullptr && cd) // scope is a class
{
innerScope = toDefinitionMutable(cd);
}
else if (nd==nullptr && cd==nullptr && fullScope.find('<')==-1) // scope is not known and could be a namespace!
{
// introduce bogus namespace
//printf("++ adding dummy namespace %s to %s tagInfo=%p\n",qPrint(nsName),qPrint(prevScope->name()),(void*)tagInfo);
NamespaceDefMutable *newNd=
toNamespaceDefMutable(
Doxygen::namespaceLinkedMap->add(fullScope,
createNamespaceDef(
"[generated]",1,1,fullScope,
tagInfo?tagInfo->tagName:QCString(),
tagInfo?tagInfo->fileName:QCString())));
if (newNd)
{
newNd->setLanguage(lang);
newNd->setArtificial(TRUE);
// add namespace to the list
innerScope = newNd;
}
}
else // scope is a namespace
{
}
if (innerScope)
{
// make the parent/child scope relation
DefinitionMutable *prevScopeMutable = toDefinitionMutable(prevScope);
if (prevScopeMutable)
{
prevScopeMutable->addInnerCompound(toDefinition(innerScope));
}
innerScope->setOuterScope(prevScope);
}
else // current scope is a class, so return only the namespace part...
{
return prevScope;
}
// proceed to the next scope fragment
p=idx+l+2;
prevScope=toDefinition(innerScope);
i++;
}
return prevScope;
}
static Definition *findScopeFromQualifiedName(NamespaceDefMutable *startScope,const QCString &n,
FileDef *fileScope,const TagInfo *tagInfo)
{
//printf("<findScopeFromQualifiedName(%s,%s)\n",startScope ? qPrint(startScope->name()) : 0, qPrint(n));
Definition *resultScope=toDefinition(startScope);
if (resultScope==nullptr) resultScope=Doxygen::globalScope;
QCString scope=stripTemplateSpecifiersFromScope(n,FALSE);
int l1 = 0;
int i1 = getScopeFragment(scope,0,&l1);
if (i1==-1)
{
//printf(">no fragments!\n");
return resultScope;
}
int p=i1+l1,l2=0,i2=0;
while ((i2=getScopeFragment(scope,p,&l2))!=-1)
{
QCString nestedNameSpecifier = scope.mid(i1,l1);
Definition *orgScope = resultScope;
//printf(" nestedNameSpecifier=%s\n",qPrint(nestedNameSpecifier));
resultScope = const_cast<Definition*>(resultScope->findInnerCompound(nestedNameSpecifier));
//printf(" resultScope=%p\n",resultScope);
if (resultScope==nullptr)
{
if (orgScope==Doxygen::globalScope && fileScope && !fileScope->getUsedNamespaces().empty())
// also search for used namespaces
{
for (const auto &nd : fileScope->getUsedNamespaces())
{
NamespaceDef *mnd = toNamespaceDefMutable(nd);
if (mnd)
{
resultScope = findScopeFromQualifiedName(toNamespaceDefMutable(nd),n,fileScope,tagInfo);
if (resultScope!=nullptr) break;
}
}
if (resultScope)
{
// for a nested class A::I in used namespace N, we get
// N::A::I while looking for A, so we should compare
// resultScope->name() against scope.left(i2+l2)
//printf(" -> result=%s scope=%s\n",qPrint(resultScope->name()),qPrint(scope));
if (rightScopeMatch(resultScope->name(),scope.left(i2+l2)))
{
break;
}
goto nextFragment;
}
}
// also search for used classes. Complication: we haven't been able
// to put them in the right scope yet, because we are still resolving
// the scope relations!
// Therefore loop through all used classes and see if there is a right
// scope match between the used class and nestedNameSpecifier.
for (const auto &usedName : g_usingDeclarations)
{
//printf("Checking using class %s\n",usedName.c_str());
if (rightScopeMatch(usedName.c_str(),nestedNameSpecifier))
{
// ui.currentKey() is the fully qualified name of nestedNameSpecifier
// so use this instead.
QCString fqn = QCString(usedName) + scope.right(scope.length()-p);
resultScope = buildScopeFromQualifiedName(fqn,startScope->getLanguage(),nullptr);
//printf("Creating scope from fqn=%s result %p\n",qPrint(fqn),resultScope);
if (resultScope)
{
//printf("> Match! resultScope=%s\n",qPrint(resultScope->name()));
return resultScope;
}
}
}
//printf("> name %s not found in scope %s\n",qPrint(nestedNameSpecifier),qPrint(orgScope->name()));
return nullptr;
}
nextFragment:
i1=i2;
l1=l2;
p=i2+l2;
}
//printf(">findScopeFromQualifiedName scope %s\n",qPrint(resultScope->name()));
return resultScope;
}
std::unique_ptr<ArgumentList> getTemplateArgumentsFromName(
const QCString &name,
const ArgumentLists &tArgLists)
{
// for each scope fragment, check if it is a template and advance through
// the list if so.
int i=0, p=0;
auto alIt = tArgLists.begin();
while ((i=name.find("::",p))!=-1 && alIt!=tArgLists.end())
{
NamespaceDef *nd = Doxygen::namespaceLinkedMap->find(name.left(i));
if (nd==nullptr)
{
ClassDef *cd = getClass(name.left(i));
if (cd)
{
if (!cd->templateArguments().empty())
{
++alIt;
}
}
}
p=i+2;
}
return alIt!=tArgLists.end() ?
std::make_unique<ArgumentList>(*alIt) :
std::unique_ptr<ArgumentList>();
}
static
ClassDef::CompoundType convertToCompoundType(EntryType section,TypeSpecifier specifier)
{
ClassDef::CompoundType sec=ClassDef::Class;
if (specifier.isStruct())
sec=ClassDef::Struct;
else if (specifier.isUnion())
sec=ClassDef::Union;
else if (specifier.isCategory())
sec=ClassDef::Category;
else if (specifier.isInterface())
sec=ClassDef::Interface;
else if (specifier.isProtocol())
sec=ClassDef::Protocol;
else if (specifier.isException())
sec=ClassDef::Exception;
else if (specifier.isService())
sec=ClassDef::Service;
else if (specifier.isSingleton())
sec=ClassDef::Singleton;
if (section.isUnionDoc())
sec=ClassDef::Union;
else if (section.isStructDoc())
sec=ClassDef::Struct;
else if (section.isInterfaceDoc())
sec=ClassDef::Interface;
else if (section.isProtocolDoc())
sec=ClassDef::Protocol;
else if (section.isCategoryDoc())
sec=ClassDef::Category;
else if (section.isExceptionDoc())
sec=ClassDef::Exception;
else if (section.isServiceDoc())
sec=ClassDef::Service;
else if (section.isSingletonDoc())
sec=ClassDef::Singleton;
return sec;
}
static void addClassToContext(const Entry *root)
{
AUTO_TRACE("name={}",root->name);
FileDef *fd = root->fileDef();
QCString scName;
if (root->parent()->section.isScope())
{
scName=root->parent()->name;
}
// name without parent's scope
QCString fullName = root->name;
// strip off any template parameters (but not those for specializations)
fullName=stripTemplateSpecifiersFromScope(fullName);
// name with scope (if not present already)
QCString qualifiedName = fullName;
if (!scName.isEmpty() && !leftScopeMatch(fullName,scName))
{
qualifiedName.prepend(scName+"::");
}
// see if we already found the class before
ClassDefMutable *cd = getClassMutable(qualifiedName);
AUTO_TRACE_ADD("Found class with name '{}', qualifiedName '{}'", cd ? cd->name() : root->name, qualifiedName);
if (cd)
{
fullName=cd->name();
AUTO_TRACE_ADD("Existing class '{}'",cd->name());
//if (cd->templateArguments()==0)
//{
// //printf("existing ClassDef tempArgList=%p specScope=%s\n",root->tArgList,qPrint(root->scopeSpec));
// cd->setTemplateArguments(tArgList);
//}
cd->setDocumentation(root->doc,root->docFile,root->docLine);
cd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
root->commandOverrides.apply_collaborationGraph([&](bool b ) { cd->overrideCollaborationGraph(b); });
root->commandOverrides.apply_inheritanceGraph ([&](CLASS_GRAPH_t gt) { cd->overrideInheritanceGraph(gt); });
if (!root->spec.isForwardDecl() && cd->isForwardDeclared())
{
cd->setDefFile(root->fileName,root->startLine,root->startColumn);
if (root->bodyLine!=-1)
{
cd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
cd->setBodyDef(fd);
}
}
if (cd->templateArguments().empty() || (cd->isForwardDeclared() && !root->spec.isForwardDecl()))
{
// this happens if a template class declared with @class is found
// before the actual definition or if a forward declaration has different template
// parameter names.
std::unique_ptr<ArgumentList> tArgList = getTemplateArgumentsFromName(cd->name(),root->tArgLists);
if (tArgList)
{
cd->setTemplateArguments(*tArgList);
}
}
if (cd->requiresClause().isEmpty() && !root->req.isEmpty())
{
cd->setRequiresClause(root->req);
}
cd->setCompoundType(convertToCompoundType(root->section,root->spec));
cd->setMetaData(root->metaData);
}
else // new class
{
ClassDef::CompoundType sec = convertToCompoundType(root->section,root->spec);
QCString className;
QCString namespaceName;
extractNamespaceName(fullName,className,namespaceName);
AUTO_TRACE_ADD("New class: fullname '{}' namespace '{}' name='{}' brief='{}' docs='{}'",
fullName, namespaceName, className, Trace::trunc(root->brief), Trace::trunc(root->doc));
QCString tagName;
QCString refFileName;
const TagInfo *tagInfo = root->tagInfo();
if (tagInfo)
{
tagName = tagInfo->tagName;
refFileName = tagInfo->fileName;
if (fullName.find("::")!=-1)
// symbols imported via tag files may come without the parent scope,
// so we artificially create it here
{
buildScopeFromQualifiedName(fullName,root->lang,tagInfo);
}
}
std::unique_ptr<ArgumentList> tArgList;
int i=0;
if ((root->lang==SrcLangExt::CSharp || root->lang==SrcLangExt::Java) && (i=fullName.findRev('<'))!=-1)
{
// a Java/C# generic class looks like a C++ specialization, so we need to split the
// name and template arguments here
tArgList = stringToArgumentList(root->lang,fullName.mid(i));
fullName=fullName.left(i);
}
else
{
tArgList = getTemplateArgumentsFromName(fullName,root->tArgLists);
}
// add class to the list
cd = toClassDefMutable(
Doxygen::classLinkedMap->add(fullName,
createClassDef(tagInfo?tagName:root->fileName,root->startLine,root->startColumn,
fullName,sec,tagName,refFileName,TRUE,root->spec.isEnum()) ));
if (cd)
{
AUTO_TRACE_ADD("New class '{}' type={} #tArgLists={} tagInfo={} hidden={} artificial={}",
fullName,cd->compoundTypeString(),root->tArgLists.size(),
fmt::ptr(tagInfo),root->hidden,root->artificial);
cd->setDocumentation(root->doc,root->docFile,root->docLine); // copy docs to definition
cd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
cd->setLanguage(root->lang);
cd->setId(root->id);
cd->setHidden(root->hidden);
cd->setArtificial(root->artificial);
cd->setClassSpecifier(root->spec);
cd->addQualifiers(root->qualifiers);
cd->setTypeConstraints(root->typeConstr);
root->commandOverrides.apply_collaborationGraph([&](bool b ) { cd->overrideCollaborationGraph(b); });
root->commandOverrides.apply_inheritanceGraph ([&](CLASS_GRAPH_t gt) { cd->overrideInheritanceGraph(gt); });
if (tArgList)
{
cd->setTemplateArguments(*tArgList);
}
cd->setRequiresClause(root->req);
cd->setProtection(root->protection);
cd->setIsStatic(root->isStatic);
// file definition containing the class cd
cd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
cd->setBodyDef(fd);
cd->setMetaData(root->metaData);
cd->insertUsedFile(fd);
}
else
{
AUTO_TRACE_ADD("Class {} not added, already exists as alias", fullName);
}
}
if (cd)
{
cd->addSectionsToDefinition(root->anchors);
if (!root->subGrouping) cd->setSubGrouping(FALSE);
if (!root->spec.isForwardDecl())
{
if (cd->hasDocumentation())
{
addIncludeFile(cd,fd,root);
}
if (fd && root->section.isCompound())
{
AUTO_TRACE_ADD("Inserting class {} in file {} (root->fileName='{}')", cd->name(), fd->name(), root->fileName);
cd->setFileDef(fd);
fd->insertClass(cd);
}
}
addClassToGroups(root,cd);
ModuleManager::instance().addClassToModule(root,cd);
cd->setRefItems(root->sli);
}
}
//----------------------------------------------------------------------
// build a list of all classes mentioned in the documentation
// and all classes that have a documentation block before their definition.
static void buildClassList(const Entry *root)
{
if ((root->section.isCompound() || root->section.isObjcImpl()) && !root->name.isEmpty())
{
AUTO_TRACE();
addClassToContext(root);
}
for (const auto &e : root->children()) buildClassList(e.get());
}
static void buildClassDocList(const Entry *root)
{
if ((root->section.isCompoundDoc()) && !root->name.isEmpty())
{
AUTO_TRACE();
addClassToContext(root);
}
for (const auto &e : root->children()) buildClassDocList(e.get());
}
//----------------------------------------------------------------------
// build a list of all classes mentioned in the documentation
// and all classes that have a documentation block before their definition.
static void addConceptToContext(const Entry *root)
{
AUTO_TRACE();
FileDef *fd = root->fileDef();
QCString scName;
if (root->parent()->section.isScope())
{
scName=root->parent()->name;
}
// name with scope (if not present already)
QCString qualifiedName = root->name;
if (!scName.isEmpty() && !leftScopeMatch(qualifiedName,scName))
{
qualifiedName.prepend(scName+"::");
}
// see if we already found the concept before
ConceptDefMutable *cd = getConceptMutable(qualifiedName);
AUTO_TRACE_ADD("Found concept with name '{}' (qualifiedName='{}')", cd ? cd->name() : root->name, qualifiedName);
if (cd)
{
qualifiedName=cd->name();
AUTO_TRACE_ADD("Existing concept '{}'",cd->name());
cd->setDocumentation(root->doc,root->docFile,root->docLine);
cd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
addIncludeFile(cd,fd,root);
}
else // new concept
{
QCString className;
QCString namespaceName;
extractNamespaceName(qualifiedName,className,namespaceName);
AUTO_TRACE_ADD("New concept: fullname '{}' namespace '{}' name='{}' brief='{}' docs='{}'",
qualifiedName,namespaceName,className,root->brief,root->doc);
QCString tagName;
QCString refFileName;
const TagInfo *tagInfo = root->tagInfo();
if (tagInfo)
{
tagName = tagInfo->tagName;
refFileName = tagInfo->fileName;
if (qualifiedName.find("::")!=-1)
// symbols imported via tag files may come without the parent scope,
// so we artificially create it here
{
buildScopeFromQualifiedName(qualifiedName,root->lang,tagInfo);
}
}
std::unique_ptr<ArgumentList> tArgList = getTemplateArgumentsFromName(qualifiedName,root->tArgLists);
// add concept to the list
cd = toConceptDefMutable(
Doxygen::conceptLinkedMap->add(qualifiedName,
createConceptDef(tagInfo?tagName:root->fileName,root->startLine,root->startColumn,
qualifiedName,tagName,refFileName)));
if (cd)
{
AUTO_TRACE_ADD("New concept '{}' #tArgLists={} tagInfo={}",
qualifiedName,root->tArgLists.size(),fmt::ptr(tagInfo));
cd->setDocumentation(root->doc,root->docFile,root->docLine); // copy docs to definition
cd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
cd->setLanguage(root->lang);
cd->setId(root->id);
cd->setHidden(root->hidden);
cd->setGroupId(root->mGrpId);
if (tArgList)
{
cd->setTemplateArguments(*tArgList);
}
cd->setInitializer(root->initializer.str().c_str());
// file definition containing the class cd
cd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
cd->setBodyDef(fd);
addIncludeFile(cd,fd,root);
// also add namespace to the correct structural context
Definition *d = findScopeFromQualifiedName(Doxygen::globalScope,qualifiedName,nullptr,tagInfo);
if (d && d->definitionType()==Definition::TypeNamespace)
{
DefinitionMutable *dm = toDefinitionMutable(d);
if (dm)
{
dm->addInnerCompound(cd);
}
cd->setOuterScope(d);
}
}
else
{
AUTO_TRACE_ADD("Concept '{}' not added, already exists (as alias)", qualifiedName);
}
}
if (cd)
{
cd->addSectionsToDefinition(root->anchors);
if (fd)
{
AUTO_TRACE_ADD("Inserting concept '{}' in file '{}' (root->fileName='{}')", cd->name(), fd->name(), root->fileName);
cd->setFileDef(fd);
fd->insertConcept(cd);
}
addConceptToGroups(root,cd);
ModuleManager::instance().addConceptToModule(root,cd);
cd->setRefItems(root->sli);
}
}
static void findModuleDocumentation(const Entry *root)
{
if (root->section.isModuleDoc())
{
AUTO_TRACE();
ModuleManager::instance().addDocs(root);
}
for (const auto &e : root->children()) findModuleDocumentation(e.get());
}
static void buildConceptList(const Entry *root)
{
if (root->section.isConcept())
{
AUTO_TRACE();
addConceptToContext(root);
}
for (const auto &e : root->children()) buildConceptList(e.get());
}
static void buildConceptDocList(const Entry *root)
{
if (root->section.isConceptDoc())
{
AUTO_TRACE();
addConceptToContext(root);
}
for (const auto &e : root->children()) buildConceptDocList(e.get());
}
// This routine is to allow @ingroup X @{ concept A; concept B; @} to work
// (same also works for variable and functions because of logic in MemberGroup::insertMember)
static void distributeConceptGroups()
{
AUTO_TRACE();
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->groupId()!=DOX_NOGROUP)
{
for (const auto &ocd : *Doxygen::conceptLinkedMap)
{
if (cd!=ocd && cd->groupId()==ocd->groupId() &&
!cd->partOfGroups().empty() && ocd->partOfGroups().empty())
{
ConceptDefMutable *ocdm = toConceptDefMutable(ocd.get());
if (ocdm)
{
for (const auto &gd : cd->partOfGroups())
{
if (gd)
{
AUTO_TRACE_ADD("making concept '{}' part of group '{}'",ocdm->name(),gd->name());
ocdm->makePartOfGroup(gd);
gd->addConcept(ocd.get());
}
}
}
}
}
}
}
}
//----------------------------------------------------------------------
static void resolveClassNestingRelations()
{
ClassDefSet visitedClasses;
bool done=FALSE;
//int iteration=0;
while (!done)
{
done=TRUE;
//++iteration;
struct ClassAlias
{
ClassAlias(const QCString &name,std::unique_ptr<ClassDef> cd,DefinitionMutable *ctx) :
aliasFullName(name),aliasCd(std::move(cd)), aliasContext(ctx) {}
QCString aliasFullName;
std::unique_ptr<ClassDef> aliasCd;
DefinitionMutable *aliasContext;
};
std::vector<ClassAlias> aliases;
for (const auto &icd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cd = toClassDefMutable(icd.get());
if (cd && visitedClasses.find(icd.get())==visitedClasses.end())
{
QCString name = stripAnonymousNamespaceScope(icd->name());
//printf("processing=%s, iteration=%d\n",qPrint(cd->name()),iteration);
// also add class to the correct structural context
Definition *d = findScopeFromQualifiedName(Doxygen::globalScope,
name,icd->getFileDef(),nullptr);
if (d)
{
//printf("****** adding %s to scope %s in iteration %d\n",qPrint(cd->name()),qPrint(d->name()),iteration);
DefinitionMutable *dm = toDefinitionMutable(d);
if (dm)
{
dm->addInnerCompound(cd);
}
cd->setOuterScope(d);
// for inline namespace add an alias of the class to the outer scope
while (d->definitionType()==Definition::TypeNamespace)
{
NamespaceDef *nd = toNamespaceDef(d);
//printf("nd->isInline()=%d\n",nd->isInline());
if (nd && nd->isInline())
{
d = d->getOuterScope();
if (d)
{
dm = toDefinitionMutable(d);
if (dm)
{
auto aliasCd = createClassDefAlias(d,cd);
QCString aliasFullName = d->qualifiedName()+"::"+aliasCd->localName();
aliases.emplace_back(aliasFullName,std::move(aliasCd),dm);
//printf("adding %s to %s as %s\n",qPrint(aliasCd->name()),qPrint(d->name()),qPrint(aliasFullName));
}
}
}
else
{
break;
}
}
visitedClasses.insert(icd.get());
done=FALSE;
}
//else
//{
// printf("****** ignoring %s: scope not (yet) found in iteration %d\n",qPrint(cd->name()),iteration);
//}
}
}
// add aliases
for (auto &alias : aliases)
{
ClassDef *aliasCd = Doxygen::classLinkedMap->add(alias.aliasFullName,std::move(alias.aliasCd));
if (aliasCd)
{
alias.aliasContext->addInnerCompound(aliasCd);
}
}
}
//give warnings for unresolved compounds
for (const auto &icd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cd = toClassDefMutable(icd.get());
if (cd && visitedClasses.find(icd.get())==visitedClasses.end())
{
QCString name = stripAnonymousNamespaceScope(cd->name());
//printf("processing unresolved=%s, iteration=%d\n",qPrint(cd->name()),iteration);
/// create the scope artificially
// anyway, so we can at least relate scopes properly.
Definition *d = buildScopeFromQualifiedName(name,cd->getLanguage(),nullptr);
if (d && d!=cd && !cd->getDefFileName().isEmpty())
// avoid recursion in case of redundant scopes, i.e: namespace N { class N::C {}; }
// for this case doxygen assumes the existence of a namespace N::N in which C is to be found!
// also avoid warning for stuff imported via a tagfile.
{
DefinitionMutable *dm = toDefinitionMutable(d);
if (dm)
{
dm->addInnerCompound(cd);
}
cd->setOuterScope(d);
warn(cd->getDefFileName(),cd->getDefLine(),
"Internal inconsistency: scope for class %s not "
"found!",qPrint(name)
);
}
}
}
}
void distributeClassGroupRelations()
{
//bool inlineGroupedClasses = Config_getBool(INLINE_GROUPED_CLASSES);
//if (!inlineGroupedClasses) return;
//printf("** distributeClassGroupRelations()\n");
ClassDefSet visitedClasses;
for (const auto &cd : *Doxygen::classLinkedMap)
{
//printf("Checking %s\n",qPrint(cd->name()));
// distribute the group to nested classes as well
if (visitedClasses.find(cd.get())==visitedClasses.end() && !cd->partOfGroups().empty())
{
//printf(" Candidate for merging\n");
GroupDef *gd = cd->partOfGroups().front();
for (auto &ncd : cd->getClasses())
{
ClassDefMutable *ncdm = toClassDefMutable(ncd);
if (ncdm && ncdm->partOfGroups().empty())
{
//printf(" Adding %s to group '%s'\n",qPrint(ncd->name()),
// gd->groupTitle());
ncdm->makePartOfGroup(gd);
gd->addClass(ncdm);
}
}
visitedClasses.insert(cd.get()); // only visit every class once
}
}
}
//----------------------------
static ClassDefMutable *createTagLessInstance(const ClassDef *rootCd,const ClassDef *templ,const QCString &fieldName)
{
QCString fullName = removeAnonymousScopes(templ->name());
if (fullName.endsWith("::")) fullName=fullName.left(fullName.length()-2);
fullName+="."+fieldName;
//printf("** adding class %s based on %s\n",qPrint(fullName),qPrint(templ->name()));
ClassDefMutable *cd = toClassDefMutable(
Doxygen::classLinkedMap->add(fullName,
createClassDef(templ->getDefFileName(),
templ->getDefLine(),
templ->getDefColumn(),
fullName,
templ->compoundType())));
if (cd)
{
cd->setDocumentation(templ->documentation(),templ->docFile(),templ->docLine()); // copy docs to definition
cd->setBriefDescription(templ->briefDescription(),templ->briefFile(),templ->briefLine());
cd->setLanguage(templ->getLanguage());
cd->setBodySegment(templ->getDefLine(),templ->getStartBodyLine(),templ->getEndBodyLine());
cd->setBodyDef(templ->getBodyDef());
cd->setOuterScope(rootCd->getOuterScope());
if (rootCd->getOuterScope()!=Doxygen::globalScope)
{
DefinitionMutable *outerScope = toDefinitionMutable(rootCd->getOuterScope());
if (outerScope)
{
outerScope->addInnerCompound(cd);
}
}
FileDef *fd = templ->getFileDef();
if (fd)
{
cd->setFileDef(fd);
fd->insertClass(cd);
}
for (auto &gd : rootCd->partOfGroups())
{
cd->makePartOfGroup(gd);
gd->addClass(cd);
}
MemberList *ml = templ->getMemberList(MemberListType::PubAttribs());
if (ml)
{
for (const auto &md : *ml)
{
//printf(" Member %s type=%s\n",qPrint(md->name()),md->typeString());
auto newMd = createMemberDef(md->getDefFileName(),md->getDefLine(),md->getDefColumn(),
md->typeString(),md->name(),md->argsString(),md->excpString(),
md->protection(),md->virtualness(),md->isStatic(),Relationship::Member,
md->memberType(),
ArgumentList(),ArgumentList(),"");
MemberDefMutable *imd = toMemberDefMutable(newMd.get());
imd->setMemberClass(cd);
imd->setDocumentation(md->documentation(),md->docFile(),md->docLine());
imd->setBriefDescription(md->briefDescription(),md->briefFile(),md->briefLine());
imd->setInbodyDocumentation(md->inbodyDocumentation(),md->inbodyFile(),md->inbodyLine());
imd->setMemberSpecifiers(md->getMemberSpecifiers());
imd->setVhdlSpecifiers(md->getVhdlSpecifiers());
imd->setMemberGroupId(md->getMemberGroupId());
imd->setInitializer(md->initializer());
imd->setRequiresClause(md->requiresClause());
imd->setMaxInitLines(md->initializerLines());
imd->setBitfields(md->bitfieldString());
imd->setLanguage(md->getLanguage());
cd->insertMember(imd);
MemberName *mn = Doxygen::memberNameLinkedMap->add(md->name());
mn->push_back(std::move(newMd));
}
}
}
return cd;
}
/** Look through the members of class \a cd and its public members.
* If there is a member m of a tag less struct/union,
* then we create a duplicate of the struct/union with the name of the
* member to identify it.
* So if cd has name S, then the tag less struct/union will get name S.m
* Since tag less structs can be nested we need to call this function
* recursively. Later on we need to patch the member types so we keep
* track of the hierarchy of classes we create.
*/
static void processTagLessClasses(const ClassDef *rootCd,
const ClassDef *cd,
ClassDefMutable *tagParentCd,
const QCString &prefix,int count)
{
//printf("%d: processTagLessClasses %s\n",count,qPrint(cd->name()));
//printf("checking members for %s\n",qPrint(cd->name()));
if (tagParentCd && !cd->getClasses().empty())
{
MemberList *ml = cd->getMemberList(MemberListType::PubAttribs());
if (ml)
{
int pos=0;
for (const auto &md : *ml)
{
QCString type = md->typeString();
if (type.find("::@")!=-1) // member of tag less struct/union
{
for (const auto &icd : cd->getClasses())
{
//printf(" member %s: type='%s'\n",qPrint(md->name()),qPrint(type));
//printf(" comparing '%s'<->'%s'\n",qPrint(type),qPrint(icd->name()));
if (type.find(icd->name())!=-1) // matching tag less struct/union
{
QCString name = md->name();
if (md->isAnonymous()) name = "__unnamed" + QCString().setNum(pos++)+"__";
if (!prefix.isEmpty()) name.prepend(prefix+".");
//printf(" found %s for class %s\n",qPrint(name),qPrint(cd->name()));
ClassDefMutable *ncd = createTagLessInstance(rootCd,icd,name);
if (ncd)
{
processTagLessClasses(rootCd,icd,ncd,name,count+1);
//printf(" addTagged %s to %s\n",qPrint(ncd->name()),qPrint(tagParentCd->name()));
ncd->setTagLessReference(icd);
// replace tag-less type for generated/original member
// by newly created class name.
// note the difference between changing cd and tagParentCd.
// for the initial call this is the same pointer, but for
// recursive calls cd is the original tag-less struct (of which
// there is only one instance) and tagParentCd is the newly
// generated tagged struct of which there can be multiple instances!
MemberList *pml = tagParentCd->getMemberList(MemberListType::PubAttribs());
if (pml)
{
for (const auto &pmd : *pml)
{
MemberDefMutable *pmdm = toMemberDefMutable(pmd);
if (pmdm && pmd->name()==md->name())
{
pmdm->setAccessorType(ncd,substitute(pmd->typeString(),icd->name(),ncd->name()));
//pmd->setType(substitute(pmd->typeString(),icd->name(),ncd->name()));
}
}
}
}
}
}
}
}
}
}
}
static void findTagLessClasses(std::vector<ClassDefMutable*> &candidates,ClassDef *cd)
{
for (const auto &icd : cd->getClasses())
{
if (icd->name().find("@")==-1) // process all non-anonymous inner classes
{
findTagLessClasses(candidates,icd);
}
}
ClassDefMutable *cdm = toClassDefMutable(cd);
if (cdm)
{
candidates.push_back(cdm);
}
}
static void findTagLessClasses()
{
std::vector<ClassDefMutable *> candidates;
for (auto &cd : *Doxygen::classLinkedMap)
{
Definition *scope = cd->getOuterScope();
if (scope && scope->definitionType()!=Definition::TypeClass) // that is not nested
{
findTagLessClasses(candidates,cd.get());
}
}
// since processTagLessClasses is potentially adding classes to Doxygen::classLinkedMap
// we need to call it outside of the loop above, otherwise the iterator gets invalidated!
for (auto &cd : candidates)
{
processTagLessClasses(cd,cd,cd,"",0); // process tag less inner struct/classes
}
}
//----------------------------------------------------------------------
// build a list of all namespaces mentioned in the documentation
// and all namespaces that have a documentation block before their definition.
static void buildNamespaceList(const Entry *root)
{
if (
(root->section.isNamespace() ||
root->section.isNamespaceDoc() ||
root->section.isPackageDoc()
) &&
!root->name.isEmpty()
)
{
AUTO_TRACE("name={}",root->name);
QCString fName = root->name;
if (root->section.isPackageDoc())
{
fName=substitute(fName,".","::");
}
QCString fullName = stripAnonymousNamespaceScope(fName);
if (!fullName.isEmpty())
{
AUTO_TRACE_ADD("Found namespace {} in {} at line {}",root->name,root->fileName,root->startLine);
NamespaceDef *ndi = Doxygen::namespaceLinkedMap->find(fullName);
if (ndi) // existing namespace
{
NamespaceDefMutable *nd = toNamespaceDefMutable(ndi);
if (nd) // non-inline namespace
{
AUTO_TRACE_ADD("Existing namespace");
nd->setDocumentation(root->doc,root->docFile,root->docLine);
nd->setName(fullName); // change name to match docs
nd->addSectionsToDefinition(root->anchors);
nd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
if (nd->getLanguage()==SrcLangExt::Unknown)
{
nd->setLanguage(root->lang);
}
if (root->tagInfo()==nullptr && nd->isReference() && !(root->doc.isEmpty() && root->brief.isEmpty()))
// if we previously found namespace nd in a tag file and now we find a
// documented namespace with the same name in the project, then remove
// the tag file reference
{
nd->setReference("");
nd->setFileName(fullName);
}
nd->setMetaData(root->metaData);
// file definition containing the namespace nd
FileDef *fd=root->fileDef();
if (nd->isArtificial())
{
nd->setArtificial(FALSE); // found namespace explicitly, so cannot be artificial
nd->setDefFile(root->fileName,root->startLine,root->startColumn);
}
// insert the namespace in the file definition
if (fd) fd->insertNamespace(nd);
addNamespaceToGroups(root,nd);
nd->setRefItems(root->sli);
}
}
else // fresh namespace
{
QCString tagName;
QCString tagFileName;
const TagInfo *tagInfo = root->tagInfo();
if (tagInfo)
{
tagName = tagInfo->tagName;
tagFileName = tagInfo->fileName;
}
AUTO_TRACE_ADD("new namespace {} lang={} tagName={}",fullName,langToString(root->lang),tagName);
// add namespace to the list
NamespaceDefMutable *nd = toNamespaceDefMutable(
Doxygen::namespaceLinkedMap->add(fullName,
createNamespaceDef(tagInfo?tagName:root->fileName,root->startLine,
root->startColumn,fullName,tagName,tagFileName,
root->type,root->spec.isPublished())));
if (nd)
{
nd->setDocumentation(root->doc,root->docFile,root->docLine); // copy docs to definition
nd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
nd->addSectionsToDefinition(root->anchors);
nd->setHidden(root->hidden);
nd->setArtificial(root->artificial);
nd->setLanguage(root->lang);
nd->setId(root->id);
nd->setMetaData(root->metaData);
nd->setInline(root->spec.isInline());
nd->setExported(root->exported);
addNamespaceToGroups(root,nd);
nd->setRefItems(root->sli);
// file definition containing the namespace nd
FileDef *fd=root->fileDef();
// insert the namespace in the file definition
if (fd) fd->insertNamespace(nd);
// the empty string test is needed for extract all case
nd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
nd->insertUsedFile(fd);
nd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
nd->setBodyDef(fd);
// also add namespace to the correct structural context
Definition *d = findScopeFromQualifiedName(Doxygen::globalScope,fullName,nullptr,tagInfo);
AUTO_TRACE_ADD("adding namespace {} to context {}",nd->name(),d ? d->name() : QCString("<none>"));
if (d==nullptr) // we didn't find anything, create the scope artificially
// anyway, so we can at least relate scopes properly.
{
d = buildScopeFromQualifiedName(fullName,nd->getLanguage(),tagInfo);
DefinitionMutable *dm = toDefinitionMutable(d);
if (dm)
{
dm->addInnerCompound(nd);
}
nd->setOuterScope(d);
// TODO: Due to the order in which the tag file is written
// a nested class can be found before its parent!
}
else
{
DefinitionMutable *dm = toDefinitionMutable(d);
if (dm)
{
dm->addInnerCompound(nd);
}
nd->setOuterScope(d);
// in case of d is an inline namespace, alias insert nd in the part scope of d.
while (d->definitionType()==Definition::TypeNamespace)
{
NamespaceDef *pnd = toNamespaceDef(d);
if (pnd && pnd->isInline())
{
d = d->getOuterScope();
if (d)
{
dm = toDefinitionMutable(d);
if (dm)
{
auto aliasNd = createNamespaceDefAlias(d,nd);
dm->addInnerCompound(aliasNd.get());
QCString aliasName = aliasNd->name();
AUTO_TRACE_ADD("adding alias {} to {}",aliasName,d->name());
Doxygen::namespaceLinkedMap->add(aliasName,std::move(aliasNd));
}
}
else
{
break;
}
}
else
{
break;
}
}
}
}
}
}
}
for (const auto &e : root->children()) buildNamespaceList(e.get());
}
//----------------------------------------------------------------------
static NamespaceDef *findUsedNamespace(const LinkedRefMap<NamespaceDef> &unl,
const QCString &name)
{
NamespaceDef *usingNd =nullptr;
for (auto &und : unl)
{
QCString uScope=und->name()+"::";
usingNd = getResolvedNamespace(uScope+name);
if (usingNd!=nullptr) break;
}
return usingNd;
}
static void findUsingDirectives(const Entry *root)
{
if (root->section.isUsingDir())
{
AUTO_TRACE("Found using directive {} at line {} of {}",root->name,root->startLine,root->fileName);
QCString name=substitute(root->name,".","::");
if (name.endsWith("::"))
{
name=name.left(name.length()-2);
}
if (!name.isEmpty())
{
NamespaceDef *usingNd = nullptr;
NamespaceDefMutable *nd = nullptr;
FileDef *fd = root->fileDef();
QCString nsName;
// see if the using statement was found inside a namespace or inside
// the global file scope.
if (root->parent() && root->parent()->section.isNamespace() &&
(fd==nullptr || fd->getLanguage()!=SrcLangExt::Java) // not a .java file
)
{
nsName=stripAnonymousNamespaceScope(root->parent()->name);
if (!nsName.isEmpty())
{
nd = getResolvedNamespaceMutable(nsName);
}
}
// find the scope in which the 'using' namespace is defined by prepending
// the possible scopes in which the using statement was found, starting
// with the most inner scope and going to the most outer scope (i.e.
// file scope).
int scopeOffset = static_cast<int>(nsName.length());
do
{
QCString scope=scopeOffset>0 ?
nsName.left(scopeOffset)+"::" : QCString();
usingNd = getResolvedNamespace(scope+name);
//printf("Trying with scope='%s' usingNd=%p\n",(scope+qPrint(name)),usingNd);
if (scopeOffset==0)
{
scopeOffset=-1;
}
else if ((scopeOffset=nsName.findRev("::",scopeOffset-1))==-1)
{
scopeOffset=0;
}
} while (scopeOffset>=0 && usingNd==nullptr);
if (usingNd==nullptr && nd) // not found, try used namespaces in this scope
// or in one of the parent namespace scopes
{
const NamespaceDefMutable *pnd = nd;
while (pnd && usingNd==nullptr)
{
// also try with one of the used namespaces found earlier
usingNd = toNamespaceDefMutable(findUsedNamespace(pnd->getUsedNamespaces(),name));
// goto the parent
Definition *s = pnd->getOuterScope();
if (s && s->definitionType()==Definition::TypeNamespace)
{
pnd = toNamespaceDefMutable(toNamespaceDef(s));
}
else
{
pnd = nullptr;
}
}
}
if (usingNd==nullptr && fd) // still nothing, also try used namespace in the
// global scope
{
usingNd = findUsedNamespace(fd->getUsedNamespaces(),name);
}
//printf("%s -> %s\n",qPrint(name),usingNd?qPrint(usingNd->name()):"<none>");
// add the namespace the correct scope
if (usingNd)
{
//printf("using fd=%p nd=%p\n",fd,nd);
if (nd)
{
//printf("Inside namespace %s\n",qPrint(nd->name()));
nd->addUsingDirective(usingNd);
}
else if (fd)
{
//printf("Inside file %s\n",qPrint(fd->name()));
fd->addUsingDirective(usingNd);
}
}
else // unknown namespace, but add it anyway.
{
AUTO_TRACE_ADD("new unknown namespace {} lang={} hidden={}",name,langToString(root->lang),root->hidden);
// add namespace to the list
nd = toNamespaceDefMutable(
Doxygen::namespaceLinkedMap->add(name,
createNamespaceDef(root->fileName,root->startLine,root->startColumn,name)));
if (nd)
{
nd->setDocumentation(root->doc,root->docFile,root->docLine); // copy docs to definition
nd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
nd->addSectionsToDefinition(root->anchors);
nd->setHidden(root->hidden);
nd->setArtificial(TRUE);
nd->setLanguage(root->lang);
nd->setId(root->id);
nd->setMetaData(root->metaData);
nd->setInline(root->spec.isInline());
nd->setExported(root->exported);
for (const Grouping &g : root->groups)
{
GroupDef *gd=nullptr;
if (!g.groupname.isEmpty() && (gd=Doxygen::groupLinkedMap->find(g.groupname)))
gd->addNamespace(nd);
}
// insert the namespace in the file definition
if (fd)
{
fd->insertNamespace(nd);
fd->addUsingDirective(nd);
}
// the empty string test is needed for extract all case
nd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
nd->insertUsedFile(fd);
nd->setRefItems(root->sli);
}
}
}
}
for (const auto &e : root->children()) findUsingDirectives(e.get());
}
//----------------------------------------------------------------------
static void buildListOfUsingDecls(const Entry *root)
{
if (root->section.isUsingDecl() &&
!root->parent()->section.isCompound() // not a class/struct member
)
{
QCString name = substitute(root->name,".","::");
g_usingDeclarations.insert(name.str());
}
for (const auto &e : root->children()) buildListOfUsingDecls(e.get());
}
static void findUsingDeclarations(const Entry *root,bool filterPythonPackages)
{
if (root->section.isUsingDecl() &&
!root->parent()->section.isCompound() && // not a class/struct member
(!filterPythonPackages || (root->lang==SrcLangExt::Python && root->fileName.endsWith("__init__.py")))
)
{
AUTO_TRACE("Found using declaration '{}' at line {} of {} inside section {}",
root->name,root->startLine,root->fileName,root->parent()->section);
if (!root->name.isEmpty())
{
const Definition *usingDef = nullptr;
NamespaceDefMutable *nd = nullptr;
FileDef *fd = root->fileDef();
QCString scName;
// see if the using statement was found inside a namespace or inside
// the global file scope.
if (root->parent()->section.isNamespace())
{
scName=root->parent()->name;
if (!scName.isEmpty())
{
nd = getResolvedNamespaceMutable(scName);
}
}
// Assume the using statement was used to import a class.
// Find the scope in which the 'using' namespace is defined by prepending
// the possible scopes in which the using statement was found, starting
// with the most inner scope and going to the most outer scope (i.e.
// file scope).
QCString name = substitute(root->name,".","::"); //Java/C# scope->internal
SymbolResolver resolver;
const Definition *scope = nd;
if (nd==nullptr) scope = fd;
usingDef = resolver.resolveSymbol(scope,name);
//printf("usingDef(scope=%s,name=%s)=%s\n",qPrint(nd?nd->qualifiedName():""),qPrint(name),usingDef?qPrint(usingDef->qualifiedName()):"nullptr");
if (!usingDef)
{
usingDef = getClass(name); // try direct lookup, this is needed to get
// builtin STL classes to properly resolve, e.g.
// vector -> std::vector
}
if (!usingDef)
{
usingDef = Doxygen::hiddenClassLinkedMap->find(name); // check if it is already hidden
}
#if 0
if (!usingDef)
{
AUTO_TRACE_ADD("New using class '{}' (sec={})! #tArgLists={}",
name,root->section,root->tArgLists.size());
ClassDefMutable *usingCd = toClassDefMutable(
Doxygen::hiddenClassLinkedMap->add(name,
createClassDef( "<using>",1,1, name, ClassDef::Class)));
if (usingCd)
{
usingCd->setArtificial(TRUE);
usingCd->setLanguage(root->lang);
usingDef = usingCd;
}
}
#endif
else
{
AUTO_TRACE_ADD("Found used type '{}' in scope='{}'",
usingDef->name(), nd ? nd->name(): fd ? fd->name() : QCString("<unknown>"));
}
if (usingDef)
{
if (nd)
{
nd->addUsingDeclaration(usingDef);
}
else if (fd)
{
fd->addUsingDeclaration(usingDef);
}
}
}
}
for (const auto &e : root->children()) findUsingDeclarations(e.get(),filterPythonPackages);
}
//----------------------------------------------------------------------
static void applyMemberOverrideOptions(const Entry *root,MemberDefMutable *md)
{
root->commandOverrides.apply_callGraph ([&](bool b) { md->overrideCallGraph(b); });
root->commandOverrides.apply_callerGraph ([&](bool b) { md->overrideCallerGraph(b); });
root->commandOverrides.apply_referencedByRelation([&](bool b) { md->overrideReferencedByRelation(b); });
root->commandOverrides.apply_referencesRelation ([&](bool b) { md->overrideReferencesRelation(b); });
root->commandOverrides.apply_inlineSource ([&](bool b) { md->overrideInlineSource(b); });
root->commandOverrides.apply_enumValues ([&](bool b) { md->overrideEnumValues(b); });
}
//----------------------------------------------------------------------
static void createUsingMemberImportForClass(const Entry *root,ClassDefMutable *cd,const MemberDef *md,
const QCString &fileName,const QCString &memName)
{
AUTO_TRACE("creating new member {} for class {}",memName,cd->name());
const ArgumentList &templAl = md->templateArguments();
const ArgumentList &al = md->argumentList();
auto newMd = createMemberDef(
fileName,root->startLine,root->startColumn,
md->typeString(),memName,md->argsString(),
md->excpString(),root->protection,root->virt,
md->isStatic(),Relationship::Member,md->memberType(),
templAl,al,root->metaData
);
auto newMmd = toMemberDefMutable(newMd.get());
newMmd->setMemberClass(cd);
cd->insertMember(newMd.get());
if (!root->doc.isEmpty() || !root->brief.isEmpty())
{
newMmd->setDocumentation(root->doc,root->docFile,root->docLine);
newMmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
newMmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
}
else
{
newMmd->setDocumentation(md->documentation(),md->docFile(),md->docLine());
newMmd->setBriefDescription(md->briefDescription(),md->briefFile(),md->briefLine());
newMmd->setInbodyDocumentation(md->inbodyDocumentation(),md->inbodyFile(),md->inbodyLine());
}
newMmd->setDefinition(md->definition());
applyMemberOverrideOptions(root,newMmd);
newMmd->addQualifiers(root->qualifiers);
newMmd->setBitfields(md->bitfieldString());
newMmd->addSectionsToDefinition(root->anchors);
newMmd->setBodySegment(md->getDefLine(),md->getStartBodyLine(),md->getEndBodyLine());
newMmd->setBodyDef(md->getBodyDef());
newMmd->setInitializer(md->initializer());
newMmd->setRequiresClause(md->requiresClause());
newMmd->setMaxInitLines(md->initializerLines());
newMmd->setMemberGroupId(root->mGrpId);
newMmd->setMemberSpecifiers(md->getMemberSpecifiers());
newMmd->setVhdlSpecifiers(md->getVhdlSpecifiers());
newMmd->setLanguage(root->lang);
newMmd->setId(root->id);
MemberName *mn = Doxygen::memberNameLinkedMap->add(memName);
mn->push_back(std::move(newMd));
}
static std::unordered_map<std::string,std::vector<ClassDefMutable*>> g_usingClassMap;
static void findUsingDeclImports(const Entry *root)
{
if (root->section.isUsingDecl() &&
root->parent()->section.isCompound() // in a class/struct member
)
{
AUTO_TRACE("Found using declaration '{}' inside section {}", root->name, root->parent()->section);
QCString fullName=removeRedundantWhiteSpace(root->parent()->name);
fullName=stripAnonymousNamespaceScope(fullName);
fullName=stripTemplateSpecifiersFromScope(fullName);
ClassDefMutable *cd = getClassMutable(fullName);
if (cd)
{
AUTO_TRACE_ADD("found class '{}'",cd->name());
int i=root->name.findRev("::");
if (i!=-1)
{
QCString scope=root->name.left(i);
QCString memName=root->name.right(root->name.length()-i-2);
SymbolResolver resolver;
const ClassDef *bcd = resolver.resolveClass(cd,scope); // todo: file in fileScope parameter
AUTO_TRACE_ADD("name={} scope={} bcd={}",scope,cd?cd->name():"<none>",bcd?bcd->name():"<none>");
if (bcd && bcd!=cd)
{
AUTO_TRACE_ADD("found class '{}' memName='{}'",bcd->name(),memName);
const MemberNameInfoLinkedMap &mnlm=bcd->memberNameInfoLinkedMap();
const MemberNameInfo *mni = mnlm.find(memName);
if (mni)
{
for (auto &mi : *mni)
{
const MemberDef *md = mi->memberDef();
if (md && md->protection()!=Protection::Private)
{
AUTO_TRACE_ADD("found member '{}'",mni->memberName());
QCString fileName = root->fileName;
if (fileName.isEmpty() && root->tagInfo())
{
fileName = root->tagInfo()->tagName;
}
if (!cd->containsOverload(md))
{
createUsingMemberImportForClass(root,cd,md,fileName,memName);
// also insert the member into copies of the class
auto it = g_usingClassMap.find(cd->qualifiedName().str());
if (it != g_usingClassMap.end())
{
for (const auto ©Cd : it->second)
{
createUsingMemberImportForClass(root,copyCd,md,fileName,memName);
}
}
}
}
}
}
}
}
}
}
else if (root->section.isUsingDecl() &&
(root->parent()->section.isNamespace() || root->parent()->section.isEmpty()) && // namespace or global member
root->lang==SrcLangExt::Cpp // do we also want this for e.g. Fortran? (see test case 095)
)
{
AUTO_TRACE("Found using declaration '{}' inside section {}", root->name, root->parent()->section);
Definition *scope = nullptr;
NamespaceDefMutable *nd = nullptr;
FileDef *fd = root->parent()->fileDef();
if (!root->parent()->name.isEmpty())
{
QCString fullName=removeRedundantWhiteSpace(root->parent()->name);
fullName=stripAnonymousNamespaceScope(fullName);
nd = toNamespaceDefMutable(getResolvedNamespace(fullName));
scope = nd;
}
else
{
scope = fd;
}
if (scope)
{
AUTO_TRACE_ADD("found scope '{}'",scope->name());
SymbolResolver resolver;
const Definition *def = resolver.resolveSymbol(root->name.startsWith("::") ? nullptr : scope,root->name);
if (def && def->definitionType()==Definition::TypeMember)
{
int i=root->name.find("::");
QCString memName;
if (i!=-1)
{
memName = root->name.right(root->name.length()-i-2);
}
else
{
memName = root->name;
}
const MemberDef *md = toMemberDef(def);
AUTO_TRACE_ADD("found member '{}' for name '{}'",md->qualifiedName(),root->name);
QCString fileName = root->fileName;
if (fileName.isEmpty() && root->tagInfo())
{
fileName = root->tagInfo()->tagName;
}
const ArgumentList &templAl = md->templateArguments();
const ArgumentList &al = md->argumentList();
auto newMd = createMemberDef(
fileName,root->startLine,root->startColumn,
md->typeString(),memName,md->argsString(),
md->excpString(),root->protection,root->virt,
md->isStatic(),Relationship::Member,md->memberType(),
templAl,al,root->metaData
);
auto newMmd = toMemberDefMutable(newMd.get());
if (nd)
{
newMmd->setNamespace(nd);
nd->insertMember(newMd.get());
}
if (fd)
{
newMmd->setFileDef(fd);
fd->insertMember(newMd.get());
}
if (!root->doc.isEmpty() || !root->brief.isEmpty())
{
newMmd->setDocumentation(root->doc,root->docFile,root->docLine);
newMmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
newMmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
}
else
{
newMmd->setDocumentation(md->documentation(),md->docFile(),md->docLine());
newMmd->setBriefDescription(md->briefDescription(),md->briefFile(),md->briefLine());
newMmd->setInbodyDocumentation(md->inbodyDocumentation(),md->inbodyFile(),md->inbodyLine());
}
newMmd->setDefinition(md->definition());
applyMemberOverrideOptions(root,newMmd);
newMmd->addQualifiers(root->qualifiers);
newMmd->setBitfields(md->bitfieldString());
newMmd->addSectionsToDefinition(root->anchors);
newMmd->setBodySegment(md->getDefLine(),md->getStartBodyLine(),md->getEndBodyLine());
newMmd->setBodyDef(md->getBodyDef());
newMmd->setInitializer(md->initializer());
newMmd->setRequiresClause(md->requiresClause());
newMmd->setMaxInitLines(md->initializerLines());
newMmd->setMemberGroupId(root->mGrpId);
newMmd->setMemberSpecifiers(md->getMemberSpecifiers());
newMmd->setVhdlSpecifiers(md->getVhdlSpecifiers());
newMmd->setLanguage(root->lang);
newMmd->setId(root->id);
MemberName *mn = Doxygen::functionNameLinkedMap->add(memName);
mn->push_back(std::move(newMd));
#if 0 // insert an alias instead of a copy
const MemberDef *md = toMemberDef(def);
AUTO_TRACE_ADD("found member '{}' for name '{}'",md->qualifiedName(),root->name);
auto aliasMd = createMemberDefAlias(nd,md);
QCString aliasFullName = nd->qualifiedName()+"::"+aliasMd->localName();
if (nd && aliasMd.get())
{
nd->insertMember(aliasMd.get());
}
if (fd && aliasMd.get())
{
fd->insertMember(aliasMd.get());
}
MemberName *mn = Doxygen::memberNameLinkedMap->add(aliasFullName);
mn->push_back(std::move(aliasMd));
#endif
}
else if (def && def->definitionType()==Definition::TypeClass)
{
const ClassDef *cd = toClassDef(def);
QCString copyFullName;
if (nd==nullptr)
{
copyFullName = cd->localName();
}
else
{
copyFullName = nd->qualifiedName()+"::"+cd->localName();
}
if (Doxygen::classLinkedMap->find(copyFullName)==nullptr)
{
ClassDefMutable *ncdm = toClassDefMutable(
Doxygen::classLinkedMap->add(copyFullName,
cd->deepCopy(copyFullName)));
AUTO_TRACE_ADD("found class '{}' for name '{}' copy '{}' obj={}",cd->qualifiedName(),root->name,copyFullName,(void*)ncdm);
g_usingClassMap[cd->qualifiedName().str()].push_back(ncdm);
if (ncdm)
{
if (nd) ncdm->moveTo(nd);
if ((!root->doc.isEmpty() || !root->brief.isEmpty())) // use docs at using statement
{
ncdm->setDocumentation(root->doc,root->docFile,root->docLine);
ncdm->setBriefDescription(root->brief,root->briefFile,root->briefLine);
}
else // use docs from used class
{
ncdm->setDocumentation(cd->documentation(),cd->docFile(),cd->docLine());
ncdm->setBriefDescription(cd->briefDescription(),cd->briefFile(),cd->briefLine());
}
if (nd)
{
nd->addInnerCompound(ncdm);
nd->addUsingDeclaration(ncdm);
}
if (fd)
{
if (ncdm) ncdm->setFileDef(fd);
fd->insertClass(ncdm);
fd->addUsingDeclaration(ncdm);
}
}
}
#if 0 // insert an alias instead of a copy
auto aliasCd = createClassDefAlias(nd,cd);
QCString aliasFullName;
if (nd==nullptr)
{
aliasFullName = aliasCd->localName();
}
else
{
aliasFullName = nd->qualifiedName()+"::"+aliasCd->localName();
}
AUTO_TRACE_ADD("found class '{}' for name '{}' aliasFullName='{}'",cd->qualifiedName(),root->name,aliasFullName);
auto acd = Doxygen::classLinkedMap->add(aliasFullName,std::move(aliasCd));
if (nd && acd)
{
nd->addInnerCompound(acd);
}
if (fd && acd)
{
fd->insertClass(acd);
}
#endif
}
else if (scope)
{
AUTO_TRACE_ADD("no symbol with name '{}' in scope {}",root->name,scope->name());
}
}
}
for (const auto &e : root->children()) findUsingDeclImports(e.get());
}
//----------------------------------------------------------------------
static void findIncludedUsingDirectives()
{
FileDefSet visitedFiles;
// then recursively add using directives found in #include files
// to files that have not been visited.
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
//printf("----- adding using directives for file %s\n",qPrint(fd->name()));
fd->addIncludedUsingDirectives(visitedFiles);
}
}
}
//----------------------------------------------------------------------
static MemberDef *addVariableToClass(
const Entry *root,
ClassDefMutable *cd,
MemberType mtype,
const QCString &type,
const QCString &name,
const QCString &args,
bool fromAnnScope,
MemberDef *fromAnnMemb,
Protection prot,
Relationship related)
{
QCString qualScope = cd->qualifiedNameWithTemplateParameters();
QCString scopeSeparator="::";
SrcLangExt lang = cd->getLanguage();
if (lang==SrcLangExt::Java || lang==SrcLangExt::CSharp)
{
qualScope = substitute(qualScope,"::",".");
scopeSeparator=".";
}
AUTO_TRACE("class variable: file='{}' type='{}' scope='{}' name='{}' args='{}' prot={} mtype={} lang={} ann={} init='{}'",
root->fileName, type, qualScope, name, args, root->protection, mtype, lang, fromAnnScope, root->initializer.str());
QCString def;
if (!type.isEmpty())
{
if (related!=Relationship::Member || mtype==MemberType::Friend || Config_getBool(HIDE_SCOPE_NAMES))
{
if (root->spec.isAlias()) // turn 'typedef B A' into 'using A'
{
def="using "+name;
}
else
{
def=type+" "+name+args;
}
}
else
{
if (root->spec.isAlias()) // turn 'typedef B C::A' into 'using C::A'
{
def="using "+qualScope+scopeSeparator+name;
}
else
{
def=type+" "+qualScope+scopeSeparator+name+args;
}
}
}
else
{
if (Config_getBool(HIDE_SCOPE_NAMES))
{
def=name+args;
}
else
{
def=qualScope+scopeSeparator+name+args;
}
}
def.stripPrefix("static ");
// see if the member is already found in the same scope
// (this may be the case for a static member that is initialized
// outside the class)
MemberName *mn=Doxygen::memberNameLinkedMap->find(name);
if (mn)
{
for (const auto &imd : *mn)
{
//printf("md->getClassDef()=%p cd=%p type=[%s] md->typeString()=[%s]\n",
// md->getClassDef(),cd,qPrint(type),md->typeString());
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md &&
md->getClassDef()==cd &&
((lang==SrcLangExt::Python && type.isEmpty() && !md->typeString().isEmpty()) ||
removeRedundantWhiteSpace(type)==md->typeString()))
// member already in the scope
{
if (root->lang==SrcLangExt::ObjC &&
root->mtype==MethodTypes::Property &&
md->memberType()==MemberType::Variable)
{ // Objective-C 2.0 property
// turn variable into a property
md->setProtection(root->protection);
cd->reclassifyMember(md,MemberType::Property);
}
addMemberDocs(root,md,def,nullptr,FALSE,root->spec);
AUTO_TRACE_ADD("Member already found!");
return md;
}
}
}
QCString fileName = root->fileName;
if (fileName.isEmpty() && root->tagInfo())
{
fileName = root->tagInfo()->tagName;
}
// new member variable, typedef or enum value
auto md = createMemberDef(
fileName,root->startLine,root->startColumn,
type,name,args,root->exception,
prot,Specifier::Normal,root->isStatic,related,
mtype,!root->tArgLists.empty() ? root->tArgLists.back() : ArgumentList(),
ArgumentList(), root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setMemberClass(cd); // also sets outer scope (i.e. getOuterScope())
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setDefinition(def);
mmd->setBitfields(root->bitfields);
mmd->addSectionsToDefinition(root->anchors);
mmd->setFromAnonymousScope(fromAnnScope);
mmd->setFromAnonymousMember(fromAnnMemb);
//md->setIndentDepth(indentDepth);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
std::string init = root->initializer.str();
mmd->setInitializer(init.c_str());
mmd->setMaxInitLines(root->initLines);
mmd->setMemberGroupId(root->mGrpId);
mmd->setMemberSpecifiers(root->spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setReadAccessor(root->read);
mmd->setWriteAccessor(root->write);
applyMemberOverrideOptions(root,mmd);
mmd->setHidden(root->hidden);
mmd->setArtificial(root->artificial);
mmd->setLanguage(root->lang);
mmd->setId(root->id);
addMemberToGroups(root,md.get());
ModuleManager::instance().addMemberToModule(root,md.get());
mmd->setBodyDef(root->fileDef());
mmd->addQualifiers(root->qualifiers);
AUTO_TRACE_ADD("Adding new member to class '{}'",cd->name());
cd->insertMember(md.get());
mmd->setRefItems(root->sli);
cd->insertUsedFile(root->fileDef());
root->markAsProcessed();
if (mtype==MemberType::Typedef)
{
resolveTemplateInstanceInType(root,cd,md.get());
}
// add the member to the global list
MemberDef *result = md.get();
mn = Doxygen::memberNameLinkedMap->add(name);
mn->push_back(std::move(md));
return result;
}
//----------------------------------------------------------------------
static MemberDef *addVariableToFile(
const Entry *root,
MemberType mtype,
const QCString &scope,
const QCString &type,
const QCString &name,
const QCString &args,
bool fromAnnScope,
MemberDef *fromAnnMemb)
{
AUTO_TRACE("global variable: file='{}' type='{}' scope='{}' name='{}' args='{}' prot={} mtype={} lang={} init='{}'",
root->fileName, type, scope, name, args, root->protection, mtype, root->lang, root->initializer.str());
FileDef *fd = root->fileDef();
// see if we have a typedef that should hide a struct or union
if (mtype==MemberType::Typedef && Config_getBool(TYPEDEF_HIDES_STRUCT))
{
QCString ttype = type;
ttype.stripPrefix("typedef ");
if (ttype.stripPrefix("struct ") || ttype.stripPrefix("union "))
{
static const reg::Ex re(R"(\a\w*)");
reg::Match match;
std::string typ = ttype.str();
if (reg::search(typ,match,re))
{
QCString typeValue = match.str();
ClassDefMutable *cd = getClassMutable(typeValue);
if (cd)
{
// this typedef should hide compound name cd, so we
// change the name that is displayed from cd.
cd->setClassName(name);
cd->setDocumentation(root->doc,root->docFile,root->docLine);
cd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
return nullptr;
}
}
}
}
// see if the function is inside a namespace
NamespaceDefMutable *nd = nullptr;
if (!scope.isEmpty())
{
if (scope.find('@')!=-1) return nullptr; // anonymous scope!
nd = getResolvedNamespaceMutable(scope);
}
QCString def;
// determine the definition of the global variable
if (nd && !nd->isAnonymous() &&
!Config_getBool(HIDE_SCOPE_NAMES)
)
// variable is inside a namespace, so put the scope before the name
{
SrcLangExt lang = nd->getLanguage();
QCString sep=getLanguageSpecificSeparator(lang);
if (!type.isEmpty())
{
if (root->spec.isAlias()) // turn 'typedef B NS::A' into 'using NS::A'
{
def="using "+nd->name()+sep+name;
}
else // normal member
{
def=type+" "+nd->name()+sep+name+args;
}
}
else
{
def=nd->name()+sep+name+args;
}
}
else
{
if (!type.isEmpty() && !root->name.isEmpty())
{
if (name.at(0)=='@') // dummy variable representing anonymous union
{
def=type;
}
else
{
if (root->spec.isAlias()) // turn 'typedef B A' into 'using A'
{
def="using "+root->name;
}
else // normal member
{
def=type+" "+name+args;
}
}
}
else
{
def=name+args;
}
}
def.stripPrefix("static ");
MemberName *mn=Doxygen::functionNameLinkedMap->find(name);
if (mn)
{
//QCString nscope=removeAnonymousScopes(scope);
//NamespaceDef *nd=nullptr;
//if (!nscope.isEmpty())
if (!scope.isEmpty())
{
nd = getResolvedNamespaceMutable(scope);
}
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md &&
((nd==nullptr && md->getNamespaceDef()==nullptr && md->getFileDef() &&
root->fileName==md->getFileDef()->absFilePath()
) // both variable names in the same file
|| (nd!=nullptr && md->getNamespaceDef()==nd) // both in same namespace
)
&& !md->isDefine() // function style #define's can be "overloaded" by typedefs or variables
&& !md->isEnumerate() // in C# an enum value and enum can have the same name
)
// variable already in the scope
{
bool isPHPArray = md->getLanguage()==SrcLangExt::PHP &&
md->argsString()!=args &&
args.find('[')!=-1;
bool staticsInDifferentFiles =
root->isStatic && md->isStatic() &&
root->fileName!=md->getDefFileName();
if (md->getFileDef() &&
!isPHPArray && // not a php array
!staticsInDifferentFiles
)
// not a php array variable
{
AUTO_TRACE_ADD("variable already found: scope='{}'",md->getOuterScope()->name());
addMemberDocs(root,md,def,nullptr,FALSE,root->spec);
md->setRefItems(root->sli);
// if md is a variable forward declaration and root is the definition that
// turn md into the definition
if (!root->explicitExternal && md->isExternal())
{
md->setDeclFile(md->getDefFileName(),md->getDefLine(),md->getDefColumn());
md->setExplicitExternal(FALSE,root->fileName,root->startLine,root->startColumn);
}
// if md is the definition and root point at a declaration, then add the
// declaration info
else if (root->explicitExternal && !md->isExternal())
{
md->setDeclFile(root->fileName,root->startLine,root->startColumn);
}
return md;
}
}
}
}
QCString fileName = root->fileName;
if (fileName.isEmpty() && root->tagInfo())
{
fileName = root->tagInfo()->tagName;
}
AUTO_TRACE_ADD("new variable, namespace='{}'",nd?nd->name():QCString("<global>"));
// new global variable, enum value or typedef
auto md = createMemberDef(
fileName,root->startLine,root->startColumn,
type,name,args,QCString(),
root->protection, Specifier::Normal,root->isStatic,Relationship::Member,
mtype,!root->tArgLists.empty() ? root->tArgLists.back() : ArgumentList(),
root->argList, root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setMemberSpecifiers(root->spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->addSectionsToDefinition(root->anchors);
mmd->setFromAnonymousScope(fromAnnScope);
mmd->setFromAnonymousMember(fromAnnMemb);
std::string init = root->initializer.str();
mmd->setInitializer(init.c_str());
mmd->setMaxInitLines(root->initLines);
mmd->setMemberGroupId(root->mGrpId);
mmd->setDefinition(def);
mmd->setLanguage(root->lang);
mmd->setId(root->id);
applyMemberOverrideOptions(root,mmd);
mmd->setExplicitExternal(root->explicitExternal,fileName,root->startLine,root->startColumn);
mmd->addQualifiers(root->qualifiers);
//md->setOuterScope(fd);
if (!root->explicitExternal)
{
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
mmd->setBodyDef(fd);
}
addMemberToGroups(root,md.get());
ModuleManager::instance().addMemberToModule(root,md.get());
mmd->setRefItems(root->sli);
if (nd && !nd->isAnonymous())
{
mmd->setNamespace(nd);
nd->insertMember(md.get());
}
// add member to the file (we do this even if we have already inserted
// it into the namespace.
if (fd)
{
mmd->setFileDef(fd);
fd->insertMember(md.get());
}
root->markAsProcessed();
if (mtype==MemberType::Typedef)
{
resolveTemplateInstanceInType(root,nd,md.get());
}
// add member definition to the list of globals
MemberDef *result = md.get();
mn = Doxygen::functionNameLinkedMap->add(name);
mn->push_back(std::move(md));
return result;
}
/*! See if the return type string \a type is that of a function pointer
* \returns -1 if this is not a function pointer variable or
* the index at which the closing brace of (...*name) was found.
*/
static int findFunctionPtr(const std::string &type,SrcLangExt lang, int *pLength=nullptr)
{
AUTO_TRACE("type='{}' lang={}",type,lang);
if (lang == SrcLangExt::Fortran || lang == SrcLangExt::VHDL)
{
return -1; // Fortran and VHDL do not have function pointers
}
static const reg::Ex re(R"(\([^)]*[*&^][^)]*\))");
reg::Match match;
size_t i=std::string::npos;
size_t l=0;
if (reg::search(type,match,re)) // contains (...*...) or (...&...) or (...^...)
{
i = match.position();
l = match.length();
}
if (i!=std::string::npos)
{
size_t di = type.find("decltype(");
if (di!=std::string::npos && di<i)
{
i = std::string::npos;
}
}
size_t bb=type.find('<');
size_t be=type.rfind('>');
bool templFp = false;
if (be!=std::string::npos) {
size_t cc_ast = type.find("::*");
size_t cc_amp = type.find("::&");
templFp = (cc_ast != std::string::npos && cc_ast>be) || (cc_amp != std::string::npos && cc_amp>be); // hack to find, e.g 'B<X>(A<int>::*)'
}
if (!type.empty() && // return type is non-empty
i!=std::string::npos && // contains (...*...)
type.find("operator")==std::string::npos && // not an operator
(type.find(")(")==std::string::npos || type.find("typedef ")!=std::string::npos) &&
// not a function pointer return type
(!(bb<i && i<be) || templFp) // bug665855: avoid treating "typedef A<void (T*)> type" as a function pointer
)
{
if (pLength) *pLength=static_cast<int>(l);
//printf("findFunctionPtr=%d\n",(int)i);
AUTO_TRACE_EXIT("result={}",i);
return static_cast<int>(i);
}
else
{
//printf("findFunctionPtr=%d\n",-1);
AUTO_TRACE_EXIT("result=-1");
return -1;
}
}
//--------------------------------------------------------------------------------------
/*! Returns TRUE iff \a type is a class within scope \a context.
* Used to detect variable declarations that look like function prototypes.
*/
static bool isVarWithConstructor(const Entry *root)
{
bool result = false;
bool typeIsClass = false;
bool typePtrType = false;
QCString type;
Definition *ctx = nullptr;
FileDef *fd = root->fileDef();
SymbolResolver resolver(fd);
AUTO_TRACE("isVarWithConstructor({})",root->name);
if (root->parent()->section.isCompound())
{ // inside a class
result=FALSE;
AUTO_TRACE_EXIT("inside class: result={}",result);
return result;
}
else if ((fd != nullptr) && (fd->name().endsWith(".c") || fd->name().endsWith(".h")))
{ // inside a .c file
result=FALSE;
AUTO_TRACE_EXIT("inside C file: result={}",result);
return result;
}
if (root->type.isEmpty())
{
result=FALSE;
AUTO_TRACE_EXIT("no type: result={}",result);
return result;
}
if (!root->parent()->name.isEmpty())
{
ctx=Doxygen::namespaceLinkedMap->find(root->parent()->name);
}
type = root->type;
// remove qualifiers
findAndRemoveWord(type,"const");
findAndRemoveWord(type,"static");
findAndRemoveWord(type,"volatile");
typePtrType = type.find('*')!=-1 || type.find('&')!=-1;
if (!typePtrType)
{
typeIsClass = resolver.resolveClass(ctx,type)!=nullptr;
int ti=0;
if (!typeIsClass && (ti=type.find('<'))!=-1)
{
typeIsClass=resolver.resolveClass(ctx,type.left(ti))!=nullptr;
}
}
if (typeIsClass) // now we still have to check if the arguments are
// types or values. Since we do not have complete type info
// we need to rely on heuristics :-(
{
if (root->argList.empty())
{
result=FALSE; // empty arg list -> function prototype.
AUTO_TRACE_EXIT("empty arg list: result={}",result);
return result;
}
for (const Argument &a : root->argList)
{
static const reg::Ex initChars(R"([\d"'&*!^]+)");
reg::Match match;
if (!a.name.isEmpty() || !a.defval.isEmpty())
{
std::string name = a.name.str();
if (reg::search(name,match,initChars) && match.position()==0)
{
result=TRUE;
}
else
{
result=FALSE; // arg has (type,name) pair -> function prototype
}
AUTO_TRACE_EXIT("function prototype: result={}",result);
return result;
}
if (!a.type.isEmpty() &&
(a.type.at(a.type.length()-1)=='*' ||
a.type.at(a.type.length()-1)=='&'))
// type ends with * or & => pointer or reference
{
result=FALSE;
AUTO_TRACE_EXIT("pointer or reference: result={}",result);
return result;
}
if (a.type.isEmpty() || resolver.resolveClass(ctx,a.type)!=nullptr)
{
result=FALSE; // arg type is a known type
AUTO_TRACE_EXIT("known type: result={}",result);
return result;
}
if (checkIfTypedef(ctx,fd,a.type))
{
result=FALSE; // argument is a typedef
AUTO_TRACE_EXIT("typedef: result={}",result);
return result;
}
std::string atype = a.type.str();
if (reg::search(atype,match,initChars) && match.position()==0)
{
result=TRUE; // argument type starts with typical initializer char
AUTO_TRACE_EXIT("argument with init char: result={}",result);
return result;
}
std::string resType=resolveTypeDef(ctx,a.type).str();
if (resType.empty()) resType=atype;
static const reg::Ex idChars(R"(\a\w*)");
if (reg::search(resType,match,idChars) && match.position()==0) // resType starts with identifier
{
resType=match.str();
if (resType=="int" || resType=="long" ||
resType=="float" || resType=="double" ||
resType=="char" || resType=="void" ||
resType=="signed" || resType=="unsigned" ||
resType=="const" || resType=="volatile" )
{
result=FALSE; // type keyword -> function prototype
AUTO_TRACE_EXIT("type keyword: result={}",result);
return result;
}
}
}
result=TRUE;
}
AUTO_TRACE_EXIT("end: result={}",result);
return result;
}
//--------------------------------------------------------------------------------------
/*! Searches for the end of a template in prototype \a s starting from
* character position \a startPos. If the end was found the position
* of the closing \> is returned, otherwise -1 is returned.
*
* Handles exotic cases such as
* \code
* Class<(id<0)>
* Class<bits<<2>
* Class<"<">
* Class<'<'>
* Class<(")<")>
* \endcode
*/
static int findEndOfTemplate(const QCString &s,size_t startPos)
{
// locate end of template
size_t e=startPos;
int brCount=1;
int roundCount=0;
size_t len = s.length();
bool insideString=FALSE;
bool insideChar=FALSE;
char pc = 0;
while (e<len && brCount!=0)
{
char c=s.at(e);
switch(c)
{
case '<':
if (!insideString && !insideChar)
{
if (e<len-1 && s.at(e+1)=='<')
e++;
else if (roundCount==0)
brCount++;
}
break;
case '>':
if (!insideString && !insideChar)
{
if (e<len-1 && s.at(e+1)=='>')
e++;
else if (roundCount==0)
brCount--;
}
break;
case '(':
if (!insideString && !insideChar)
roundCount++;
break;
case ')':
if (!insideString && !insideChar)
roundCount--;
break;
case '"':
if (!insideChar)
{
if (insideString && pc!='\\')
insideString=FALSE;
else
insideString=TRUE;
}
break;
case '\'':
if (!insideString)
{
if (insideChar && pc!='\\')
insideChar=FALSE;
else
insideChar=TRUE;
}
break;
}
pc = c;
e++;
}
return brCount==0 ? static_cast<int>(e) : -1;
}
//--------------------------------------------------------------------------------------
static void addVariable(const Entry *root,int isFuncPtr=-1)
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
AUTO_TRACE("VARIABLE_SEC: type='{}' name='{}' args='{}' bodyLine={} endBodyLine={} mGrpId={} relates='{}'",
root->type, root->name, root->args, root->bodyLine, root->endBodyLine, root->mGrpId, root->relates);
//printf("root->parent->name=%s\n",qPrint(root->parent->name));
QCString type = root->type;
QCString name = root->name;
QCString args = root->args;
if (type.isEmpty() && name.find("operator")==-1 &&
(name.find('*')!=-1 || name.find('&')!=-1))
{
// recover from parse error caused by redundant braces
// like in "int *(var[10]);", which is parsed as
// type="" name="int *" args="(var[10])"
type=name;
std::string sargs = args.str();
static const reg::Ex reName(R"(\a\w*)");
reg::Match match;
if (reg::search(sargs,match,reName))
{
name = match.str(); // e.g. 'var' in '(var[10])'
sargs = match.suffix().str(); // e.g. '[10]) in '(var[10])'
size_t j = sargs.find(')');
if (j!=std::string::npos) args=sargs.substr(0,j); // extract, e.g '[10]' from '[10])'
}
}
else
{
int i=isFuncPtr;
if (i==-1 && (root->spec.isAlias())==0) i=findFunctionPtr(type.str(),root->lang); // for typedefs isFuncPtr is not yet set
AUTO_TRACE_ADD("functionPtr={}",i!=-1?"yes":"no");
if (i>=0) // function pointer
{
int ai = type.find('[',i);
if (ai>i) // function pointer array
{
args.prepend(type.right(type.length()-ai));
type=type.left(ai);
}
else if (type.find(')',i)!=-1) // function ptr, not variable like "int (*bla)[10]"
{
type=type.left(type.length()-1);
args.prepend(") ");
}
}
}
AUTO_TRACE_ADD("after correction: type='{}' name='{}' args='{}'",type,name,args);
QCString scope;
name=removeRedundantWhiteSpace(name);
// find the scope of this variable
int index = computeQualifiedIndex(name);
if (index!=-1 && root->parent()->section.isGroupDoc() && root->parent()->tagInfo())
// grouped members are stored with full scope
{
buildScopeFromQualifiedName(name.left(index+2),root->lang,root->tagInfo());
scope=name.left(index);
name=name.mid(index+2);
}
else
{
Entry *p = root->parent();
while (p->section.isScope())
{
QCString scopeName = p->name;
if (!scopeName.isEmpty())
{
scope.prepend(scopeName);
break;
}
p=p->parent();
}
}
type=type.stripWhiteSpace();
ClassDefMutable *cd=nullptr;
bool isRelated=FALSE;
bool isMemberOf=FALSE;
QCString classScope=stripAnonymousNamespaceScope(scope);
classScope=stripTemplateSpecifiersFromScope(classScope,FALSE);
QCString annScopePrefix=scope.left(scope.length()-classScope.length());
// Look for last :: not part of template specifier
int p=-1;
for (size_t i=0;i<name.length()-1;i++)
{
if (name[i]==':' && name[i+1]==':')
{
p=static_cast<int>(i);
}
else if (name[i]=='<') // skip over template parts,
// i.e. A::B<C::D> => p=1 and
// A<B::C>::D => p=8
{
int e = findEndOfTemplate(name,i+1);
if (e!=-1) i=static_cast<int>(e);
}
}
if (p!=-1) // found it
{
if (type=="friend class" || type=="friend struct" ||
type=="friend union")
{
cd=getClassMutable(scope);
if (cd)
{
addVariableToClass(root, // entry
cd, // class to add member to
MemberType::Friend, // type of member
type, // type value as string
name, // name of the member
args, // arguments as string
FALSE, // from Anonymous scope
nullptr, // anonymous member
Protection::Public, // protection
Relationship::Member // related to a class
);
}
}
if (root->bodyLine!=-1 && root->endBodyLine!=-1) // store the body location for later use
{
Doxygen::staticInitMap.emplace(name.str(),BodyInfo{root->startLine,root->bodyLine,root->endBodyLine});
}
AUTO_TRACE_ADD("static variable {} body=[{}..{}]",name,root->bodyLine,root->endBodyLine);
return; /* skip this member, because it is a
* static variable definition (always?), which will be
* found in a class scope as well, but then we know the
* correct protection level, so only then it will be
* inserted in the correct list!
*/
}
MemberType mtype = MemberType::Variable;
if (type=="@")
mtype=MemberType::EnumValue;
else if (type.startsWith("typedef "))
mtype=MemberType::Typedef;
else if (type.startsWith("friend "))
mtype=MemberType::Friend;
else if (root->mtype==MethodTypes::Property)
mtype=MemberType::Property;
else if (root->mtype==MethodTypes::Event)
mtype=MemberType::Event;
else if (type.find("sequence<") != -1)
mtype=sliceOpt ? MemberType::Sequence : MemberType::Typedef;
else if (type.find("dictionary<") != -1)
mtype=sliceOpt ? MemberType::Dictionary : MemberType::Typedef;
if (!root->relates.isEmpty()) // related variable
{
isRelated=TRUE;
isMemberOf=(root->relatesType==RelatesType::MemberOf);
if (getClass(root->relates)==nullptr && !scope.isEmpty())
scope=mergeScopes(scope,root->relates);
else
scope=root->relates;
}
cd=getClassMutable(scope);
if (cd==nullptr && classScope!=scope) cd=getClassMutable(classScope);
if (cd)
{
MemberDef *md=nullptr;
// if cd is an anonymous (=tag less) scope we insert the member
// into a non-anonymous parent scope as well. This is needed to
// be able to refer to it using \var or \fn
//int indentDepth=0;
int si=scope.find('@');
//int anonyScopes = 0;
//bool added=FALSE;
bool inlineSimpleStructs = Config_getBool(INLINE_SIMPLE_STRUCTS);
Relationship relationship = isMemberOf ? Relationship::Foreign :
isRelated ? Relationship::Related :
Relationship::Member ;
if (si!=-1 && !inlineSimpleStructs) // anonymous scope or type
{
QCString pScope;
ClassDefMutable *pcd=nullptr;
pScope = scope.left(std::max(si-2,0)); // scope without tag less parts
if (!pScope.isEmpty())
pScope.prepend(annScopePrefix);
else if (annScopePrefix.length()>2)
pScope=annScopePrefix.left(annScopePrefix.length()-2);
if (name.at(0)!='@')
{
if (!pScope.isEmpty() && (pcd=getClassMutable(pScope)))
{
AUTO_TRACE_ADD("Adding anonymous member to scope '{}'",pScope);
md=addVariableToClass(root, // entry
pcd, // class to add member to
mtype, // member type
type, // type value as string
name, // member name
args, // arguments as string
TRUE, // from anonymous scope
nullptr, // from anonymous member
root->protection,
relationship
);
//added=TRUE;
}
else // anonymous scope inside namespace or file => put variable in the global scope
{
if (mtype==MemberType::Variable)
{
AUTO_TRACE_ADD("Adding anonymous member to global scope '{}'");
md=addVariableToFile(root,mtype,pScope,type,name,args,TRUE,nullptr);
}
//added=TRUE;
}
}
}
addVariableToClass(root, // entry
cd, // class to add member to
mtype, // member type
type, // type value as string
name, // name of the member
args, // arguments as string
FALSE, // from anonymous scope
md, // from anonymous member
root->protection,
relationship
);
}
else if (!name.isEmpty()) // global variable
{
addVariableToFile(root,mtype,scope,type,name,args,FALSE,/*nullptr,*/nullptr);
}
}
//----------------------------------------------------------------------
// Searches the Entry tree for typedef documentation sections.
// If found they are stored in their class or in the global list.
static void buildTypedefList(const Entry *root)
{
//printf("buildVarList(%s)\n",qPrint(rootNav->name()));
if (!root->name.isEmpty() &&
root->section.isVariable() &&
root->type.find("typedef ")!=-1 // its a typedef
)
{
AUTO_TRACE();
QCString rname = removeRedundantWhiteSpace(root->name);
QCString scope;
int index = computeQualifiedIndex(rname);
if (index!=-1 && root->parent()->section.isGroupDoc() && root->parent()->tagInfo())
// grouped members are stored with full scope
{
buildScopeFromQualifiedName(rname.left(index+2),root->lang,root->tagInfo());
scope=rname.left(index);
rname=rname.mid(index+2);
}
else
{
scope=root->parent()->name; //stripAnonymousNamespaceScope(root->parent->name);
}
ClassDefMutable *cd=getClassMutable(scope);
NamespaceDef *nd=getResolvedNamespace(scope);
MemberName *mn = Doxygen::functionNameLinkedMap->find(rname);
bool found=false;
if (mn) // symbol with the same name already found
{
for (auto &imd : *mn)
{
if (!imd->isTypedef())
continue;
QCString rtype = root->type;
rtype.stripPrefix("typedef ");
// merge the typedefs only if they're not both grouped, and both are
// either part of the same class, part of the same namespace, or both
// are global (i.e., neither in a class or a namespace)
bool notBothGrouped = root->groups.empty() || imd->getGroupDef()==nullptr; // see example #100
bool bothSameScope = (!cd && !nd) || (cd && imd->getClassDef() == cd) || (nd && imd->getNamespaceDef() == nd);
//printf("imd->isTypedef()=%d imd->typeString()=%s root->type=%s\n",imd->isTypedef(),
// qPrint(imd->typeString()),qPrint(root->type));
if (notBothGrouped && bothSameScope && imd->typeString()==rtype)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md)
{
md->setDocumentation(root->doc,root->docFile,root->docLine);
md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
md->setDocsForDefinition(!root->proto);
md->setBriefDescription(root->brief,root->briefFile,root->briefLine);
md->addSectionsToDefinition(root->anchors);
md->setRefItems(root->sli);
md->addQualifiers(root->qualifiers);
// merge ingroup specifiers
if (md->getGroupDef()==nullptr && !root->groups.empty())
{
addMemberToGroups(root,md);
}
else if (md->getGroupDef()!=nullptr && root->groups.empty())
{
//printf("existing member is grouped, new member not\n");
}
else if (md->getGroupDef()!=nullptr && !root->groups.empty())
{
//printf("both members are grouped\n");
}
found=true;
break;
}
}
}
}
if (found)
{
AUTO_TRACE_ADD("typedef '{}' already found",rname);
// mark the entry as processed, as we copied everything from it elsewhere
// also, otherwise, due to containing `typedef` it may later get treated
// as a function typedef in filterMemberDocumentation, which is incorrect
root->markAsProcessed();
}
else
{
AUTO_TRACE_ADD("new typedef '{}'",rname);
addVariable(root);
}
}
for (const auto &e : root->children())
if (!e->section.isEnum())
buildTypedefList(e.get());
}
//----------------------------------------------------------------------
// Searches the Entry tree for sequence documentation sections.
// If found they are stored in the global list.
static void buildSequenceList(const Entry *root)
{
if (!root->name.isEmpty() &&
root->section.isVariable() &&
root->type.find("sequence<")!=-1 // it's a sequence
)
{
AUTO_TRACE();
addVariable(root);
}
for (const auto &e : root->children())
if (!e->section.isEnum())
buildSequenceList(e.get());
}
//----------------------------------------------------------------------
// Searches the Entry tree for dictionary documentation sections.
// If found they are stored in the global list.
static void buildDictionaryList(const Entry *root)
{
if (!root->name.isEmpty() &&
root->section.isVariable() &&
root->type.find("dictionary<")!=-1 // it's a dictionary
)
{
AUTO_TRACE();
addVariable(root);
}
for (const auto &e : root->children())
if (!e->section.isEnum())
buildDictionaryList(e.get());
}
//----------------------------------------------------------------------
// Searches the Entry tree for Variable documentation sections.
// If found they are stored in their class or in the global list.
static void buildVarList(const Entry *root)
{
//printf("buildVarList(%s) section=%08x\n",qPrint(rootNav->name()),rootNav->section());
int isFuncPtr=-1;
if (!root->name.isEmpty() &&
(root->type.isEmpty() || g_compoundKeywords.find(root->type.str())==g_compoundKeywords.end()) &&
(
(root->section.isVariable() && // it's a variable
root->type.find("typedef ")==-1 // and not a typedef
) ||
(root->section.isFunction() && // or maybe a function pointer variable
(isFuncPtr=findFunctionPtr(root->type.str(),root->lang))!=-1
) ||
(root->section.isFunction() && // class variable initialized by constructor
isVarWithConstructor(root)
)
)
) // documented variable
{
AUTO_TRACE();
addVariable(root,isFuncPtr);
}
for (const auto &e : root->children())
if (!e->section.isEnum())
buildVarList(e.get());
}
//----------------------------------------------------------------------
// Searches the Entry tree for Interface sections (UNO IDL only).
// If found they are stored in their service or in the global list.
//
static void addInterfaceOrServiceToServiceOrSingleton(
const Entry *root,
ClassDefMutable *cd,
QCString const& rname)
{
FileDef *fd = root->fileDef();
enum MemberType type = root->section.isExportedInterface() ? MemberType::Interface : MemberType::Service;
QCString fileName = root->fileName;
if (fileName.isEmpty() && root->tagInfo())
{
fileName = root->tagInfo()->tagName;
}
auto md = createMemberDef(
fileName, root->startLine, root->startColumn, root->type, rname,
"", "", root->protection, root->virt, root->isStatic, Relationship::Member,
type, ArgumentList(), root->argList, root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setMemberClass(cd);
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setDocsForDefinition(false);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
mmd->setMemberSpecifiers(root->spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setMemberGroupId(root->mGrpId);
mmd->setTypeConstraints(root->typeConstr);
mmd->setLanguage(root->lang);
mmd->setBodyDef(fd);
mmd->setFileDef(fd);
mmd->addSectionsToDefinition(root->anchors);
QCString const def = root->type + " " + rname;
mmd->setDefinition(def);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
AUTO_TRACE("Interface member: fileName='{}' type='{}' name='{}' mtype='{}' prot={} virt={} state={} proto={} def='{}'",
fileName,root->type,rname,type,root->protection,root->virt,root->isStatic,root->proto,def);
// add member to the class cd
cd->insertMember(md.get());
// also add the member as a "base" (to get nicer diagrams)
// "optional" interface/service get Protected which turns into dashed line
BaseInfo base(rname,
root->spec.isOptional() ? Protection::Protected : Protection::Public, Specifier::Normal);
TemplateNameMap templateNames;
findClassRelation(root,cd,cd,&base,templateNames,DocumentedOnly,true) ||
findClassRelation(root,cd,cd,&base,templateNames,Undocumented,true);
// add file to list of used files
cd->insertUsedFile(fd);
addMemberToGroups(root,md.get());
ModuleManager::instance().addMemberToModule(root,md.get());
root->markAsProcessed();
mmd->setRefItems(root->sli);
// add member to the global list of all members
MemberName *mn = Doxygen::memberNameLinkedMap->add(rname);
mn->push_back(std::move(md));
}
static void buildInterfaceAndServiceList(const Entry *root)
{
if (root->section.isExportedInterface() || root->section.isIncludedService())
{
AUTO_TRACE("Exported interface/included service: type='{}' scope='{}' name='{}' args='{}'"
" relates='{}' relatesType='{}' file='{}' line={} bodyLine={} #tArgLists={}"
" mGrpId={} spec={} proto={} docFile='{}'",
root->type, root->parent()->name, root->name, root->args,
root->relates, root->relatesType, root->fileName, root->startLine, root->bodyLine, root->tArgLists.size(),
root->mGrpId, root->spec, root->proto, root->docFile);
QCString rname = removeRedundantWhiteSpace(root->name);
if (!rname.isEmpty())
{
QCString scope = root->parent()->name;
ClassDefMutable *cd = getClassMutable(scope);
assert(cd);
if (cd && ((ClassDef::Interface == cd->compoundType()) ||
(ClassDef::Service == cd->compoundType()) ||
(ClassDef::Singleton == cd->compoundType())))
{
addInterfaceOrServiceToServiceOrSingleton(root,cd,rname);
}
else
{
assert(false); // was checked by scanner.l
}
}
else if (rname.isEmpty())
{
warn(root->fileName,root->startLine,
"Illegal member name found.");
}
}
// can only have these in IDL anyway
switch (root->lang)
{
case SrcLangExt::Unknown: // fall through (root node always is Unknown)
case SrcLangExt::IDL:
for (const auto &e : root->children()) buildInterfaceAndServiceList(e.get());
break;
default:
return; // nothing to do here
}
}
//----------------------------------------------------------------------
// Searches the Entry tree for Function sections.
// If found they are stored in their class or in the global list.
static void addMethodToClass(const Entry *root,ClassDefMutable *cd,
const QCString &rtype,const QCString &rname,const QCString &rargs,
bool isFriend,
Protection protection,bool stat,Specifier virt,TypeSpecifier spec,
const QCString &relates
)
{
FileDef *fd=root->fileDef();
QCString type = rtype;
QCString args = rargs;
QCString name=removeRedundantWhiteSpace(rname);
name.stripPrefix("::");
MemberType mtype = MemberType::Function;
if (isFriend) mtype=MemberType::Friend;
else if (root->mtype==MethodTypes::Signal) mtype=MemberType::Signal;
else if (root->mtype==MethodTypes::Slot) mtype=MemberType::Slot;
else if (root->mtype==MethodTypes::DCOP) mtype=MemberType::DCOP;
// strip redundant template specifier for constructors
int i = -1;
int j = -1;
if ((fd==nullptr || fd->getLanguage()==SrcLangExt::Cpp) &&
!name.startsWith("operator ") && // not operator
(i=name.find('<'))!=-1 && // containing <
(j=name.find('>'))!=-1 && // or >
(j!=i+2 || name.at(i+1)!='=') // but not the C++20 spaceship operator <=>
)
{
name=name.left(i);
}
QCString fileName = root->fileName;
if (fileName.isEmpty() && root->tagInfo())
{
fileName = root->tagInfo()->tagName;
}
//printf("root->name='%s; args='%s' root->argList='%s'\n",
// qPrint(root->name),qPrint(args),qPrint(argListToString(root->argList))
// );
// adding class member
Relationship relationship = relates.isEmpty() ? Relationship::Member :
root->relatesType==RelatesType::MemberOf ? Relationship::Foreign :
Relationship::Related ;
auto md = createMemberDef(
fileName,root->startLine,root->startColumn,
type,name,args,root->exception,
protection,virt,
stat && root->relatesType!=RelatesType::MemberOf,
relationship,
mtype,!root->tArgLists.empty() ? root->tArgLists.back() : ArgumentList(),
root->argList, root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setMemberClass(cd);
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setDocsForDefinition(!root->proto);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
mmd->setMemberSpecifiers(spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setMemberGroupId(root->mGrpId);
mmd->setTypeConstraints(root->typeConstr);
mmd->setLanguage(root->lang);
mmd->setRequiresClause(root->req);
mmd->setId(root->id);
mmd->setBodyDef(fd);
mmd->setFileDef(fd);
mmd->addSectionsToDefinition(root->anchors);
QCString def;
QCString qualScope = cd->qualifiedNameWithTemplateParameters();
SrcLangExt lang = cd->getLanguage();
QCString scopeSeparator=getLanguageSpecificSeparator(lang);
if (scopeSeparator!="::")
{
qualScope = substitute(qualScope,"::",scopeSeparator);
}
if (lang==SrcLangExt::PHP)
{
// for PHP we use Class::method and Namespace\method
scopeSeparator="::";
}
// QCString optArgs = root->argList.empty() ? args : QCString();
if (!relates.isEmpty() || isFriend || Config_getBool(HIDE_SCOPE_NAMES))
{
if (!type.isEmpty())
{
def=type+" "+name; //+optArgs;
}
else
{
def=name; //+optArgs;
}
}
else
{
if (!type.isEmpty())
{
def=type+" "+qualScope+scopeSeparator+name; //+optArgs;
}
else
{
def=qualScope+scopeSeparator+name; //+optArgs;
}
}
def.stripPrefix("friend ");
mmd->setDefinition(def);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
AUTO_TRACE("function member: type='{}' scope='{}' name='{}' args='{}' proto={} def='{}'",
type, qualScope, rname, args, root->proto, def);
// add member to the class cd
cd->insertMember(md.get());
// add file to list of used files
cd->insertUsedFile(fd);
addMemberToGroups(root,md.get());
ModuleManager::instance().addMemberToModule(root,md.get());
root->markAsProcessed();
mmd->setRefItems(root->sli);
// add member to the global list of all members
//printf("Adding member=%s class=%s\n",qPrint(md->name()),qPrint(cd->name()));
MemberName *mn = Doxygen::memberNameLinkedMap->add(name);
mn->push_back(std::move(md));
}
//------------------------------------------------------------------------------------------
static void addGlobalFunction(const Entry *root,const QCString &rname,const QCString &sc)
{
QCString scope = sc;
// new global function
QCString name=removeRedundantWhiteSpace(rname);
auto md = createMemberDef(
root->fileName,root->startLine,root->startColumn,
root->type,name,root->args,root->exception,
root->protection,root->virt,root->isStatic,Relationship::Member,
MemberType::Function,
!root->tArgLists.empty() ? root->tArgLists.back() : ArgumentList(),
root->argList,root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setLanguage(root->lang);
mmd->setId(root->id);
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setPrototype(root->proto,root->fileName,root->startLine,root->startColumn);
mmd->setDocsForDefinition(!root->proto);
mmd->setTypeConstraints(root->typeConstr);
//md->setBody(root->body);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
FileDef *fd=root->fileDef();
mmd->setBodyDef(fd);
mmd->addSectionsToDefinition(root->anchors);
mmd->setMemberSpecifiers(root->spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setMemberGroupId(root->mGrpId);
mmd->setRequiresClause(root->req);
mmd->setExplicitExternal(root->explicitExternal,root->fileName,root->startLine,root->startColumn);
NamespaceDefMutable *nd = nullptr;
// see if the function is inside a namespace that was not part of
// the name already (in that case nd should be non-zero already)
if (root->parent()->section.isNamespace())
{
//QCString nscope=removeAnonymousScopes(root->parent()->name);
QCString nscope=root->parent()->name;
if (!nscope.isEmpty())
{
nd = getResolvedNamespaceMutable(nscope);
}
}
else if (root->parent()->section.isGroupDoc() && !scope.isEmpty())
{
nd = getResolvedNamespaceMutable(sc);
}
if (!scope.isEmpty())
{
QCString sep = getLanguageSpecificSeparator(root->lang);
if (sep!="::")
{
scope = substitute(scope,"::",sep);
}
scope+=sep;
}
if (Config_getBool(HIDE_SCOPE_NAMES)) scope = "";
QCString def;
//QCString optArgs = root->argList.empty() ? QCString() : root->args;
if (!root->type.isEmpty())
{
def=root->type+" "+scope+name; //+optArgs;
}
else
{
def=scope+name; //+optArgs;
}
AUTO_TRACE("new non-member function type='{}' scope='{}' name='{}' args='{}' proto={} def='{}'",
root->type,scope,rname,root->args,root->proto,def);
mmd->setDefinition(def);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
mmd->setRefItems(root->sli);
if (nd && !nd->name().isEmpty() && nd->name().at(0)!='@')
{
// add member to namespace
mmd->setNamespace(nd);
nd->insertMember(md.get());
}
if (fd)
{
// add member to the file (we do this even if we have already
// inserted it into the namespace)
mmd->setFileDef(fd);
fd->insertMember(md.get());
}
addMemberToGroups(root,md.get());
ModuleManager::instance().addMemberToModule(root,md.get());
if (root->relatesType == RelatesType::Simple) // if this is a relatesalso command,
// allow find Member to pick it up
{
root->markAsProcessed(); // Otherwise we have finished with this entry.
}
// add member to the list of file members
MemberName *mn = Doxygen::functionNameLinkedMap->add(name);
mn->push_back(std::move(md));
}
//------------------------------------------------------------------------------------------
static void buildFunctionList(const Entry *root)
{
if (root->section.isFunction())
{
AUTO_TRACE("member function: type='{}' scope='{}' name='{}' args='{}' relates='{}' relatesType='{}'"
" file='{}' line={} bodyLine={} #tArgLists={} mGrpId={}"
" spec={} proto={} docFile='{}'",
root->type, root->parent()->name, root->name, root->args, root->relates, root->relatesType,
root->fileName, root->startLine, root->bodyLine, root->tArgLists.size(), root->mGrpId,
root->spec, root->proto, root->docFile);
bool isFriend=root->type.find("friend ")!=-1;
QCString rname = removeRedundantWhiteSpace(root->name);
//printf("rname=%s\n",qPrint(rname));
QCString scope;
int index = computeQualifiedIndex(rname);
if (index!=-1 && root->parent()->section.isGroupDoc() && root->parent()->tagInfo())
// grouped members are stored with full scope
{
buildScopeFromQualifiedName(rname.left(index+2),root->lang,root->tagInfo());
scope=rname.left(index);
rname=rname.mid(index+2);
}
else
{
scope=root->parent()->name; //stripAnonymousNamespaceScope(root->parent->name);
}
if (!rname.isEmpty() && scope.find('@')==-1)
{
// check if this function's parent is a class
scope=stripTemplateSpecifiersFromScope(scope,FALSE);
FileDef *rfd=root->fileDef();
int memIndex=rname.findRev("::");
ClassDefMutable *cd=getClassMutable(scope);
if (cd && scope+"::"==rname.left(scope.length()+2)) // found A::f inside A
{
// strip scope from name
rname=rname.right(rname.length()-root->parent()->name.length()-2);
}
bool isMember=FALSE;
if (memIndex!=-1)
{
int ts=rname.find('<');
int te=rname.find('>');
if (memIndex>0 && (ts==-1 || te==-1))
{
// note: the following code was replaced by inMember=TRUE to deal with a
// function rname='X::foo' of class X inside a namespace also called X...
// bug id 548175
//nd = Doxygen::namespaceLinkedMap->find(rname.left(memIndex));
//isMember = nd==nullptr;
//if (nd)
//{
// // strip namespace scope from name
// scope=rname.left(memIndex);
// rname=rname.right(rname.length()-memIndex-2);
//}
isMember = TRUE;
}
else
{
isMember=memIndex<ts || memIndex>te;
}
}
if (!root->parent()->name.isEmpty() && root->parent()->section.isCompound() && cd)
{
AUTO_TRACE_ADD("member '{}' of class '{}'", rname,cd->name());
addMethodToClass(root,cd,root->type,rname,root->args,isFriend,
root->protection,root->isStatic,root->virt,root->spec,root->relates);
}
else if (root->parent()->section.isObjcImpl() && cd)
{
const MemberDef *md = cd->getMemberByName(rname);
if (md)
{
MemberDefMutable *mdm = toMemberDefMutable(const_cast<MemberDef*>(md));
if (mdm)
{
mdm->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
mdm->setBodyDef(root->fileDef());
}
}
}
else if (!root->parent()->section.isCompound() && !root->parent()->section.isObjcImpl() &&
!isMember &&
(root->relates.isEmpty() || root->relatesType==RelatesType::Duplicate) &&
!root->type.startsWith("extern ") && !root->type.startsWith("typedef ")
)
// no member => unrelated function
{
/* check the uniqueness of the function name in the file.
* A file could contain a function prototype and a function definition
* or even multiple function prototypes.
*/
bool found=FALSE;
MemberDef *md_found=nullptr;
MemberName *mn = Doxygen::functionNameLinkedMap->find(rname);
if (mn)
{
AUTO_TRACE_ADD("function '{}' already found",rname);
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md)
{
const NamespaceDef *mnd = md->getNamespaceDef();
NamespaceDef *rnd = nullptr;
//printf("root namespace=%s\n",qPrint(rootNav->parent()->name()));
QCString fullScope = scope;
QCString parentScope = root->parent()->name;
if (!parentScope.isEmpty() && !leftScopeMatch(parentScope,scope))
{
if (!scope.isEmpty()) fullScope.prepend("::");
fullScope.prepend(parentScope);
}
//printf("fullScope=%s\n",qPrint(fullScope));
rnd = getResolvedNamespace(fullScope);
const FileDef *mfd = md->getFileDef();
QCString nsName,rnsName;
if (mnd) nsName = mnd->name();
if (rnd) rnsName = rnd->name();
//printf("matching arguments for %s%s %s%s\n",
// qPrint(md->name()),md->argsString(),qPrint(rname),qPrint(argListToString(root->argList)));
const ArgumentList &mdAl = md->argumentList();
const ArgumentList &mdTempl = md->templateArguments();
// in case of template functions, we need to check if the
// functions have the same number of template parameters
bool sameNumTemplateArgs = TRUE;
bool matchingReturnTypes = TRUE;
bool sameRequiresClause = TRUE;
if (!mdTempl.empty() && !root->tArgLists.empty())
{
if (mdTempl.size()!=root->tArgLists.back().size())
{
sameNumTemplateArgs = FALSE;
}
if (md->typeString()!=removeRedundantWhiteSpace(root->type))
{
matchingReturnTypes = FALSE;
}
if (md->requiresClause()!=root->req)
{
sameRequiresClause = FALSE;
}
}
else if (!mdTempl.empty() || !root->tArgLists.empty())
{ // if one has template parameters and the other doesn't then that also counts as a
// difference
sameNumTemplateArgs = FALSE;
}
bool staticsInDifferentFiles =
root->isStatic && md->isStatic() && root->fileName!=md->getDefFileName();
if (
matchArguments2(md->getOuterScope(),mfd,&mdAl,
rnd ? rnd : Doxygen::globalScope,rfd,&root->argList,
FALSE,root->lang) &&
sameNumTemplateArgs &&
matchingReturnTypes &&
sameRequiresClause &&
!staticsInDifferentFiles
)
{
GroupDef *gd=nullptr;
if (!root->groups.empty() && !root->groups.front().groupname.isEmpty())
{
gd = Doxygen::groupLinkedMap->find(root->groups.front().groupname);
}
//printf("match!\n");
//printf("mnd=%p rnd=%p nsName=%s rnsName=%s\n",mnd,rnd,qPrint(nsName),qPrint(rnsName));
// see if we need to create a new member
found=(mnd && rnd && nsName==rnsName) || // members are in the same namespace
((mnd==nullptr && rnd==nullptr && mfd!=nullptr && // no external reference and
mfd->absFilePath()==root->fileName // prototype in the same file
)
);
// otherwise, allow a duplicate global member with the same argument list
if (!found && gd && gd==md->getGroupDef() && nsName==rnsName)
{
// member is already in the group, so we don't want to add it again.
found=TRUE;
}
AUTO_TRACE_ADD("combining function with prototype found={} in namespace '{}'",found,nsName);
if (found)
{
// merge argument lists
ArgumentList mergedArgList = root->argList;
mergeArguments(const_cast<ArgumentList&>(mdAl),mergedArgList,!root->doc.isEmpty());
// merge documentation
if (md->documentation().isEmpty() && !root->doc.isEmpty())
{
if (root->proto)
{
md->moveDeclArgumentList(stringToArgumentList(root->lang,root->args));
}
else
{
md->moveArgumentList(stringToArgumentList(root->lang,root->args));
}
}
md->setDocumentation(root->doc,root->docFile,root->docLine);
md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
md->setDocsForDefinition(!root->proto);
if (md->getStartBodyLine()==-1 && root->bodyLine!=-1)
{
md->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
md->setBodyDef(rfd);
}
if (md->briefDescription().isEmpty() && !root->brief.isEmpty())
{
md->setArgsString(root->args);
}
md->setBriefDescription(root->brief,root->briefFile,root->briefLine);
md->addSectionsToDefinition(root->anchors);
applyMemberOverrideOptions(root,md);
md->addQualifiers(root->qualifiers);
// merge ingroup specifiers
if (md->getGroupDef()==nullptr && !root->groups.empty())
{
addMemberToGroups(root,md);
}
else if (md->getGroupDef()!=nullptr && root->groups.empty())
{
//printf("existing member is grouped, new member not\n");
}
else if (md->getGroupDef()!=nullptr && !root->groups.empty())
{
//printf("both members are grouped\n");
}
ModuleManager::instance().addMemberToModule(root,md);
// if md is a declaration and root is the corresponding
// definition, then turn md into a definition.
if (md->isPrototype() && !root->proto)
{
md->setDeclFile(md->getDefFileName(),md->getDefLine(),md->getDefColumn());
md->setPrototype(FALSE,root->fileName,root->startLine,root->startColumn);
}
// if md is already the definition, then add the declaration info
else if (!md->isPrototype() && root->proto)
{
md->setDeclFile(root->fileName,root->startLine,root->startColumn);
}
}
}
}
if (found)
{
md_found = md;
break;
}
}
}
if (!found) /* global function is unique with respect to the file */
{
addGlobalFunction(root,rname,scope);
}
else
{
FileDef *fd=root->fileDef();
if (fd)
{
// add member to the file (we do this even if we have already
// inserted it into the namespace)
fd->insertMember(md_found);
}
}
AUTO_TRACE_ADD("unrelated function type='{}' name='{}' args='{}'",root->type,rname,root->args);
}
else
{
AUTO_TRACE_ADD("function '{}' is not processed",rname);
}
}
else if (rname.isEmpty())
{
warn(root->fileName,root->startLine,
"Illegal member name found."
);
}
}
for (const auto &e : root->children()) buildFunctionList(e.get());
}
//----------------------------------------------------------------------
static void findFriends()
{
AUTO_TRACE();
for (const auto &fn : *Doxygen::functionNameLinkedMap) // for each global function name
{
MemberName *mn = Doxygen::memberNameLinkedMap->find(fn->memberName());
if (mn)
{ // there are members with the same name
// for each function with that name
for (const auto &ifmd : *fn)
{
MemberDefMutable *fmd = toMemberDefMutable(ifmd.get());
// for each member with that name
for (const auto &immd : *mn)
{
MemberDefMutable *mmd = toMemberDefMutable(immd.get());
//printf("Checking for matching arguments
// mmd->isRelated()=%d mmd->isFriend()=%d mmd->isFunction()=%d\n",
// mmd->isRelated(),mmd->isFriend(),mmd->isFunction());
if (fmd && mmd &&
(mmd->isFriend() || (mmd->isRelated() && mmd->isFunction())) &&
matchArguments2(mmd->getOuterScope(), mmd->getFileDef(), &mmd->argumentList(),
fmd->getOuterScope(), fmd->getFileDef(), &fmd->argumentList(),
TRUE,mmd->getLanguage()
)
) // if the member is related and the arguments match then the
// function is actually a friend.
{
AUTO_TRACE_ADD("Merging related global and member '{}' isFriend={} isRelated={} isFunction={}",
mmd->name(),mmd->isFriend(),mmd->isRelated(),mmd->isFunction());
const ArgumentList &mmdAl = mmd->argumentList();
const ArgumentList &fmdAl = fmd->argumentList();
mergeArguments(const_cast<ArgumentList&>(fmdAl),const_cast<ArgumentList&>(mmdAl));
// reset argument lists to add missing default parameters
QCString mmdAlStr = argListToString(mmdAl);
QCString fmdAlStr = argListToString(fmdAl);
mmd->setArgsString(mmdAlStr);
fmd->setArgsString(fmdAlStr);
mmd->moveDeclArgumentList(std::make_unique<ArgumentList>(mmdAl));
fmd->moveDeclArgumentList(std::make_unique<ArgumentList>(fmdAl));
AUTO_TRACE_ADD("friend args='{}' member args='{}'",argListToString(fmd->argumentList()),argListToString(mmd->argumentList()));
if (!fmd->documentation().isEmpty())
{
mmd->setDocumentation(fmd->documentation(),fmd->docFile(),fmd->docLine());
}
else if (!mmd->documentation().isEmpty())
{
fmd->setDocumentation(mmd->documentation(),mmd->docFile(),mmd->docLine());
}
if (mmd->briefDescription().isEmpty() && !fmd->briefDescription().isEmpty())
{
mmd->setBriefDescription(fmd->briefDescription(),fmd->briefFile(),fmd->briefLine());
}
else if (!mmd->briefDescription().isEmpty() && !fmd->briefDescription().isEmpty())
{
fmd->setBriefDescription(mmd->briefDescription(),mmd->briefFile(),mmd->briefLine());
}
if (!fmd->inbodyDocumentation().isEmpty())
{
mmd->setInbodyDocumentation(fmd->inbodyDocumentation(),fmd->inbodyFile(),fmd->inbodyLine());
}
else if (!mmd->inbodyDocumentation().isEmpty())
{
fmd->setInbodyDocumentation(mmd->inbodyDocumentation(),mmd->inbodyFile(),mmd->inbodyLine());
}
//printf("body mmd %d fmd %d\n",mmd->getStartBodyLine(),fmd->getStartBodyLine());
if (mmd->getStartBodyLine()==-1 && fmd->getStartBodyLine()!=-1)
{
mmd->setBodySegment(fmd->getDefLine(),fmd->getStartBodyLine(),fmd->getEndBodyLine());
mmd->setBodyDef(fmd->getBodyDef());
//mmd->setBodyMember(fmd);
}
else if (mmd->getStartBodyLine()!=-1 && fmd->getStartBodyLine()==-1)
{
fmd->setBodySegment(mmd->getDefLine(),mmd->getStartBodyLine(),mmd->getEndBodyLine());
fmd->setBodyDef(mmd->getBodyDef());
//fmd->setBodyMember(mmd);
}
mmd->setDocsForDefinition(fmd->isDocsForDefinition());
mergeMemberOverrideOptions(mmd,fmd);
mmd->addQualifiers(fmd->getQualifiers());
fmd->addQualifiers(mmd->getQualifiers());
}
}
}
}
}
}
//----------------------------------------------------------------------
static void transferFunctionDocumentation()
{
AUTO_TRACE();
// find matching function declaration and definitions.
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
//printf("memberName=%s count=%zu\n",qPrint(mn->memberName()),mn->size());
/* find a matching function declaration and definition for this function */
for (const auto &imdec : *mn)
{
MemberDefMutable *mdec = toMemberDefMutable(imdec.get());
if (mdec &&
(mdec->isPrototype() ||
(mdec->isVariable() && mdec->isExternal())
))
{
for (const auto &imdef : *mn)
{
MemberDefMutable *mdef = toMemberDefMutable(imdef.get());
if (mdef && mdec!=mdef &&
mdec->getNamespaceDef()==mdef->getNamespaceDef())
{
combineDeclarationAndDefinition(mdec,mdef);
}
}
}
}
}
}
//----------------------------------------------------------------------
static void transferFunctionReferences()
{
AUTO_TRACE();
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
MemberDefMutable *mdef=nullptr,*mdec=nullptr;
/* find a matching function declaration and definition for this function */
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md)
{
if (md->isPrototype())
mdec=md;
else if (md->isVariable() && md->isExternal())
mdec=md;
if (md->isFunction() && !md->isStatic() && !md->isPrototype())
mdef=md;
else if (md->isVariable() && !md->isExternal() && !md->isStatic())
mdef=md;
}
if (mdef && mdec) break;
}
if (mdef && mdec)
{
const ArgumentList &mdefAl = mdef->argumentList();
const ArgumentList &mdecAl = mdec->argumentList();
if (
matchArguments2(mdef->getOuterScope(),mdef->getFileDef(),const_cast<ArgumentList*>(&mdefAl),
mdec->getOuterScope(),mdec->getFileDef(),const_cast<ArgumentList*>(&mdecAl),
TRUE,mdef->getLanguage()
)
) /* match found */
{
AUTO_TRACE_ADD("merging references for mdec={} mdef={}",mdec->name(),mdef->name());
mdef->mergeReferences(mdec);
mdec->mergeReferences(mdef);
mdef->mergeReferencedBy(mdec);
mdec->mergeReferencedBy(mdef);
}
}
}
}
//----------------------------------------------------------------------
static void transferRelatedFunctionDocumentation()
{
AUTO_TRACE();
// find match between function declaration and definition for
// related functions
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
/* find a matching function declaration and definition for this function */
// for each global function
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md)
{
//printf(" Function '%s'\n",qPrint(md->name()));
MemberName *rmn = Doxygen::memberNameLinkedMap->find(md->name());
if (rmn) // check if there is a member with the same name
{
//printf(" Member name found\n");
// for each member with the same name
for (const auto &irmd : *rmn)
{
MemberDefMutable *rmd = toMemberDefMutable(irmd.get());
//printf(" Member found: related='%d'\n",rmd->isRelated());
if (rmd &&
(rmd->isRelated() || rmd->isForeign()) && // related function
matchArguments2( md->getOuterScope(), md->getFileDef(), &md->argumentList(),
rmd->getOuterScope(),rmd->getFileDef(),&rmd->argumentList(),
TRUE,md->getLanguage()
)
)
{
AUTO_TRACE_ADD("Found related member '{}'",md->name());
if (rmd->relatedAlso())
md->setRelatedAlso(rmd->relatedAlso());
else if (rmd->isForeign())
md->makeForeign();
else
md->makeRelated();
}
}
}
}
}
}
}
//----------------------------------------------------------------------
void transferStaticInstanceInitializers()
{
AUTO_TRACE();
for (const auto &[qualifiedName,bodyInfo] : Doxygen::staticInitMap)
{
size_t i=qualifiedName.rfind("::");
if (i!=std::string::npos)
{
QCString scope = qualifiedName.substr(0,i);
QCString name = qualifiedName.substr(i+2);
MemberName *mn = Doxygen::memberNameLinkedMap->find(name);
if (mn)
{
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md && md->qualifiedName().str()==qualifiedName && md->isVariable())
{
AUTO_TRACE_ADD("found static member {} body [{}..{}]\n",
md->qualifiedName(),bodyInfo.startLine,bodyInfo.endLine);
md->setBodySegment(bodyInfo.defLine,
bodyInfo.startLine,
bodyInfo.endLine);
}
}
}
}
}
}
//----------------------------------------------------------------------
/*! make a dictionary of all template arguments of class cd
* that are part of the base class name.
* Example: A template class A with template arguments <R,S,T>
* that inherits from B<T,T,S> will have T and S in the dictionary.
*/
static TemplateNameMap getTemplateArgumentsInName(const ArgumentList &templateArguments,const std::string &name)
{
std::map<std::string,int> templateNames;
int count=0;
for (const Argument &arg : templateArguments)
{
static const reg::Ex re(R"(\a[\w:]*)");
reg::Iterator it(name,re);
reg::Iterator end;
for (; it!=end ; ++it)
{
const auto &match = *it;
std::string n = match.str();
if (n==arg.name.str())
{
if (templateNames.find(n)==templateNames.end())
{
templateNames.emplace(n,count);
}
}
}
}
return templateNames;
}
/*! Searches a class from within \a context and \a cd and returns its
* definition if found (otherwise nullptr is returned).
*/
static ClassDef *findClassWithinClassContext(Definition *context,ClassDef *cd,const QCString &name)
{
ClassDef *result=nullptr;
if (cd==nullptr)
{
return result;
}
FileDef *fd=cd->getFileDef();
SymbolResolver resolver(fd);
if (context && cd!=context)
{
result = const_cast<ClassDef*>(resolver.resolveClass(context,name,true,true));
}
//printf("1. result=%p\n",result);
if (result==nullptr)
{
result = const_cast<ClassDef*>(resolver.resolveClass(cd,name,true,true));
}
//printf("2. result=%p\n",result);
if (result==nullptr) // try direct class, needed for namespaced classes imported via tag files (see bug624095)
{
result = getClass(name);
}
//printf("3. result=%p\n",result);
//printf("** Trying to find %s within context %s class %s result=%s lookup=%p\n",
// qPrint(name),
// context ? qPrint(context->name()) : "<none>",
// cd ? qPrint(cd->name()) : "<none>",
// result ? qPrint(result->name()) : "<none>",
// Doxygen::classLinkedMap->find(name)
// );
return result;
}
static void findUsedClassesForClass(const Entry *root,
Definition *context,
ClassDefMutable *masterCd,
ClassDefMutable *instanceCd,
bool isArtificial,
const ArgumentList *actualArgs = nullptr,
const TemplateNameMap &templateNames = TemplateNameMap()
)
{
AUTO_TRACE();
const ArgumentList &formalArgs = masterCd->templateArguments();
for (auto &mni : masterCd->memberNameInfoLinkedMap())
{
for (auto &mi : *mni)
{
const MemberDef *md=mi->memberDef();
if (md->isVariable() || md->isObjCProperty()) // for each member variable in this class
{
AUTO_TRACE_ADD("Found variable '{}' in class '{}'",md->name(),masterCd->name());
QCString type = normalizeNonTemplateArgumentsInString(md->typeString(),masterCd,formalArgs);
QCString typedefValue = md->getLanguage()==SrcLangExt::Java ? type : resolveTypeDef(masterCd,type);
if (!typedefValue.isEmpty())
{
type = typedefValue;
}
int pos=0;
QCString usedClassName;
QCString templSpec;
bool found=FALSE;
// the type can contain template variables, replace them if present
type = substituteTemplateArgumentsInString(type,formalArgs,actualArgs);
//printf(" template substitution gives=%s\n",qPrint(type));
while (!found && extractClassNameFromType(type,pos,usedClassName,templSpec,root->lang)!=-1)
{
// find the type (if any) that matches usedClassName
SymbolResolver resolver(masterCd->getFileDef());
const ClassDefMutable *typeCd = resolver.resolveClassMutable(masterCd,usedClassName,false,true);
//printf("====> usedClassName=%s -> typeCd=%s\n",
// qPrint(usedClassName),typeCd?qPrint(typeCd->name()):"<none>");
if (typeCd)
{
usedClassName = typeCd->name();
}
int sp=usedClassName.find('<');
if (sp==-1) sp=0;
// replace any namespace aliases
replaceNamespaceAliases(usedClassName);
// add any template arguments to the class
QCString usedName = removeRedundantWhiteSpace(usedClassName+templSpec);
//printf(" usedName=%s usedClassName=%s templSpec=%s\n",qPrint(usedName),qPrint(usedClassName),qPrint(templSpec));
TemplateNameMap formTemplateNames;
if (templateNames.empty())
{
formTemplateNames = getTemplateArgumentsInName(formalArgs,usedName.str());
}
BaseInfo bi(usedName,Protection::Public,Specifier::Normal);
findClassRelation(root,context,instanceCd,&bi,formTemplateNames,TemplateInstances,isArtificial);
for (const Argument &arg : masterCd->templateArguments())
{
if (arg.name==usedName) // type is a template argument
{
ClassDef *usedCd = Doxygen::hiddenClassLinkedMap->find(usedName);
ClassDefMutable *usedCdm = toClassDefMutable(usedCd);
if (usedCd==nullptr)
{
usedCdm = toClassDefMutable(
Doxygen::hiddenClassLinkedMap->add(usedName,
createClassDef(
masterCd->getDefFileName(),masterCd->getDefLine(),
masterCd->getDefColumn(),
usedName,
ClassDef::Class)));
if (usedCdm)
{
//printf("making %s a template argument!!!\n",qPrint(usedCd->name()));
usedCdm->makeTemplateArgument();
usedCdm->setUsedOnly(TRUE);
usedCdm->setLanguage(masterCd->getLanguage());
usedCd = usedCdm;
}
}
if (usedCd)
{
found=TRUE;
AUTO_TRACE_ADD("case 1: adding used class '{}'", usedCd->name());
instanceCd->addUsedClass(usedCd,md->name(),md->protection());
if (usedCdm)
{
if (isArtificial) usedCdm->setArtificial(TRUE);
usedCdm->addUsedByClass(instanceCd,md->name(),md->protection());
}
}
}
}
if (!found)
{
ClassDef *usedCd=findClassWithinClassContext(context,masterCd,usedName);
//printf("Looking for used class %s: result=%s master=%s\n",
// qPrint(usedName),usedCd?qPrint(usedCd->name()):"<none>",masterCd?qPrint(masterCd->name()):"<none>");
if (usedCd)
{
found=TRUE;
AUTO_TRACE_ADD("case 2: adding used class '{}'", usedCd->name());
instanceCd->addUsedClass(usedCd,md->name(),md->protection()); // class exists
ClassDefMutable *usedCdm = toClassDefMutable(usedCd);
if (usedCdm)
{
usedCdm->addUsedByClass(instanceCd,md->name(),md->protection());
}
}
}
}
if (!found && !type.isEmpty()) // used class is not documented in any scope
{
ClassDef *usedCd = Doxygen::hiddenClassLinkedMap->find(type);
ClassDefMutable *usedCdm = toClassDefMutable(usedCd);
if (usedCd==nullptr && !Config_getBool(HIDE_UNDOC_RELATIONS))
{
if (type.endsWith("(*") || type.endsWith("(^")) // type is a function pointer
{
type+=md->argsString();
}
AUTO_TRACE_ADD("New undocumented used class '{}'", type);
usedCdm = toClassDefMutable(
Doxygen::hiddenClassLinkedMap->add(type,
createClassDef(
masterCd->getDefFileName(),masterCd->getDefLine(),
masterCd->getDefColumn(),
type,ClassDef::Class)));
if (usedCdm)
{
usedCdm->setUsedOnly(TRUE);
usedCdm->setLanguage(masterCd->getLanguage());
usedCd = usedCdm;
}
}
if (usedCd)
{
AUTO_TRACE_ADD("case 3: adding used class '{}'", usedCd->name());
instanceCd->addUsedClass(usedCd,md->name(),md->protection());
if (usedCdm)
{
if (isArtificial) usedCdm->setArtificial(TRUE);
usedCdm->addUsedByClass(instanceCd,md->name(),md->protection());
}
}
}
}
}
}
}
static void findBaseClassesForClass(
const Entry *root,
Definition *context,
ClassDefMutable *masterCd,
ClassDefMutable *instanceCd,
FindBaseClassRelation_Mode mode,
bool isArtificial,
const ArgumentList *actualArgs = nullptr,
const TemplateNameMap &templateNames=TemplateNameMap()
)
{
AUTO_TRACE("name={}",root->name);
// The base class could ofcouse also be a non-nested class
const ArgumentList &formalArgs = masterCd->templateArguments();
for (const BaseInfo &bi : root->extends)
{
//printf("masterCd=%s bi.name='%s' #actualArgs=%d\n",
// qPrint(masterCd->localName()),qPrint(bi.name),actualArgs ? (int)actualArgs->size() : -1);
TemplateNameMap formTemplateNames;
if (templateNames.empty())
{
formTemplateNames = getTemplateArgumentsInName(formalArgs,bi.name.str());
}
BaseInfo tbi = bi;
tbi.name = substituteTemplateArgumentsInString(bi.name,formalArgs,actualArgs);
//printf("masterCd=%p instanceCd=%p bi->name=%s tbi.name=%s\n",(void*)masterCd,(void*)instanceCd,qPrint(bi.name),qPrint(tbi.name));
if (mode==DocumentedOnly)
{
// find a documented base class in the correct scope
if (!findClassRelation(root,context,instanceCd,&tbi,formTemplateNames,DocumentedOnly,isArtificial))
{
// 1.8.2: decided to show inheritance relations even if not documented,
// we do make them artificial, so they do not appear in the index
//if (!Config_getBool(HIDE_UNDOC_RELATIONS))
bool b = Config_getBool(HIDE_UNDOC_RELATIONS) ? TRUE : isArtificial;
//{
// no documented base class -> try to find an undocumented one
findClassRelation(root,context,instanceCd,&tbi,formTemplateNames,Undocumented,b);
//}
}
}
else if (mode==TemplateInstances)
{
findClassRelation(root,context,instanceCd,&tbi,formTemplateNames,TemplateInstances,isArtificial);
}
}
}
//----------------------------------------------------------------------
static void findTemplateInstanceRelation(const Entry *root,
Definition *context,
ClassDefMutable *templateClass,const QCString &templSpec,
const TemplateNameMap &templateNames,
bool isArtificial)
{
AUTO_TRACE("Derived from template '{}' with parameters '{}' isArtificial={}",
templateClass->name(),templSpec,isArtificial);
QCString tempArgsStr = tempArgListToString(templateClass->templateArguments(),root->lang,false);
bool existingClass = templSpec==tempArgsStr;
if (existingClass) return; // avoid recursion
bool freshInstance=FALSE;
ClassDefMutable *instanceClass = toClassDefMutable(
templateClass->insertTemplateInstance(
root->fileName,root->startLine,root->startColumn,templSpec,freshInstance));
if (instanceClass)
{
instanceClass->setArtificial(TRUE);
instanceClass->setLanguage(root->lang);
if (freshInstance)
{
AUTO_TRACE_ADD("found fresh instance '{}'",instanceClass->name());
instanceClass->setTemplateBaseClassNames(templateNames);
// search for new template instances caused by base classes of
// instanceClass
auto it_pair = g_classEntries.equal_range(templateClass->name().str());
for (auto it=it_pair.first ; it!=it_pair.second ; ++it)
{
const Entry *templateRoot = it->second;
AUTO_TRACE_ADD("template root found '{}' templSpec='{}'",templateRoot->name,templSpec);
std::unique_ptr<ArgumentList> templArgs = stringToArgumentList(root->lang,templSpec);
findBaseClassesForClass(templateRoot,context,templateClass,instanceClass,
TemplateInstances,isArtificial,templArgs.get(),templateNames);
findUsedClassesForClass(templateRoot,context,templateClass,instanceClass,
isArtificial,templArgs.get(),templateNames);
}
}
else
{
AUTO_TRACE_ADD("instance already exists");
}
}
}
//----------------------------------------------------------------------
static void resolveTemplateInstanceInType(const Entry *root,const Definition *scope,const MemberDef *md)
{
// For a statement like 'using X = T<A>', add a template instance 'T<A>' as a symbol, so it can
// be used to match arguments (see issue #11111)
AUTO_TRACE();
QCString ttype = md->typeString();
ttype.stripPrefix("typedef ");
int ti=ttype.find('<');
if (ti!=-1)
{
QCString templateClassName = ttype.left(ti);
SymbolResolver resolver(root->fileDef());
ClassDefMutable *baseClass = resolver.resolveClassMutable(scope ? scope : Doxygen::globalScope,
templateClassName, true, true);
AUTO_TRACE_ADD("templateClassName={} baseClass={}",templateClassName,baseClass?baseClass->name():"<none>");
if (baseClass)
{
const ArgumentList &tl = baseClass->templateArguments();
TemplateNameMap templateNames = getTemplateArgumentsInName(tl,templateClassName.str());
findTemplateInstanceRelation(root,md->getOuterScope(),
baseClass,
ttype.mid(ti),
templateNames,
baseClass->isArtificial());
}
}
}
//----------------------------------------------------------------------
static bool isRecursiveBaseClass(const QCString &scope,const QCString &name)
{
QCString n=name;
int index=n.find('<');
if (index!=-1)
{
n=n.left(index);
}
bool result = rightScopeMatch(scope,n);
return result;
}
static int findTemplateSpecializationPosition(const QCString &name)
{
if (name.isEmpty()) return 0;
int l = static_cast<int>(name.length());
if (name[l-1]=='>') // search backward to find the matching <, allowing nested <...> and strings.
{
int count=1;
int i=l-2;
char insideQuote=0;
while (count>0 && i>=0)
{
char c = name[i--];
switch (c)
{
case '>': if (!insideQuote) count++; break;
case '<': if (!insideQuote) count--; break;
case '\'': if (!insideQuote) insideQuote=c;
else if (insideQuote==c && (i<0 || name[i]!='\\')) insideQuote=0;
break;
case '"': if (!insideQuote) insideQuote=c;
else if (insideQuote==c && (i<0 || name[i]!='\\')) insideQuote=0;
break;
default: break;
}
}
if (i>=0) l=i+1;
}
return l;
}
static bool findClassRelation(
const Entry *root,
Definition *context,
ClassDefMutable *cd,
const BaseInfo *bi,
const TemplateNameMap &templateNames,
FindBaseClassRelation_Mode mode,
bool isArtificial
)
{
AUTO_TRACE("name={} base={} isArtificial={}",cd->name(),bi->name,isArtificial);
QCString biName=bi->name;
bool explicitGlobalScope=FALSE;
if (biName.startsWith("::")) // explicit global scope
{
biName=biName.right(biName.length()-2);
explicitGlobalScope=TRUE;
}
Entry *parentNode=root->parent();
bool lastParent=FALSE;
do // for each parent scope, starting with the largest scope
// (in case of nested classes)
{
QCString scopeName= parentNode ? parentNode->name : QCString();
int scopeOffset=explicitGlobalScope ? 0 : static_cast<int>(scopeName.length());
do // try all parent scope prefixes, starting with the largest scope
{
//printf("scopePrefix='%s' biName='%s'\n",
// qPrint(scopeName.left(scopeOffset)),qPrint(biName));
QCString baseClassName=biName;
if (scopeOffset>0)
{
baseClassName.prepend(scopeName.left(scopeOffset)+"::");
}
//QCString stripped;
//baseClassName=stripTemplateSpecifiersFromScope
// (removeRedundantWhiteSpace(baseClassName),TRUE,
// &stripped);
SymbolResolver resolver(cd->getFileDef());
ClassDefMutable *baseClass = resolver.resolveClassMutable(explicitGlobalScope ? Doxygen::globalScope : context,
baseClassName,
mode==Undocumented,
true
);
const MemberDef *baseClassTypeDef = resolver.getTypedef();
QCString templSpec = resolver.getTemplateSpec();
//printf("baseClassName=%s baseClass=%p cd=%p explicitGlobalScope=%d\n",
// qPrint(baseClassName),baseClass,cd,explicitGlobalScope);
//printf(" scope='%s' baseClassName='%s' baseClass=%s templSpec=%s\n",
// cd ? qPrint(cd->name()):"<none>",
// qPrint(baseClassName),
// baseClass?qPrint(baseClass->name()):"<none>",
// qPrint(templSpec)
// );
//if (baseClassName.left(root->name.length())!=root->name ||
// baseClassName.at(root->name.length())!='<'
// ) // Check for base class with the same name.
// // If found then look in the outer scope for a match
// // and prevent recursion.
if (!isRecursiveBaseClass(root->name,baseClassName)
|| explicitGlobalScope
// sadly isRecursiveBaseClass always true for UNO IDL ifc/svc members
// (i.e. this is needed for addInterfaceOrServiceToServiceOrSingleton)
|| (root->lang==SrcLangExt::IDL &&
(root->section.isExportedInterface() ||
root->section.isIncludedService()))
)
{
AUTO_TRACE_ADD("class relation '{}' inherited/used by '{}' found prot={} virt={} templSpec='{}'",
baseClassName, root->name, bi->prot, bi->virt, templSpec);
int i=findTemplateSpecializationPosition(baseClassName);
int si=baseClassName.findRev("::",i);
if (si==-1) si=0;
if (baseClass==nullptr && static_cast<size_t>(i)!=baseClassName.length())
// base class has template specifiers
{
// TODO: here we should try to find the correct template specialization
// but for now, we only look for the unspecialized base class.
int e=findEndOfTemplate(baseClassName,i+1);
//printf("baseClass==0 i=%d e=%d\n",i,e);
if (e!=-1) // end of template was found at e
{
templSpec = removeRedundantWhiteSpace(baseClassName.mid(i,e-i));
baseClassName = baseClassName.left(i)+baseClassName.right(baseClassName.length()-e);
baseClass = resolver.resolveClassMutable(explicitGlobalScope ? Doxygen::globalScope : context,
baseClassName,
mode==Undocumented,
true
);
baseClassTypeDef = resolver.getTypedef();
//printf("baseClass=%p -> baseClass=%s templSpec=%s\n",
// baseClass,qPrint(baseClassName),qPrint(templSpec));
}
}
else if (baseClass && !templSpec.isEmpty()) // we have a known class, but also
// know it is a template, so see if
// we can also link to the explicit
// instance (for instance if a class
// derived from a template argument)
{
//printf("baseClass=%s templSpec=%s\n",qPrint(baseClass->name()),qPrint(templSpec));
ClassDefMutable *templClass=getClassMutable(baseClass->name()+templSpec);
if (templClass)
{
// use the template instance instead of the template base.
baseClass = templClass;
templSpec.clear();
}
}
//printf("cd=%p baseClass=%p\n",cd,baseClass);
bool found=baseClass!=nullptr && (baseClass!=cd || mode==TemplateInstances);
//printf("1. found=%d\n",found);
if (!found && si!=-1)
{
// replace any namespace aliases
replaceNamespaceAliases(baseClassName);
baseClass = resolver.resolveClassMutable(explicitGlobalScope ? Doxygen::globalScope : context,
baseClassName,
mode==Undocumented,
true
);
baseClassTypeDef = resolver.getTypedef();
found=baseClass!=nullptr && baseClass!=cd;
if (found) templSpec = resolver.getTemplateSpec();
}
//printf("2. found=%d\n",found);
if (!found)
{
baseClass=toClassDefMutable(findClassWithinClassContext(context,cd,baseClassName));
//printf("findClassWithinClassContext(%s,%s)=%p\n",
// qPrint(cd->name()),qPrint(baseClassName),baseClass);
found = baseClass!=nullptr && baseClass!=cd;
}
//printf("3. found=%d\n",found);
if (!found)
{
// for PHP the "use A\B as C" construct map class C to A::B, so we lookup
// the class name also in the alias mapping.
auto it = Doxygen::namespaceAliasMap.find(baseClassName.str());
if (it!=Doxygen::namespaceAliasMap.end()) // see if it is indeed a class.
{
baseClass=getClassMutable(QCString(it->second.alias));
found = baseClass!=nullptr && baseClass!=cd;
}
}
bool isATemplateArgument = templateNames.find(biName.str())!=templateNames.end();
//printf("4. found=%d\n",found);
if (found)
{
AUTO_TRACE_ADD("Documented base class '{}' templSpec='{}'",biName,templSpec);
// add base class to this class
// if templSpec is not empty then we should "instantiate"
// the template baseClass. A new ClassDef should be created
// to represent the instance. To be able to add the (instantiated)
// members and documentation of a template class
// (inserted in that template class at a later stage),
// the template should know about its instances.
// the instantiation process, should be done in a recursive way,
// since instantiating a template may introduce new inheritance
// relations.
if (!templSpec.isEmpty() && mode==TemplateInstances)
{
// if baseClass is actually a typedef then we should not
// instantiate it, since typedefs are in a different namespace
// see bug531637 for an example where this would otherwise hang
// Doxygen
if (baseClassTypeDef==nullptr)
{
//printf(" => findTemplateInstanceRelation: %s\n",qPrint(baseClass->name()));
findTemplateInstanceRelation(root,context,baseClass,templSpec,templateNames,baseClass->isArtificial());
}
}
else if (mode==DocumentedOnly || mode==Undocumented)
{
//printf(" => insert base class\n");
QCString usedName;
if (baseClassTypeDef || cd->isCSharp())
{
usedName=biName;
//printf("***** usedName=%s templSpec=%s\n",qPrint(usedName),qPrint(templSpec));
}
Protection prot = bi->prot;
if (Config_getBool(SIP_SUPPORT)) prot=Protection::Public;
if (cd!=baseClass && !cd->isSubClass(baseClass) && baseClass->isBaseClass(cd,true,templSpec)==0) // check for recursion, see bug690787
{
cd->insertBaseClass(baseClass,usedName,prot,bi->virt,templSpec);
// add this class as super class to the base class
baseClass->insertSubClass(cd,prot,bi->virt,templSpec);
}
else
{
warn(root->fileName,root->startLine,
"Detected potential recursive class relation "
"between class %s and base class %s!",
qPrint(cd->name()),qPrint(baseClass->name())
);
}
}
return TRUE;
}
else if (mode==Undocumented && (scopeOffset==0 || isATemplateArgument))
{
AUTO_TRACE_ADD("New undocumented base class '{}' baseClassName='{}' templSpec='{}' isArtificial={}",
biName,baseClassName,templSpec,isArtificial);
baseClass=nullptr;
if (isATemplateArgument)
{
baseClass = toClassDefMutable(Doxygen::hiddenClassLinkedMap->find(baseClassName));
if (baseClass==nullptr) // not found (or alias)
{
baseClass= toClassDefMutable(
Doxygen::hiddenClassLinkedMap->add(baseClassName,
createClassDef(root->fileName,root->startLine,root->startColumn,
baseClassName,
ClassDef::Class)));
if (baseClass) // really added (not alias)
{
if (isArtificial) baseClass->setArtificial(TRUE);
baseClass->setLanguage(root->lang);
}
}
}
else
{
baseClass = toClassDefMutable(Doxygen::classLinkedMap->find(baseClassName));
//printf("*** classDDict->find(%s)=%p biName=%s templSpec=%s\n",
// qPrint(baseClassName),baseClass,qPrint(biName),qPrint(templSpec));
if (baseClass==nullptr) // not found (or alias)
{
baseClass = toClassDefMutable(
Doxygen::classLinkedMap->add(baseClassName,
createClassDef(root->fileName,root->startLine,root->startColumn,
baseClassName,
ClassDef::Class)));
if (baseClass) // really added (not alias)
{
if (isArtificial) baseClass->setArtificial(TRUE);
baseClass->setLanguage(root->lang);
si = baseClassName.findRev("::");
if (si!=-1) // class is nested
{
Definition *sd = findScopeFromQualifiedName(Doxygen::globalScope,baseClassName.left(si),nullptr,root->tagInfo());
if (sd==nullptr || sd==Doxygen::globalScope) // outer scope not found
{
baseClass->setArtificial(TRUE); // see bug678139
}
}
}
}
}
if (baseClass)
{
if (biName.endsWith("-p"))
{
biName="<"+biName.left(biName.length()-2)+">";
}
if (!cd->isSubClass(baseClass) && cd!=baseClass && cd->isBaseClass(baseClass,true,templSpec)==0) // check for recursion
{
// add base class to this class
cd->insertBaseClass(baseClass,biName,bi->prot,bi->virt,templSpec);
// add this class as super class to the base class
baseClass->insertSubClass(cd,bi->prot,bi->virt,templSpec);
}
// the undocumented base was found in this file
baseClass->insertUsedFile(root->fileDef());
Definition *scope = buildScopeFromQualifiedName(baseClass->name(),root->lang,nullptr);
if (scope!=baseClass)
{
baseClass->setOuterScope(scope);
}
if (baseClassName.endsWith("-p"))
{
baseClass->setCompoundType(ClassDef::Protocol);
}
return TRUE;
}
else
{
AUTO_TRACE_ADD("Base class '{}' not created (alias?)",biName);
}
}
else
{
AUTO_TRACE_ADD("Base class '{}' not found",biName);
}
}
else
{
if (mode!=TemplateInstances)
{
warn(root->fileName,root->startLine,
"Detected potential recursive class relation "
"between class %s and base class %s!",
qPrint(root->name),qPrint(baseClassName)
);
}
// for mode==TemplateInstance this case is quite common and
// indicates a relation between a template class and a template
// instance with the same name.
}
if (scopeOffset==0)
{
scopeOffset=-1;
}
else if ((scopeOffset=scopeName.findRev("::",scopeOffset-1))==-1)
{
scopeOffset=0;
}
//printf("new scopeOffset='%d'",scopeOffset);
} while (scopeOffset>=0);
if (parentNode==nullptr)
{
lastParent=TRUE;
}
else
{
parentNode=parentNode->parent();
}
} while (lastParent);
return FALSE;
}
//----------------------------------------------------------------------
// Computes the base and super classes for each class in the tree
static bool isClassSection(const Entry *root)
{
if ( !root->name.isEmpty() )
{
if (root->section.isCompound())
// is it a compound (class, struct, union, interface ...)
{
return TRUE;
}
else if (root->section.isCompoundDoc())
// is it a documentation block with inheritance info.
{
bool hasExtends = !root->extends.empty();
if (hasExtends) return TRUE;
}
}
return FALSE;
}
/*! Builds a dictionary of all entry nodes in the tree starting with \a root
*/
static void findClassEntries(const Entry *root)
{
if (isClassSection(root))
{
g_classEntries.emplace(root->name.str(),root);
}
for (const auto &e : root->children()) findClassEntries(e.get());
}
static QCString extractClassName(const Entry *root)
{
// strip any anonymous scopes first
QCString bName=stripAnonymousNamespaceScope(root->name);
bName=stripTemplateSpecifiersFromScope(bName);
int i=0;
if ((root->lang==SrcLangExt::CSharp || root->lang==SrcLangExt::Java) &&
(i=bName.find('<'))!=-1)
{
// a Java/C# generic class looks like a C++ specialization, so we need to strip the
// template part before looking for matches
bName=bName.left(i);
}
return bName;
}
/*! Using the dictionary build by findClassEntries(), this
* function will look for additional template specialization that
* exists as inheritance relations only. These instances will be
* added to the template they are derived from.
*/
static void findInheritedTemplateInstances()
{
AUTO_TRACE();
ClassDefSet visitedClasses;
for (const auto &[name,root] : g_classEntries)
{
QCString bName = extractClassName(root);
ClassDefMutable *cdm = getClassMutable(bName);
if (cdm)
{
findBaseClassesForClass(root,cdm,cdm,cdm,TemplateInstances,FALSE);
}
}
}
static void makeTemplateInstanceRelation(const Entry *root,ClassDefMutable *cd)
{
AUTO_TRACE("root->name={} cd={}",root->name,cd->name());
int i = root->name.find('<');
if (i!=-1)
{
ClassDefMutable *master = getClassMutable(root->name.left(i));
if (master && master!=cd && !cd->templateMaster())
{
AUTO_TRACE_ADD("class={} master={}",cd->name(),cd->templateMaster()?cd->templateMaster()->name():"<none>",master->name());
cd->setTemplateMaster(master);
master->insertExplicitTemplateInstance(cd,root->name.mid(i));
}
}
}
static void findUsedTemplateInstances()
{
AUTO_TRACE();
for (const auto &[name,root] : g_classEntries)
{
QCString bName = extractClassName(root);
ClassDefMutable *cdm = getClassMutable(bName);
if (cdm)
{
findUsedClassesForClass(root,cdm,cdm,cdm,TRUE);
makeTemplateInstanceRelation(root,cdm);
cdm->addTypeConstraints();
}
}
}
static void warnUndocumentedNamespaces()
{
AUTO_TRACE();
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (!nd->hasDocumentation())
{
if ((guessSection(nd->getDefFileName()).isHeader() ||
nd->getLanguage() == SrcLangExt::Fortran) && // Fortran doesn't have header files.
!Config_getBool(HIDE_UNDOC_NAMESPACES) // undocumented namespaces are visible
)
{
warn_undoc(nd->getDefFileName(),nd->getDefLine(), "%s %s is not documented.",
nd->getLanguage() == SrcLangExt::Fortran ? "Module" : "Namespace",
qPrint(nd->name()));
}
}
}
}
static void computeClassRelations()
{
AUTO_TRACE();
for (const auto &[name,root] : g_classEntries)
{
QCString bName = extractClassName(root);
ClassDefMutable *cd = getClassMutable(bName);
if (cd)
{
findBaseClassesForClass(root,cd,cd,cd,DocumentedOnly,FALSE);
}
size_t numMembers = cd ? cd->memberNameInfoLinkedMap().size() : 0;
if ((cd==nullptr || (!cd->hasDocumentation() && !cd->isReference())) && numMembers>0 && !bName.endsWith("::"))
{
if (!root->name.isEmpty() && root->name.find('@')==-1 && // normal name
(guessSection(root->fileName).isHeader() ||
Config_getBool(EXTRACT_LOCAL_CLASSES)) && // not defined in source file
protectionLevelVisible(root->protection) && // hidden by protection
!Config_getBool(HIDE_UNDOC_CLASSES) // undocumented class are visible
)
warn_undoc(
root->fileName,root->startLine,
"Compound %s is not documented.",
qPrint(root->name)
);
}
}
}
static void computeTemplateClassRelations()
{
AUTO_TRACE();
for (const auto &[name,root] : g_classEntries)
{
QCString bName=stripAnonymousNamespaceScope(root->name);
bName=stripTemplateSpecifiersFromScope(bName);
ClassDefMutable *cd=getClassMutable(bName);
// strip any anonymous scopes first
if (cd && !cd->getTemplateInstances().empty())
{
AUTO_TRACE_ADD("Template class '{}'",cd->name());
for (const auto &ti : cd->getTemplateInstances()) // for each template instance
{
ClassDefMutable *tcd=toClassDefMutable(ti.classDef);
if (tcd)
{
AUTO_TRACE_ADD("Template instance '{}'",tcd->name());
QCString templSpec = ti.templSpec;
std::unique_ptr<ArgumentList> templArgs = stringToArgumentList(tcd->getLanguage(),templSpec);
for (const BaseInfo &bi : root->extends)
{
// check if the base class is a template argument
BaseInfo tbi = bi;
const ArgumentList &tl = cd->templateArguments();
if (!tl.empty())
{
TemplateNameMap baseClassNames = tcd->getTemplateBaseClassNames();
TemplateNameMap templateNames = getTemplateArgumentsInName(tl,bi.name.str());
// for each template name that we inherit from we need to
// substitute the formal with the actual arguments
TemplateNameMap actualTemplateNames;
for (const auto &tn_kv : templateNames)
{
size_t templIndex = tn_kv.second;
Argument actArg;
bool hasActArg=FALSE;
if (templIndex<templArgs->size())
{
actArg=templArgs->at(templIndex);
hasActArg=TRUE;
}
if (hasActArg &&
baseClassNames.find(actArg.type.str())!=baseClassNames.end() &&
actualTemplateNames.find(actArg.type.str())==actualTemplateNames.end()
)
{
actualTemplateNames.emplace(actArg.type.str(),static_cast<int>(templIndex));
}
}
tbi.name = substituteTemplateArgumentsInString(bi.name,tl,templArgs.get());
// find a documented base class in the correct scope
if (!findClassRelation(root,cd,tcd,&tbi,actualTemplateNames,DocumentedOnly,FALSE))
{
// no documented base class -> try to find an undocumented one
findClassRelation(root,cd,tcd,&tbi,actualTemplateNames,Undocumented,TRUE);
}
}
}
}
}
}
}
}
//-----------------------------------------------------------------------
// compute the references (anchors in HTML) for each function in the file
static void computeMemberReferences()
{
AUTO_TRACE();
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->computeAnchors();
}
}
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->computeAnchors();
}
}
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->computeAnchors();
}
}
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->computeAnchors();
}
}
//----------------------------------------------------------------------
static void addListReferences()
{
AUTO_TRACE();
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->addListReferences();
}
}
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->addListReferences();
}
}
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->addListReferences();
}
}
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->addListReferences();
}
for (const auto &pd : *Doxygen::pageLinkedMap)
{
QCString name = pd->getOutputFileBase();
if (pd->getGroupDef())
{
name = pd->getGroupDef()->getOutputFileBase();
}
{
const RefItemVector &xrefItems = pd->xrefListItems();
addRefItem(xrefItems,
name,
theTranslator->trPage(TRUE,TRUE),
name,pd->title(),QCString(),nullptr);
}
}
for (const auto &dd : *Doxygen::dirLinkedMap)
{
QCString name = dd->getOutputFileBase();
//if (dd->getGroupDef())
//{
// name = dd->getGroupDef()->getOutputFileBase();
//}
const RefItemVector &xrefItems = dd->xrefListItems();
addRefItem(xrefItems,
name,
theTranslator->trDir(TRUE,TRUE),
name,dd->displayName(),QCString(),nullptr);
}
ModuleManager::instance().addListReferences();
}
//----------------------------------------------------------------------
static void generateXRefPages()
{
AUTO_TRACE();
for (RefListManager::Ptr &rl : RefListManager::instance())
{
rl->generatePage();
}
}
//----------------------------------------------------------------------
// Copy the documentation in entry 'root' to member definition 'md' and
// set the function declaration of the member to 'funcDecl'. If the boolean
// over_load is set the standard overload text is added.
static void addMemberDocs(const Entry *root,
MemberDefMutable *md, const QCString &funcDecl,
const ArgumentList *al,
bool over_load,
TypeSpecifier spec
)
{
if (md==nullptr) return;
AUTO_TRACE("scope='{}' name='{}' args='{}' funcDecl='{}' mSpec={}",
root->parent()->name,md->name(),md->argsString(),funcDecl,spec);
if (!root->section.isDoc()) // @fn or @var does not need to specify the complete definition, so don't overwrite it
{
QCString fDecl=funcDecl;
// strip extern specifier
fDecl.stripPrefix("extern ");
md->setDefinition(fDecl);
}
applyMemberOverrideOptions(root,md);
md->addQualifiers(root->qualifiers);
ClassDefMutable *cd=md->getClassDefMutable();
const NamespaceDef *nd=md->getNamespaceDef();
QCString fullName;
if (cd)
fullName = cd->name();
else if (nd)
fullName = nd->name();
if (!fullName.isEmpty()) fullName+="::";
fullName+=md->name();
FileDef *rfd=root->fileDef();
// TODO determine scope based on root not md
Definition *rscope = md->getOuterScope();
const ArgumentList &mdAl = md->argumentList();
if (al)
{
ArgumentList mergedAl = *al;
//printf("merging arguments (1) docs=%d\n",root->doc.isEmpty());
mergeArguments(const_cast<ArgumentList&>(mdAl),mergedAl,!root->doc.isEmpty());
}
else
{
if (
matchArguments2( md->getOuterScope(), md->getFileDef(),const_cast<ArgumentList*>(&mdAl),
rscope,rfd,&root->argList,
TRUE, root->lang
)
)
{
//printf("merging arguments (2)\n");
ArgumentList mergedArgList = root->argList;
mergeArguments(const_cast<ArgumentList&>(mdAl),mergedArgList,!root->doc.isEmpty());
}
}
if (over_load) // the \overload keyword was used
{
QCString doc=getOverloadDocs();
if (!root->doc.isEmpty())
{
doc+="<p>";
doc+=root->doc;
}
md->setDocumentation(doc,root->docFile,root->docLine);
md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
md->setDocsForDefinition(!root->proto);
}
else
{
//printf("overwrite!\n");
md->setDocumentation(root->doc,root->docFile,root->docLine);
md->setDocsForDefinition(!root->proto);
//printf("overwrite!\n");
md->setBriefDescription(root->brief,root->briefFile,root->briefLine);
if (
(md->inbodyDocumentation().isEmpty() ||
!root->parent()->name.isEmpty()
) && !root->inbodyDocs.isEmpty()
)
{
md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
}
}
//printf("initializer: '%s'(isEmpty=%d) '%s'(isEmpty=%d)\n",
// qPrint(md->initializer()),md->initializer().isEmpty(),
// qPrint(root->initializer),root->initializer.isEmpty()
// );
std::string rootInit = root->initializer.str();
if (md->initializer().isEmpty() && !rootInit.empty())
{
//printf("setInitializer\n");
md->setInitializer(rootInit.c_str());
}
if (md->requiresClause().isEmpty() && !root->req.isEmpty())
{
md->setRequiresClause(root->req);
}
md->setMaxInitLines(root->initLines);
if (rfd)
{
if ((md->getStartBodyLine()==-1 && root->bodyLine!=-1)
)
{
//printf("Setting new body segment [%d,%d]\n",root->bodyLine,root->endBodyLine);
md->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
md->setBodyDef(rfd);
}
md->setRefItems(root->sli);
}
applyMemberOverrideOptions(root,md);
md->addQualifiers(root->qualifiers);
md->mergeMemberSpecifiers(spec);
md->addSectionsToDefinition(root->anchors);
addMemberToGroups(root,md);
ModuleManager::instance().addMemberToModule(root,md);
if (cd) cd->insertUsedFile(rfd);
//printf("root->mGrpId=%d\n",root->mGrpId);
if (root->mGrpId!=-1)
{
if (md->getMemberGroupId()!=-1)
{
if (md->getMemberGroupId()!=root->mGrpId)
{
warn(
root->fileName,root->startLine,
"member %s belongs to two different groups. The second "
"one found here will be ignored.",
qPrint(md->name())
);
}
}
else // set group id
{
//printf("setMemberGroupId=%d md=%s\n",root->mGrpId,qPrint(md->name()));
md->setMemberGroupId(root->mGrpId);
}
}
md->addQualifiers(root->qualifiers);
}
//----------------------------------------------------------------------
// find a class definition given the scope name and (optionally) a
// template list specifier
static const ClassDef *findClassDefinition(FileDef *fd,NamespaceDef *nd,
const QCString &scopeName)
{
SymbolResolver resolver(fd);
const ClassDef *tcd = resolver.resolveClass(nd,scopeName,true,true);
return tcd;
}
//----------------------------------------------------------------------------
// Returns TRUE, if the entry belongs to the group of the member definition,
// otherwise FALSE.
static bool isEntryInGroupOfMember(const Entry *root,const MemberDef *md,bool allowNoGroup=false)
{
const GroupDef *gd = md->getGroupDef();
if (!gd)
{
return allowNoGroup;
}
for (const auto &g : root->groups)
{
if (g.groupname == gd->name())
{
return true; // matching group
}
}
return false;
}
//----------------------------------------------------------------------
// Adds the documentation contained in 'root' to a global function
// with name 'name' and argument list 'args' (for overloading) and
// function declaration 'decl' to the corresponding member definition.
static bool findGlobalMember(const Entry *root,
const QCString &namespaceName,
const QCString &type,
const QCString &name,
const QCString &tempArg,
const QCString &,
const QCString &decl,
TypeSpecifier /* spec */)
{
AUTO_TRACE("namespace='{}' type='{}' name='{}' tempArg='{}' decl='{}'",namespaceName,type,name,tempArg,decl);
QCString n=name;
if (n.isEmpty()) return FALSE;
if (n.find("::")!=-1) return FALSE; // skip undefined class members
MemberName *mn=Doxygen::functionNameLinkedMap->find(n+tempArg); // look in function dictionary
if (mn==nullptr)
{
mn=Doxygen::functionNameLinkedMap->find(n); // try without template arguments
}
if (mn) // function name defined
{
AUTO_TRACE_ADD("Found symbol name");
//int count=0;
bool found=FALSE;
for (const auto &md : *mn)
{
// If the entry has groups, then restrict the search to members which are
// in one of the groups of the entry. If md is not associated with a group yet,
// allow this documentation entry to add the group info.
if (!root->groups.empty() && !isEntryInGroupOfMember(root, md.get(), true))
{
continue;
}
const NamespaceDef *nd=nullptr;
if (md->isAlias() && md->getOuterScope() &&
md->getOuterScope()->definitionType()==Definition::TypeNamespace)
{
nd = toNamespaceDef(md->getOuterScope());
}
else
{
nd = md->getNamespaceDef();
}
// special case for strong enums
int enumNamePos=0;
if (nd && md->isEnumValue() && (enumNamePos=namespaceName.findRev("::"))!=-1)
{ // md part of a strong enum in a namespace?
QCString enumName = namespaceName.mid(enumNamePos+2);
if (namespaceName.left(enumNamePos)==nd->name())
{
MemberName *enumMn=Doxygen::functionNameLinkedMap->find(enumName);
if (enumMn)
{
for (const auto &emd : *enumMn)
{
found = emd->isStrong() && md->getEnumScope()==emd.get();
if (found)
{
addMemberDocs(root,toMemberDefMutable(md->resolveAlias()),decl,nullptr,FALSE,root->spec);
break;
}
}
}
}
if (found)
{
break;
}
}
else if (nd==nullptr && md->isEnumValue()) // md part of global strong enum?
{
MemberName *enumMn=Doxygen::functionNameLinkedMap->find(namespaceName);
if (enumMn)
{
for (const auto &emd : *enumMn)
{
found = emd->isStrong() && md->getEnumScope()==emd.get();
if (found)
{
addMemberDocs(root,toMemberDefMutable(md->resolveAlias()),decl,nullptr,FALSE,root->spec);
break;
}
}
}
}
const FileDef *fd=root->fileDef();
//printf("File %s\n",fd ? qPrint(fd->name()) : "<none>");
LinkedRefMap<NamespaceDef> nl;
if (fd)
{
nl = fd->getUsedNamespaces();
}
//printf("NamespaceList %p\n",nl);
// search in the list of namespaces that are imported via a
// using declaration
bool viaUsingDirective = nd && nl.find(nd->qualifiedName())!=nullptr;
if ((namespaceName.isEmpty() && nd==nullptr) || // not in a namespace
(nd && nd->name()==namespaceName) || // or in the same namespace
viaUsingDirective // member in 'using' namespace
)
{
AUTO_TRACE_ADD("Try to add member '{}' to scope '{}'",md->name(),namespaceName);
NamespaceDef *rnd = nullptr;
if (!namespaceName.isEmpty()) rnd = Doxygen::namespaceLinkedMap->find(namespaceName);
const ArgumentList &mdAl = md.get()->argumentList();
bool matching=
(mdAl.empty() && root->argList.empty()) ||
md->isVariable() || md->isTypedef() || /* in case of function pointers */
matchArguments2(md->getOuterScope(),md.get()->getFileDef(),&mdAl,
rnd ? rnd : Doxygen::globalScope,fd,&root->argList,
FALSE,root->lang);
// for template members we need to check if the number of
// template arguments is the same, otherwise we are dealing with
// different functions.
if (matching && !root->tArgLists.empty())
{
const ArgumentList &mdTempl = md->templateArguments();
if (root->tArgLists.back().size()!=mdTempl.size())
{
matching=FALSE;
}
}
//printf("%s<->%s\n",
// qPrint(argListToString(md->argumentList())),
// qPrint(argListToString(root->argList)));
// For static members we also check if the comment block was found in
// the same file. This is needed because static members with the same
// name can be in different files. Thus it would be wrong to just
// put the comment block at the first syntactically matching member. If
// the comment block belongs to a group of the static member, then add
// the documentation even if it is in a different file.
if (matching && md->isStatic() &&
md->getDefFileName()!=root->fileName &&
mn->size()>1 &&
!isEntryInGroupOfMember(root,md.get()))
{
matching = FALSE;
}
// for template member we also need to check the return type and requires
if (!md->templateArguments().empty() && !root->tArgLists.empty())
{
//printf("Comparing return types '%s'<->'%s'\n",
// md->typeString(),type);
if (md->templateArguments().size()!=root->tArgLists.back().size() ||
md->typeString()!=type ||
md->requiresClause()!=root->req)
{
//printf(" ---> no matching\n");
matching = FALSE;
}
}
if (matching) // add docs to the member
{
AUTO_TRACE_ADD("Match found");
addMemberDocs(root,toMemberDefMutable(md->resolveAlias()),decl,&root->argList,FALSE,root->spec);
found=TRUE;
break;
}
}
}
if (!found && root->relatesType!=RelatesType::Duplicate && root->section.isFunction()) // no match
{
QCString fullFuncDecl=decl;
if (!root->argList.empty()) fullFuncDecl+=argListToString(root->argList,TRUE);
QCString warnMsg =
QCString("no matching file member found for \n")+substitute(fullFuncDecl,"%","%%");
if (mn->size()>0)
{
warnMsg+="\nPossible candidates:";
for (const auto &md : *mn)
{
warnMsg+="\n '";
warnMsg+=substitute(md->declaration(),"%","%%");
warnMsg+="' " + warn_line(md->getDefFileName(),md->getDefLine());
}
}
warn(root->fileName,root->startLine, "%s", qPrint(warnMsg));
}
}
else // got docs for an undefined member!
{
if (root->type!="friend class" &&
root->type!="friend struct" &&
root->type!="friend union" &&
root->type!="friend" &&
(!Config_getBool(TYPEDEF_HIDES_STRUCT) ||
root->type.find("typedef ")==-1)
)
{
warn(root->fileName,root->startLine,
"documented symbol '%s' was not declared or defined.",qPrint(decl)
);
}
}
return TRUE;
}
static bool isSpecialization(
const ArgumentLists &srcTempArgLists,
const ArgumentLists &dstTempArgLists
)
{
auto srcIt = srcTempArgLists.begin();
auto dstIt = dstTempArgLists.begin();
while (srcIt!=srcTempArgLists.end() && dstIt!=dstTempArgLists.end())
{
if ((*srcIt).size()!=(*dstIt).size()) return TRUE;
++srcIt;
++dstIt;
}
return FALSE;
}
static bool scopeIsTemplate(const Definition *d)
{
bool result=FALSE;
if (d && d->definitionType()==Definition::TypeClass)
{
result = !(toClassDef(d))->templateArguments().empty() ||
scopeIsTemplate(d->getOuterScope());
}
return result;
}
static QCString substituteTemplatesInString(
const ArgumentLists &srcTempArgLists,
const ArgumentLists &dstTempArgLists,
const std::string &src
)
{
std::string dst;
static const reg::Ex re(R"(\a\w*)");
reg::Iterator it(src,re);
reg::Iterator end;
//printf("type=%s\n",qPrint(sa->type));
size_t p=0;
for (; it!=end ; ++it) // for each word in srcType
{
const auto &match = *it;
size_t i = match.position();
size_t l = match.length();
bool found=FALSE;
dst+=src.substr(p,i-p);
std::string name=match.str();
auto srcIt = srcTempArgLists.begin();
auto dstIt = dstTempArgLists.begin();
while (srcIt!=srcTempArgLists.end() && !found)
{
const ArgumentList *tdAli = nullptr;
std::vector<Argument>::const_iterator tdaIt;
if (dstIt!=dstTempArgLists.end())
{
tdAli = &(*dstIt);
tdaIt = tdAli->begin();
++dstIt;
}
const ArgumentList &tsaLi = *srcIt;
for (auto tsaIt = tsaLi.begin(); tsaIt!=tsaLi.end() && !found; ++tsaIt)
{
Argument tsa = *tsaIt;
const Argument *tda = nullptr;
if (tdAli && tdaIt!=tdAli->end())
{
tda = &(*tdaIt);
++tdaIt;
}
//if (tda) printf("tsa=%s|%s tda=%s|%s\n",
// qPrint(tsa.type),qPrint(tsa.name),
// qPrint(tda->type),qPrint(tda->name));
if (name==tsa.name.str())
{
if (tda && tda->name.isEmpty())
{
QCString tdaName = tda->name;
QCString tdaType = tda->type;
int vc=0;
if (tdaType.startsWith("class ")) vc=6;
else if (tdaType.startsWith("typename ")) vc=9;
if (vc>0) // convert type=="class T" to type=="class" name=="T"
{
tdaName = tdaType.mid(vc);
}
if (!tdaName.isEmpty())
{
name=tdaName.str(); // substitute
found=TRUE;
}
}
}
}
//printf(" srcList='%s' dstList='%s faList='%s'\n",
// qPrint(argListToString(srclali.current())),
// qPrint(argListToString(dstlali.current())),
// funcTempArgList ? qPrint(argListToString(funcTempArgList)) : "<none>");
++srcIt;
}
dst+=name;
p=i+l;
}
dst+=src.substr(p);
//printf(" substituteTemplatesInString(%s)=%s\n",
// qPrint(src),qPrint(dst));
return QCString(dst);
}
static void substituteTemplatesInArgList(
const ArgumentLists &srcTempArgLists,
const ArgumentLists &dstTempArgLists,
const ArgumentList &src,
ArgumentList &dst
)
{
auto dstIt = dst.begin();
for (const Argument &sa : src)
{
QCString dstType = substituteTemplatesInString(srcTempArgLists,dstTempArgLists,sa.type.str());
QCString dstArray = substituteTemplatesInString(srcTempArgLists,dstTempArgLists,sa.array.str());
if (dstIt == dst.end())
{
Argument da = sa;
da.type = dstType;
da.array = dstArray;
dst.push_back(da);
dstIt = dst.end();
}
else
{
Argument da = *dstIt;
da.type = dstType;
da.array = dstArray;
++dstIt;
}
}
dst.setConstSpecifier(src.constSpecifier());
dst.setVolatileSpecifier(src.volatileSpecifier());
dst.setPureSpecifier(src.pureSpecifier());
dst.setTrailingReturnType(substituteTemplatesInString(
srcTempArgLists,dstTempArgLists,
src.trailingReturnType().str()));
dst.setIsDeleted(src.isDeleted());
dst.setRefQualifier(src.refQualifier());
dst.setNoParameters(src.noParameters());
//printf("substituteTemplatesInArgList: replacing %s with %s\n",
// qPrint(argListToString(src)),qPrint(argListToString(dst))
// );
}
//-------------------------------------------------------------------------------------------
static void addLocalObjCMethod(const Entry *root,
const QCString &scopeName,
const QCString &funcType,const QCString &funcName,const QCString &funcArgs,
const QCString &exceptions,const QCString &funcDecl,
TypeSpecifier spec)
{
AUTO_TRACE();
//printf("scopeName='%s' className='%s'\n",qPrint(scopeName),qPrint(className));
ClassDefMutable *cd=nullptr;
if (Config_getBool(EXTRACT_LOCAL_METHODS) && (cd=getClassMutable(scopeName)))
{
AUTO_TRACE_ADD("Local objective C method '{}' scopeName='{}'",root->name,scopeName);
auto md = createMemberDef(
root->fileName,root->startLine,root->startColumn,
funcType,funcName,funcArgs,exceptions,
root->protection,root->virt,root->isStatic,Relationship::Member,
MemberType::Function,ArgumentList(),root->argList,root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setLanguage(root->lang);
mmd->setId(root->id);
mmd->makeImplementationDetail();
mmd->setMemberClass(cd);
mmd->setDefinition(funcDecl);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setDocsForDefinition(!root->proto);
mmd->setPrototype(root->proto,root->fileName,root->startLine,root->startColumn);
mmd->addSectionsToDefinition(root->anchors);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
FileDef *fd=root->fileDef();
mmd->setBodyDef(fd);
mmd->setMemberSpecifiers(spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setMemberGroupId(root->mGrpId);
cd->insertMember(md.get());
cd->insertUsedFile(fd);
mmd->setRefItems(root->sli);
MemberName *mn = Doxygen::memberNameLinkedMap->add(root->name);
mn->push_back(std::move(md));
}
else
{
// local objective C method found for class without interface
}
}
//-------------------------------------------------------------------------------------------
static void addMemberFunction(const Entry *root,
MemberName *mn,
const QCString &scopeName,
const QCString &namespaceName,
const QCString &className,
const QCString &funcTyp,
const QCString &funcName,
const QCString &funcArgs,
const QCString &funcTempList,
const QCString &exceptions,
const QCString &type,
const QCString &args,
bool isFriend,
TypeSpecifier spec,
const QCString &relates,
const QCString &funcDecl,
bool overloaded,
bool isFunc)
{
AUTO_TRACE();
QCString funcType = funcTyp;
int count=0;
int noMatchCount=0;
bool memFound=FALSE;
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md==nullptr) continue;
ClassDefMutable *cd=md->getClassDefMutable();
if (cd==nullptr) continue;
//AUTO_TRACE_ADD("member definition found, scope needed='{}' scope='{}' args='{}' fileName='{}'",
// scopeName, cd->name(), md->argsString(), root->fileName);
FileDef *fd=root->fileDef();
NamespaceDef *nd=nullptr;
if (!namespaceName.isEmpty()) nd=getResolvedNamespace(namespaceName);
//printf("scopeName %s->%s\n",qPrint(scopeName),
// qPrint(stripTemplateSpecifiersFromScope(scopeName,FALSE)));
// if the member we are searching for is an enum value that is part of
// a "strong" enum, we need to look into the fields of the enum for a match
int enumNamePos=0;
if (md->isEnumValue() && (enumNamePos=className.findRev("::"))!=-1)
{
QCString enumName = className.mid(enumNamePos+2);
QCString fullScope = className.left(enumNamePos);
if (!namespaceName.isEmpty()) fullScope.prepend(namespaceName+"::");
if (fullScope==cd->name())
{
MemberName *enumMn=Doxygen::memberNameLinkedMap->find(enumName);
//printf("enumMn(%s)=%p\n",qPrint(className),(void*)enumMn);
if (enumMn)
{
for (const auto &emd : *enumMn)
{
memFound = emd->isStrong() && md->getEnumScope()==emd.get();
if (memFound)
{
addMemberDocs(root,md,funcDecl,nullptr,overloaded,spec);
count++;
}
if (memFound) break;
}
}
}
}
if (memFound) break;
const ClassDef *tcd=findClassDefinition(fd,nd,scopeName);
if (tcd==nullptr && cd && stripAnonymousNamespaceScope(cd->name())==scopeName)
{
// don't be fooled by anonymous scopes
tcd=cd;
}
//printf("Looking for %s inside nd=%s result=%p (%s) cd=%p\n",
// qPrint(scopeName),nd?qPrint(nd->name()):"<none>",tcd,tcd?qPrint(tcd->name()):"",cd);
if (cd && tcd==cd) // member's classes match
{
AUTO_TRACE_ADD("class definition '{}' found",cd->name());
// get the template parameter lists found at the member declaration
ArgumentLists declTemplArgs = cd->getTemplateParameterLists();
const ArgumentList &templAl = md->templateArguments();
if (!templAl.empty())
{
declTemplArgs.push_back(templAl);
}
// get the template parameter lists found at the member definition
const ArgumentLists &defTemplArgs = root->tArgLists;
//printf("defTemplArgs=%p\n",defTemplArgs);
// do we replace the decl argument lists with the def argument lists?
bool substDone=FALSE;
ArgumentList argList;
/* substitute the occurrences of class template names in the
* argument list before matching
*/
const ArgumentList &mdAl = md->argumentList();
if (declTemplArgs.size()>0 && declTemplArgs.size()==defTemplArgs.size())
{
/* the function definition has template arguments
* and the class definition also has template arguments, so
* we must substitute the template names of the class by that
* of the function definition before matching.
*/
substituteTemplatesInArgList(declTemplArgs,defTemplArgs,mdAl,argList);
substDone=TRUE;
}
else /* no template arguments, compare argument lists directly */
{
argList = mdAl;
}
AUTO_TRACE_ADD("matching '{}'<=>'{}' className='{}' namespaceName='{}'",
argListToString(argList,TRUE),argListToString(root->argList,TRUE),className,namespaceName);
bool matching=
md->isVariable() || md->isTypedef() || // needed for function pointers
matchArguments2(
md->getClassDef(),md->getFileDef(),&argList,
cd,fd,&root->argList,
TRUE,root->lang);
if (md->getLanguage()==SrcLangExt::ObjC && md->isVariable() && root->section.isFunction())
{
matching = FALSE; // don't match methods and attributes with the same name
}
// for template member we also need to check the return type
if (!md->templateArguments().empty() && !root->tArgLists.empty())
{
QCString memType = md->typeString();
memType.stripPrefix("static "); // see bug700696
funcType=substitute(stripTemplateSpecifiersFromScope(funcType,TRUE),
className+"::",""); // see bug700693 & bug732594
memType=substitute(stripTemplateSpecifiersFromScope(memType,TRUE),
className+"::",""); // see bug758900
AUTO_TRACE_ADD("Comparing return types '{}'<->'{}' #args {}<->{}",
md->typeString(),funcType,md->templateArguments().size(),root->tArgLists.back().size());
if (md->templateArguments().size()!=root->tArgLists.back().size() || memType!=funcType)
{
//printf(" ---> no matching\n");
matching = FALSE;
}
}
else if (defTemplArgs.size()>declTemplArgs.size())
{
// avoid matching a non-template function in a template class against a
// template function with the same name and parameters, see issue #10184
substDone = false;
matching = false;
}
bool rootIsUserDoc = root->section.isMemberDoc();
bool classIsTemplate = scopeIsTemplate(md->getClassDef());
bool mdIsTemplate = md->templateArguments().hasParameters();
bool classOrMdIsTemplate = mdIsTemplate || classIsTemplate;
bool rootIsTemplate = !root->tArgLists.empty();
//printf("classIsTemplate=%d mdIsTemplate=%d rootIsTemplate=%d\n",classIsTemplate,mdIsTemplate,rootIsTemplate);
if (!rootIsUserDoc && // don't check out-of-line @fn references, see bug722457
(mdIsTemplate || rootIsTemplate) && // either md or root is a template
((classOrMdIsTemplate && !rootIsTemplate) || (!classOrMdIsTemplate && rootIsTemplate))
)
{
// Method with template return type does not match method without return type
// even if the parameters are the same. See also bug709052
AUTO_TRACE_ADD("Comparing return types: template v.s. non-template");
matching = FALSE;
}
AUTO_TRACE_ADD("Match results of matchArguments2='{}' substDone='{}'",matching,substDone);
if (substDone) // found a new argument list
{
if (matching) // replace member's argument list
{
md->setDefinitionTemplateParameterLists(root->tArgLists);
md->moveArgumentList(std::make_unique<ArgumentList>(argList));
}
else // no match
{
if (!funcTempList.isEmpty() &&
isSpecialization(declTemplArgs,defTemplArgs))
{
// check if we are dealing with a partial template
// specialization. In this case we add it to the class
// even though the member arguments do not match.
addMethodToClass(root,cd,type,md->name(),args,isFriend,
md->protection(),md->isStatic(),md->virtualness(),spec,relates);
return;
}
}
}
if (matching)
{
addMemberDocs(root,md,funcDecl,nullptr,overloaded,spec);
count++;
memFound=TRUE;
}
}
else if (cd && cd!=tcd) // we did find a class with the same name as cd
// but in a different namespace
{
noMatchCount++;
}
if (memFound) break;
}
if (count==0 && root->parent() && root->parent()->section.isObjcImpl())
{
addLocalObjCMethod(root,scopeName,funcType,funcName,funcArgs,exceptions,funcDecl,spec);
return;
}
if (count==0 && !(isFriend && funcType=="class"))
{
int candidates=0;
const ClassDef *ecd = nullptr, *ucd = nullptr;
MemberDef *emd = nullptr, *umd = nullptr;
//printf("Assume template class\n");
for (const auto &md : *mn)
{
MemberDef *cmd=md.get();
MemberDefMutable *cdmdm = toMemberDefMutable(cmd);
ClassDefMutable *ccd=cdmdm ? cdmdm->getClassDefMutable() : nullptr;
//printf("ccd->name()==%s className=%s\n",qPrint(ccd->name()),qPrint(className));
if (ccd!=nullptr && rightScopeMatch(ccd->name(),className))
{
const ArgumentList &templAl = md->templateArguments();
if (!root->tArgLists.empty() && !templAl.empty() &&
root->tArgLists.back().size()<=templAl.size())
{
AUTO_TRACE_ADD("add template specialization");
addMethodToClass(root,ccd,type,md->name(),args,isFriend,
root->protection,root->isStatic,root->virt,spec,relates);
return;
}
if (argListToString(md->argumentList(),FALSE,FALSE) ==
argListToString(root->argList,FALSE,FALSE))
{ // exact argument list match -> remember
ucd = ecd = ccd;
umd = emd = cmd;
AUTO_TRACE_ADD("new candidate className='{}' scope='{}' args='{}': exact match",
className,ccd->name(),md->argsString());
}
else // arguments do not match, but member name and scope do -> remember
{
ucd = ccd;
umd = cmd;
AUTO_TRACE_ADD("new candidate className='{}' scope='{}' args='{}': no match",
className,ccd->name(),md->argsString());
}
candidates++;
}
}
bool strictProtoMatching = Config_getBool(STRICT_PROTO_MATCHING);
if (!strictProtoMatching)
{
if (candidates==1 && ucd && umd)
{
// we didn't find an actual match on argument lists, but there is only 1 member with this
// name in the same scope, so that has to be the one.
addMemberDocs(root,toMemberDefMutable(umd),funcDecl,nullptr,overloaded,spec);
return;
}
else if (candidates>1 && ecd && emd)
{
// we didn't find a unique match using type resolution,
// but one of the matches has the exact same signature so
// we take that one.
addMemberDocs(root,toMemberDefMutable(emd),funcDecl,nullptr,overloaded,spec);
return;
}
}
QCString warnMsg = "no ";
if (noMatchCount>1) warnMsg+="uniquely ";
warnMsg+="matching class member found for \n";
for (const ArgumentList &al : root->tArgLists)
{
warnMsg+=" template ";
warnMsg+=tempArgListToString(al,root->lang);
warnMsg+='\n';
}
QCString fullFuncDecl=funcDecl;
if (isFunc) fullFuncDecl+=argListToString(root->argList,TRUE);
warnMsg+=" ";
warnMsg+=fullFuncDecl;
if (candidates>0 || noMatchCount>=1)
{
warnMsg+="\nPossible candidates:";
NamespaceDef *nd=nullptr;
if (!namespaceName.isEmpty()) nd=getResolvedNamespace(namespaceName);
FileDef *fd=root->fileDef();
for (const auto &md : *mn)
{
const ClassDef *cd=md->getClassDef();
const ClassDef *tcd=findClassDefinition(fd,nd,scopeName);
if (tcd==nullptr && cd && stripAnonymousNamespaceScope(cd->name())==scopeName)
{
// don't be fooled by anonymous scopes
tcd=cd;
}
if (cd!=nullptr && (rightScopeMatch(cd->name(),className) || (cd!=tcd)))
{
warnMsg+='\n';
const ArgumentList &templAl = md->templateArguments();
warnMsg+=" '";
if (templAl.hasParameters())
{
warnMsg+="template ";
warnMsg+=tempArgListToString(templAl,root->lang);
warnMsg+='\n';
warnMsg+=" ";
}
if (!md->typeString().isEmpty())
{
warnMsg+=md->typeString();
warnMsg+=' ';
}
QCString qScope = cd->qualifiedNameWithTemplateParameters();
if (!qScope.isEmpty())
warnMsg+=qScope+"::"+md->name();
warnMsg+=md->argsString();
warnMsg+="' " + warn_line(md->getDefFileName(),md->getDefLine());
}
}
}
warn(root->fileName,root->startLine,"%s",qPrint(warnMsg));
}
}
//-------------------------------------------------------------------------------------------
static void addMemberSpecialization(const Entry *root,
MemberName *mn,
ClassDefMutable *cd,
const QCString &funcType,
const QCString &funcName,
const QCString &funcArgs,
const QCString &funcDecl,
const QCString &exceptions,
TypeSpecifier spec
)
{
AUTO_TRACE("funcType={} funcName={} funcArgs={} funcDecl={} spec={}",funcType,funcName,funcArgs,funcDecl,spec);
MemberDef *declMd=nullptr;
for (const auto &md : *mn)
{
if (md->getClassDef()==cd)
{
// TODO: we should probably also check for matching arguments
declMd = md.get();
break;
}
}
MemberType mtype=MemberType::Function;
ArgumentList tArgList;
// getTemplateArgumentsFromName(cd->name()+"::"+funcName,root->tArgLists);
auto md = createMemberDef(
root->fileName,root->startLine,root->startColumn,
funcType,funcName,funcArgs,exceptions,
declMd ? declMd->protection() : root->protection,
root->virt,root->isStatic,Relationship::Member,
mtype,tArgList,root->argList,root->metaData);
auto mmd = toMemberDefMutable(md.get());
//printf("new specialized member %s args='%s'\n",qPrint(md->name()),qPrint(funcArgs));
mmd->setTagInfo(root->tagInfo());
mmd->setLanguage(root->lang);
mmd->setId(root->id);
mmd->setMemberClass(cd);
mmd->setTemplateSpecialization(TRUE);
mmd->setTypeConstraints(root->typeConstr);
mmd->setDefinition(funcDecl);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setDocsForDefinition(!root->proto);
mmd->setPrototype(root->proto,root->fileName,root->startLine,root->startColumn);
mmd->addSectionsToDefinition(root->anchors);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
FileDef *fd=root->fileDef();
mmd->setBodyDef(fd);
mmd->setMemberSpecifiers(spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setMemberGroupId(root->mGrpId);
cd->insertMember(md.get());
mmd->setRefItems(root->sli);
mn->push_back(std::move(md));
}
//-------------------------------------------------------------------------------------------
static void addOverloaded(const Entry *root,MemberName *mn,
const QCString &funcType,const QCString &funcName,const QCString &funcArgs,
const QCString &funcDecl,const QCString &exceptions,TypeSpecifier spec)
{
// for unique overloaded member we allow the class to be
// omitted, this is to be Qt compatible. Using this should
// however be avoided, because it is error prone
bool sameClass=false;
if (mn->size()>0)
{
// check if all members with the same name are also in the same class
sameClass = std::equal(mn->begin()+1,mn->end(),mn->begin(),
[](const auto &md1,const auto &md2)
{ return md1->getClassDef()->name()==md2->getClassDef()->name(); });
}
if (sameClass)
{
MemberDefMutable *mdm = toMemberDefMutable(mn->front().get());
ClassDefMutable *cd = mdm ? mdm->getClassDefMutable() : nullptr;
if (cd==nullptr) return;
MemberType mtype = MemberType::Function;
if (root->mtype==MethodTypes::Signal) mtype=MemberType::Signal;
else if (root->mtype==MethodTypes::Slot) mtype=MemberType::Slot;
else if (root->mtype==MethodTypes::DCOP) mtype=MemberType::DCOP;
// new overloaded member function
std::unique_ptr<ArgumentList> tArgList =
getTemplateArgumentsFromName(cd->name()+"::"+funcName,root->tArgLists);
//printf("new related member %s args='%s'\n",qPrint(md->name()),qPrint(funcArgs));
auto md = createMemberDef(
root->fileName,root->startLine,root->startColumn,
funcType,funcName,funcArgs,exceptions,
root->protection,root->virt,root->isStatic,Relationship::Related,
mtype,tArgList ? *tArgList : ArgumentList(),root->argList,root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setLanguage(root->lang);
mmd->setId(root->id);
mmd->setTypeConstraints(root->typeConstr);
mmd->setMemberClass(cd);
mmd->setDefinition(funcDecl);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
QCString doc=getOverloadDocs();
doc+="<p>";
doc+=root->doc;
mmd->setDocumentation(doc,root->docFile,root->docLine);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setDocsForDefinition(!root->proto);
mmd->setPrototype(root->proto,root->fileName,root->startLine,root->startColumn);
mmd->addSectionsToDefinition(root->anchors);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
FileDef *fd=root->fileDef();
mmd->setBodyDef(fd);
mmd->setMemberSpecifiers(spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setMemberGroupId(root->mGrpId);
cd->insertMember(md.get());
cd->insertUsedFile(fd);
mmd->setRefItems(root->sli);
mn->push_back(std::move(md));
}
}
static void insertMemberAlias(Definition *outerScope,const MemberDef *md)
{
if (outerScope && outerScope!=Doxygen::globalScope)
{
auto aliasMd = createMemberDefAlias(outerScope,md);
if (outerScope->definitionType()==Definition::TypeClass)
{
ClassDefMutable *cdm = toClassDefMutable(outerScope);
if (cdm)
{
cdm->insertMember(aliasMd.get());
}
}
else if (outerScope->definitionType()==Definition::TypeNamespace)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(outerScope);
if (ndm)
{
ndm->insertMember(aliasMd.get());
}
}
else if (outerScope->definitionType()==Definition::TypeFile)
{
toFileDef(outerScope)->insertMember(aliasMd.get());
}
if (aliasMd)
{
Doxygen::functionNameLinkedMap->add(md->name())->push_back(std::move(aliasMd));
}
}
}
//-------------------------------------------------------------------------------------------
/*! This function tries to find a member (in a documented class/file/namespace)
* that corresponds to the function/variable declaration given in \a funcDecl.
*
* The boolean \a overloaded is used to specify whether or not a standard
* overload documentation line should be generated.
*
* The boolean \a isFunc is a hint that indicates that this is a function
* instead of a variable or typedef.
*/
static void findMember(const Entry *root,
const QCString &relates,
const QCString &type,
const QCString &args,
QCString funcDecl,
bool overloaded,
bool isFunc
)
{
AUTO_TRACE("root='{}' funcDecl='{}' related='{}' overload={} isFunc={} mGrpId={} #tArgList={} spec={} lang={}",
root->name, funcDecl, relates, overloaded, isFunc, root->mGrpId, root->tArgLists.size(),
root->spec, root->lang);
QCString scopeName;
QCString className;
QCString namespaceName;
QCString funcType;
QCString funcName;
QCString funcArgs;
QCString funcTempList;
QCString exceptions;
QCString funcSpec;
bool isRelated=false;
bool isMemberOf=false;
bool isFriend=false;
bool done=false;
TypeSpecifier spec = root->spec;
while (!done)
{
done=true;
if (funcDecl.stripPrefix("friend ")) // treat friends as related members
{
isFriend=true;
done=false;
}
if (funcDecl.stripPrefix("inline "))
{
spec.setInline(true);
done=false;
}
if (funcDecl.stripPrefix("explicit "))
{
spec.setExplicit(true);
done=false;
}
if (funcDecl.stripPrefix("mutable "))
{
spec.setMutable(true);
done=false;
}
if (funcDecl.stripPrefix("virtual "))
{
done=false;
}
}
// delete any ; from the function declaration
int sep=0;
while ((sep=funcDecl.find(';'))!=-1)
{
funcDecl=(funcDecl.left(sep)+funcDecl.right(funcDecl.length()-sep-1)).stripWhiteSpace();
}
// make sure the first character is a space to simplify searching.
if (!funcDecl.isEmpty() && funcDecl[0]!=' ') funcDecl.prepend(" ");
// remove some superfluous spaces
funcDecl= substitute(
substitute(
substitute(funcDecl,"~ ","~"),
":: ","::"
),
" ::","::"
).stripWhiteSpace();
//printf("funcDecl='%s'\n",qPrint(funcDecl));
if (isFriend && funcDecl.startsWith("class "))
{
//printf("friend class\n");
funcDecl=funcDecl.right(funcDecl.length()-6);
funcName = funcDecl;
}
else if (isFriend && funcDecl.startsWith("struct "))
{
funcDecl=funcDecl.right(funcDecl.length()-7);
funcName = funcDecl;
}
else
{
// extract information from the declarations
parseFuncDecl(funcDecl,root->lang,scopeName,funcType,funcName,
funcArgs,funcTempList,exceptions
);
}
// the class name can also be a namespace name, we decide this later.
// if a related class name is specified and the class name could
// not be derived from the function declaration, then use the
// related field.
AUTO_TRACE_ADD("scopeName='{}' className='{}' namespaceName='{}' funcType='{}' funcName='{}' funcArgs='{}'",
scopeName,className,namespaceName,funcType,funcName,funcArgs);
if (!relates.isEmpty())
{ // related member, prefix user specified scope
isRelated=TRUE;
isMemberOf=(root->relatesType == RelatesType::MemberOf);
if (getClass(relates)==nullptr && !scopeName.isEmpty())
{
scopeName= mergeScopes(scopeName,relates);
}
else
{
scopeName = relates;
}
}
if (relates.isEmpty() && root->parent() &&
(root->parent()->section.isScope() || root->parent()->section.isObjcImpl()) &&
!root->parent()->name.isEmpty()) // see if we can combine scopeName
// with the scope in which it was found
{
QCString joinedName = root->parent()->name+"::"+scopeName;
if (!scopeName.isEmpty() &&
(getClass(joinedName) || Doxygen::namespaceLinkedMap->find(joinedName)))
{
scopeName = joinedName;
}
else
{
scopeName = mergeScopes(root->parent()->name,scopeName);
}
}
else // see if we can prefix a namespace or class that is used from the file
{
FileDef *fd=root->fileDef();
if (fd)
{
for (const auto &fnd : fd->getUsedNamespaces())
{
QCString joinedName = fnd->name()+"::"+scopeName;
if (Doxygen::namespaceLinkedMap->find(joinedName))
{
scopeName=joinedName;
break;
}
}
}
}
scopeName=stripTemplateSpecifiersFromScope(
removeRedundantWhiteSpace(scopeName),false,&funcSpec,QCString(),false);
// funcSpec contains the last template specifiers of the given scope.
// If this method does not have any template arguments or they are
// empty while funcSpec is not empty we assume this is a
// specialization of a method. If not, we clear the funcSpec and treat
// this as a normal method of a template class.
if (!(root->tArgLists.size()>0 &&
root->tArgLists.front().size()==0
)
)
{
funcSpec.clear();
}
//namespaceName=removeAnonymousScopes(namespaceName);
if (!Config_getBool(EXTRACT_ANON_NSPACES) && scopeName.find('@')!=-1) return; // skip stuff in anonymous namespace...
// split scope into a namespace and a class part
extractNamespaceName(scopeName,className,namespaceName,TRUE);
AUTO_TRACE_ADD("scopeName='{}' className='{}' namespaceName='{}'",scopeName,className,namespaceName);
//printf("namespaceName='%s' className='%s'\n",qPrint(namespaceName),qPrint(className));
// merge class and namespace scopes again
scopeName.clear();
if (!namespaceName.isEmpty())
{
if (className.isEmpty())
{
scopeName=namespaceName;
}
else if (!relates.isEmpty() || // relates command with explicit scope
!getClass(className)) // class name only exists in a namespace
{
scopeName=namespaceName+"::"+className;
}
else
{
scopeName=className;
}
}
else if (!className.isEmpty())
{
scopeName=className;
}
//printf("new scope='%s'\n",qPrint(scopeName));
QCString tempScopeName=scopeName;
ClassDefMutable *cd=getClassMutable(scopeName);
if (cd)
{
if (funcSpec.isEmpty())
{
uint32_t argListIndex=0;
tempScopeName=cd->qualifiedNameWithTemplateParameters(&root->tArgLists,&argListIndex);
}
else
{
tempScopeName=scopeName+funcSpec;
}
}
//printf("scopeName=%s cd=%p root->tArgLists=%p result=%s\n",
// qPrint(scopeName),cd,root->tArgLists,qPrint(tempScopeName));
//printf("scopeName='%s' className='%s'\n",qPrint(scopeName),qPrint(className));
// rebuild the function declaration (needed to get the scope right).
if (!scopeName.isEmpty() && !isRelated && !isFriend && !Config_getBool(HIDE_SCOPE_NAMES))
{
if (!funcType.isEmpty())
{
if (isFunc) // a function -> we use argList for the arguments
{
funcDecl=funcType+" "+tempScopeName+"::"+funcName+funcTempList;
}
else
{
funcDecl=funcType+" "+tempScopeName+"::"+funcName+funcArgs;
}
}
else
{
if (isFunc) // a function => we use argList for the arguments
{
funcDecl=tempScopeName+"::"+funcName+funcTempList;
}
else // variable => add 'argument' list
{
funcDecl=tempScopeName+"::"+funcName+funcArgs;
}
}
}
else // build declaration without scope
{
if (!funcType.isEmpty()) // but with a type
{
if (isFunc) // function => omit argument list
{
funcDecl=funcType+" "+funcName+funcTempList;
}
else // variable => add 'argument' list
{
funcDecl=funcType+" "+funcName+funcArgs;
}
}
else // no type
{
if (isFunc)
{
funcDecl=funcName+funcTempList;
}
else
{
funcDecl=funcName+funcArgs;
}
}
}
if (funcType=="template class" && !funcTempList.isEmpty())
return; // ignore explicit template instantiations
AUTO_TRACE_ADD("Parse results: namespaceName='{}' className=`{}` funcType='{}' funcSpec='{}' "
" funcName='{}' funcArgs='{}' funcTempList='{}' funcDecl='{}' relates='{}'"
" exceptions='{}' isRelated={} isMemberOf={} isFriend={} isFunc={}",
namespaceName, className, funcType, funcSpec,
funcName, funcArgs, funcTempList, funcDecl, relates,
exceptions, isRelated, isMemberOf, isFriend, isFunc);
if (!funcName.isEmpty()) // function name is valid
{
// check if 'className' is actually a scoped enum, in which case we need to
// process it as a global, see issue #6471
bool strongEnum = false;
MemberName *mn=nullptr;
if (!className.isEmpty() && (mn=Doxygen::functionNameLinkedMap->find(className)))
{
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
Definition *mdScope = nullptr;
if (md && md->isEnumerate() && md->isStrong() && (mdScope=md->getOuterScope()) &&
// need filter for the correct scope, see issue #9668
((namespaceName.isEmpty() && mdScope==Doxygen::globalScope) || (mdScope->name()==namespaceName)))
{
AUTO_TRACE_ADD("'{}' is a strong enum! (namespace={} md->getOuterScope()->name()={})",md->name(),namespaceName,md->getOuterScope()->name());
strongEnum = true;
// pass the scope name name as a 'namespace' to the findGlobalMember function
if (!namespaceName.isEmpty())
{
namespaceName+="::"+className;
}
else
{
namespaceName=className;
}
}
}
}
if (funcName.startsWith("operator ")) // strip class scope from cast operator
{
funcName = substitute(funcName,className+"::","");
}
mn = nullptr;
if (!funcTempList.isEmpty()) // try with member specialization
{
mn=Doxygen::memberNameLinkedMap->find(funcName+funcTempList);
}
if (mn==nullptr) // try without specialization
{
mn=Doxygen::memberNameLinkedMap->find(funcName);
}
if (!isRelated && !strongEnum && mn) // function name already found
{
AUTO_TRACE_ADD("member name exists ({} members with this name)",mn->size());
if (!className.isEmpty()) // class name is valid
{
if (funcSpec.isEmpty()) // not a member specialization
{
addMemberFunction(root,mn,scopeName,namespaceName,className,funcType,funcName,
funcArgs,funcTempList,exceptions,
type,args,isFriend,spec,relates,funcDecl,overloaded,isFunc);
}
else if (cd) // member specialization
{
addMemberSpecialization(root,mn,cd,funcType,funcName,funcArgs,funcDecl,exceptions,spec);
}
else
{
//printf("*** Specialized member %s of unknown scope %s%s found!\n",
// qPrint(scopeName),qPrint(funcName),qPrint(funcArgs));
}
}
else if (overloaded) // check if the function belongs to only one class
{
addOverloaded(root,mn,funcType,funcName,funcArgs,funcDecl,exceptions,spec);
}
else // unrelated function with the same name as a member
{
if (!findGlobalMember(root,namespaceName,funcType,funcName,funcTempList,funcArgs,funcDecl,spec))
{
QCString fullFuncDecl=funcDecl;
if (isFunc) fullFuncDecl+=argListToString(root->argList,TRUE);
warn(root->fileName,root->startLine,
"Cannot determine class for function\n%s",
qPrint(fullFuncDecl)
);
}
}
}
else if (isRelated && !relates.isEmpty())
{
AUTO_TRACE_ADD("related function scopeName='{}' className='{}'",scopeName,className);
if (className.isEmpty()) className=relates;
//printf("scopeName='%s' className='%s'\n",qPrint(scopeName),qPrint(className));
if ((cd=getClassMutable(scopeName)))
{
bool newMember=TRUE; // assume we have a new member
MemberDefMutable *mdDefine=nullptr;
{
mn = Doxygen::functionNameLinkedMap->find(funcName);
if (mn)
{
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md && md->isDefine())
{
mdDefine = md;
break;
}
}
}
}
if (mdDefine) // macro definition is already created by the preprocessor and inserted as a file member
{
//printf("moving #define %s into class %s\n",qPrint(mdDefine->name()),qPrint(cd->name()));
// take mdDefine from the Doxygen::functionNameLinkedMap (without deleting the data)
auto mdDefineTaken = Doxygen::functionNameLinkedMap->take(funcName,mdDefine);
// insert it as a class member
if ((mn=Doxygen::memberNameLinkedMap->find(funcName))==nullptr)
{
mn=Doxygen::memberNameLinkedMap->add(funcName);
}
if (mdDefine->getFileDef())
{
mdDefine->getFileDef()->removeMember(mdDefine);
}
mdDefine->makeRelated();
mdDefine->setMemberClass(cd);
mdDefine->moveTo(cd);
cd->insertMember(mdDefine);
// also insert the member as an alias in the parent's scope, so it can be referenced also without cd's scope
insertMemberAlias(cd->getOuterScope(),mdDefine);
mn->push_back(std::move(mdDefineTaken));
}
else // normal member, needs to be created and added to the class
{
FileDef *fd=root->fileDef();
if ((mn=Doxygen::memberNameLinkedMap->find(funcName))==nullptr)
{
mn=Doxygen::memberNameLinkedMap->add(funcName);
}
else
{
// see if we got another member with matching arguments
MemberDefMutable *rmd_found = nullptr;
for (const auto &irmd : *mn)
{
MemberDefMutable *rmd = toMemberDefMutable(irmd.get());
if (rmd)
{
const ArgumentList &rmdAl = rmd->argumentList();
newMember=
className!=rmd->getOuterScope()->name() ||
!matchArguments2(rmd->getOuterScope(),rmd->getFileDef(),&rmdAl,
cd,fd,&root->argList,
TRUE,root->lang);
if (!newMember)
{
rmd_found = rmd;
}
}
}
if (rmd_found) // member already exists as rmd -> add docs
{
AUTO_TRACE_ADD("addMemberDocs for related member {}",root->name);
addMemberDocs(root,rmd_found,funcDecl,nullptr,overloaded,spec);
newMember=false;
}
}
if (newMember) // need to create a new member
{
MemberType mtype = MemberType::Function;
switch (root->mtype)
{
case MethodTypes::Method: mtype = MemberType::Function; break;
case MethodTypes::Signal: mtype = MemberType::Signal; break;
case MethodTypes::Slot: mtype = MemberType::Slot; break;
case MethodTypes::DCOP: mtype = MemberType::DCOP; break;
case MethodTypes::Property: mtype = MemberType::Property; break;
case MethodTypes::Event: mtype = MemberType::Event; break;
}
//printf("New related name '%s' '%d'\n",qPrint(funcName),
// root->argList ? (int)root->argList->count() : -1);
// first note that we pass:
// (root->tArgLists ? root->tArgLists->last() : nullptr)
// for the template arguments for the new "member."
// this accurately reflects the template arguments of
// the related function, which don't have to do with
// those of the related class.
auto md = createMemberDef(
root->fileName,root->startLine,root->startColumn,
funcType,funcName,funcArgs,exceptions,
root->protection,root->virt,
root->isStatic,
isMemberOf ? Relationship::Foreign : Relationship::Related,
mtype,
(!root->tArgLists.empty() ? root->tArgLists.back() : ArgumentList()),
funcArgs.isEmpty() ? ArgumentList() : root->argList,
root->metaData);
auto mmd = toMemberDefMutable(md.get());
// also insert the member as an alias in the parent's scope, so it can be referenced also without cd's scope
insertMemberAlias(cd->getOuterScope(),md.get());
// we still have the problem that
// MemberDef::writeDocumentation() in memberdef.cpp
// writes the template argument list for the class,
// as if this member is a member of the class.
// fortunately, MemberDef::writeDocumentation() has
// a special mechanism that allows us to totally
// override the set of template argument lists that
// are printed. We use that and set it to the
// template argument lists of the related function.
//
mmd->setDefinitionTemplateParameterLists(root->tArgLists);
mmd->setTagInfo(root->tagInfo());
//printf("Related member name='%s' decl='%s' bodyLine='%d'\n",
// qPrint(funcName),qPrint(funcDecl),root->bodyLine);
// try to find the matching line number of the body from the
// global function list
bool found=FALSE;
if (root->bodyLine==-1)
{
MemberName *rmn=Doxygen::functionNameLinkedMap->find(funcName);
if (rmn)
{
const MemberDefMutable *rmd_found=nullptr;
for (const auto &irmd : *rmn)
{
MemberDefMutable *rmd = toMemberDefMutable(irmd.get());
if (rmd)
{
const ArgumentList &rmdAl = rmd->argumentList();
// check for matching argument lists
if (
matchArguments2(rmd->getOuterScope(),rmd->getFileDef(),&rmdAl,
cd,fd,&root->argList,
TRUE,root->lang)
)
{
found=TRUE;
rmd_found = rmd;
break;
}
}
}
if (rmd_found) // member found -> copy line number info
{
mmd->setBodySegment(rmd_found->getDefLine(),rmd_found->getStartBodyLine(),rmd_found->getEndBodyLine());
mmd->setBodyDef(rmd_found->getBodyDef());
//md->setBodyMember(rmd);
}
}
}
if (!found) // line number could not be found or is available in this
// entry
{
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
mmd->setBodyDef(fd);
}
//if (root->mGrpId!=-1)
//{
// md->setMemberGroup(memberGroupDict[root->mGrpId]);
//}
mmd->setMemberClass(cd);
mmd->setMemberSpecifiers(spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setDefinition(funcDecl);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
mmd->setDocsForDefinition(!root->proto);
mmd->setPrototype(root->proto,root->fileName,root->startLine,root->startColumn);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->addSectionsToDefinition(root->anchors);
mmd->setMemberGroupId(root->mGrpId);
mmd->setLanguage(root->lang);
mmd->setId(root->id);
//md->setMemberDefTemplateArguments(root->mtArgList);
cd->insertMember(md.get());
cd->insertUsedFile(fd);
mmd->setRefItems(root->sli);
if (root->relatesType==RelatesType::Duplicate) mmd->setRelatedAlso(cd);
addMemberToGroups(root,md.get());
ModuleManager::instance().addMemberToModule(root,md.get());
//printf("Adding member=%s\n",qPrint(md->name()));
mn->push_back(std::move(md));
}
if (root->relatesType==RelatesType::Duplicate)
{
if (!findGlobalMember(root,namespaceName,funcType,funcName,funcTempList,funcArgs,funcDecl,spec))
{
QCString fullFuncDecl=funcDecl;
if (isFunc) fullFuncDecl+=argListToString(root->argList,TRUE);
warn(root->fileName,root->startLine,
"Cannot determine file/namespace for relatedalso function\n%s",
qPrint(fullFuncDecl)
);
}
}
}
}
else
{
warn_undoc(root->fileName,root->startLine,
"class '%s' for related function '%s' is not "
"documented.",
qPrint(className),qPrint(funcName)
);
}
}
else if (root->parent() && root->parent()->section.isObjcImpl())
{
addLocalObjCMethod(root,scopeName,funcType,funcName,funcArgs,exceptions,funcDecl,spec);
}
else // unrelated not overloaded member found
{
bool globMem = findGlobalMember(root,namespaceName,funcType,funcName,funcTempList,funcArgs,funcDecl,spec);
if (className.isEmpty() && !globMem)
{
warn(root->fileName,root->startLine,
"class for member '%s' cannot "
"be found.", qPrint(funcName)
);
}
else if (!className.isEmpty() && !globMem)
{
warn(root->fileName,root->startLine,
"member '%s' of class '%s' cannot be found",
qPrint(funcName),qPrint(className));
}
}
}
else
{
// this should not be called
warn(root->fileName,root->startLine,
"member with no name found.");
}
return;
}
//----------------------------------------------------------------------
// find the members corresponding to the different documentation blocks
// that are extracted from the sources.
static void filterMemberDocumentation(const Entry *root,const QCString &relates)
{
AUTO_TRACE("root->type='{}' root->inside='{}' root->name='{}' root->args='{}' section={} root->spec={} root->mGrpId={}",
root->type,root->inside,root->name,root->args,root->section,root->spec,root->mGrpId);
//printf("root->parent()->name=%s\n",qPrint(root->parent()->name));
bool isFunc=TRUE;
QCString type = root->type;
QCString args = root->args;
int i=-1, l=0;
if ( // detect func variable/typedef to func ptr
(i=findFunctionPtr(type.str(),root->lang,&l))!=-1
)
{
//printf("Fixing function pointer!\n");
// fix type and argument
args.prepend(type.right(type.length()-i-l));
type=type.left(i+l);
//printf("Results type=%s,name=%s,args=%s\n",qPrint(type),qPrint(root->name),qPrint(args));
isFunc=FALSE;
}
else if ((type.startsWith("typedef ") && args.find('(')!=-1))
// detect function types marked as functions
{
isFunc=FALSE;
}
//printf("Member %s isFunc=%d\n",qPrint(root->name),isFunc);
if (root->section.isMemberDoc())
{
//printf("Documentation for inline member '%s' found args='%s'\n",
// qPrint(root->name),qPrint(args));
//if (relates.length()) printf(" Relates %s\n",qPrint(relates));
if (type.isEmpty())
{
findMember(root,
relates,
type,
args,
root->name + args + root->exception,
FALSE,
isFunc);
}
else
{
findMember(root,
relates,
type,
args,
type + " " + root->name + args + root->exception,
FALSE,
isFunc);
}
}
else if (root->section.isOverloadDoc())
{
//printf("Overloaded member %s found\n",qPrint(root->name));
findMember(root,
relates,
type,
args,
root->name,
TRUE,
isFunc);
}
else if
((root->section.isFunction() // function
||
(root->section.isVariable() && // variable
!type.isEmpty() && // with a type
g_compoundKeywords.find(type.str())==g_compoundKeywords.end() // that is not a keyword
// (to skip forward declaration of class etc.)
)
)
)
{
//printf("Documentation for member '%s' found args='%s' excp='%s'\n",
// qPrint(root->name),qPrint(args),qPrint(root->exception));
//if (relates.length()) printf(" Relates %s\n",qPrint(relates));
//printf("Inside=%s\n Relates=%s\n",qPrint(root->inside),qPrint(relates));
if (type=="friend class" || type=="friend struct" ||
type=="friend union")
{
findMember(root,
relates,
type,
args,
type+" "+root->name,
FALSE,FALSE);
}
else if (!type.isEmpty())
{
findMember(root,
relates,
type,
args,
type+" "+ root->inside + root->name + args + root->exception,
FALSE,isFunc);
}
else
{
findMember(root,
relates,
type,
args,
root->inside + root->name + args + root->exception,
FALSE,isFunc);
}
}
else if (root->section.isDefine() && !relates.isEmpty())
{
findMember(root,
relates,
type,
args,
root->name + args,
FALSE,
!args.isEmpty());
}
else if (root->section.isVariableDoc())
{
//printf("Documentation for variable %s found\n",qPrint(root->name));
//if (!relates.isEmpty()) printf(" Relates %s\n",qPrint(relates));
findMember(root,
relates,
type,
args,
root->name,
FALSE,
FALSE);
}
else if (root->section.isExportedInterface() ||
root->section.isIncludedService())
{
findMember(root,
relates,
type,
args,
type + " " + root->name,
FALSE,
FALSE);
}
else
{
// skip section
//printf("skip section\n");
}
}
static void findMemberDocumentation(const Entry *root)
{
if (root->section.isMemberDoc() ||
root->section.isOverloadDoc() ||
root->section.isFunction() ||
root->section.isVariable() ||
root->section.isVariableDoc() ||
root->section.isDefine() ||
root->section.isIncludedService() ||
root->section.isExportedInterface()
)
{
AUTO_TRACE();
if (root->relatesType==RelatesType::Duplicate && !root->relates.isEmpty())
{
filterMemberDocumentation(root,"");
}
filterMemberDocumentation(root,root->relates);
}
for (const auto &e : root->children())
{
if (!e->section.isEnum())
{
findMemberDocumentation(e.get());
}
}
}
//----------------------------------------------------------------------
static void findObjCMethodDefinitions(const Entry *root)
{
AUTO_TRACE();
for (const auto &objCImpl : root->children())
{
if (objCImpl->section.isObjcImpl())
{
for (const auto &objCMethod : objCImpl->children())
{
if (objCMethod->section.isFunction())
{
//Printf(" Found ObjC method definition %s\n",qPrint(objCMethod->name));
findMember(objCMethod.get(),
objCMethod->relates,
objCMethod->type,
objCMethod->args,
objCMethod->type+" "+objCImpl->name+"::"+objCMethod->name+" "+objCMethod->args,
FALSE,TRUE);
objCMethod->section=EntryType::makeEmpty();
}
}
}
}
}
//----------------------------------------------------------------------
// find and add the enumeration to their classes, namespaces or files
static void findEnums(const Entry *root)
{
if (root->section.isEnum())
{
AUTO_TRACE("name={}",root->name);
ClassDefMutable *cd = nullptr;
FileDef *fd = nullptr;
NamespaceDefMutable *nd = nullptr;
MemberNameLinkedMap *mnsd = nullptr;
bool isGlobal = false;
bool isRelated = false;
bool isMemberOf = false;
//printf("Found enum with name '%s' relates=%s\n",qPrint(root->name),qPrint(root->relates));
QCString name;
QCString scope;
int i = root->name.findRev("::");
if (i!=-1) // scope is specified
{
scope=root->name.left(i); // extract scope
name=root->name.right(root->name.length()-i-2); // extract name
if ((cd=getClassMutable(scope))==nullptr)
{
nd=toNamespaceDefMutable(buildScopeFromQualifiedName(root->name.left(i+2),root->lang,root->tagInfo()));
}
}
else // no scope, check the scope in which the docs where found
{
if (root->parent()->section.isScope() && !root->parent()->name.isEmpty()) // found enum docs inside a compound
{
scope=root->parent()->name;
if ((cd=getClassMutable(scope))==nullptr) nd=getResolvedNamespaceMutable(scope);
}
name=root->name;
}
if (!root->relates.isEmpty())
{ // related member, prefix user specified scope
isRelated=TRUE;
isMemberOf=(root->relatesType==RelatesType::MemberOf);
if (getClass(root->relates)==nullptr && !scope.isEmpty())
scope=mergeScopes(scope,root->relates);
else
scope=root->relates;
if ((cd=getClassMutable(scope))==nullptr) nd=getResolvedNamespaceMutable(scope);
}
if (cd && !name.isEmpty()) // found a enum inside a compound
{
//printf("Enum '%s'::'%s'\n",qPrint(cd->name()),qPrint(name));
fd=nullptr;
mnsd=Doxygen::memberNameLinkedMap;
isGlobal=false;
}
else if (nd) // found enum inside namespace
{
mnsd=Doxygen::functionNameLinkedMap;
isGlobal=true;
}
else // found a global enum
{
fd=root->fileDef();
mnsd=Doxygen::functionNameLinkedMap;
isGlobal=true;
}
if (!name.isEmpty())
{
// new enum type
AUTO_TRACE_ADD("new enum {} at line {} of {}",name,root->bodyLine,root->fileName);
auto md = createMemberDef(
root->fileName,root->startLine,root->startColumn,
QCString(),name,QCString(),QCString(),
root->protection,Specifier::Normal,FALSE,
isMemberOf ? Relationship::Foreign : isRelated ? Relationship::Related : Relationship::Member,
MemberType::Enumeration,
ArgumentList(),ArgumentList(),root->metaData);
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setLanguage(root->lang);
mmd->setId(root->id);
if (!isGlobal) mmd->setMemberClass(cd); else mmd->setFileDef(fd);
mmd->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
mmd->setBodyDef(root->fileDef());
mmd->setMemberSpecifiers(root->spec);
mmd->setVhdlSpecifiers(root->vhdlSpec);
mmd->setEnumBaseType(root->args);
//printf("Enum %s definition at line %d of %s: protection=%d scope=%s\n",
// qPrint(root->name),root->bodyLine,qPrint(root->fileName),root->protection,cd?qPrint(cd->name()):"<none>");
mmd->addSectionsToDefinition(root->anchors);
mmd->setMemberGroupId(root->mGrpId);
applyMemberOverrideOptions(root,mmd);
mmd->addQualifiers(root->qualifiers);
//printf("%s::setRefItems(%zu)\n",qPrint(md->name()),root->sli.size());
mmd->setRefItems(root->sli);
//printf("found enum %s nd=%p\n",qPrint(md->name()),nd);
bool defSet=FALSE;
QCString baseType = root->args;
if (!baseType.isEmpty())
{
baseType.prepend(" : ");
}
if (nd)
{
if (isRelated || Config_getBool(HIDE_SCOPE_NAMES))
{
mmd->setDefinition(name+baseType);
}
else
{
mmd->setDefinition(nd->name()+"::"+name+baseType);
}
//printf("definition=%s\n",md->definition());
defSet=TRUE;
mmd->setNamespace(nd);
nd->insertMember(md.get());
}
// even if we have already added the enum to a namespace, we still
// also want to add it to other appropriate places such as file
// or class.
if (isGlobal && (nd==nullptr || !nd->isAnonymous()))
{
if (!defSet) mmd->setDefinition(name+baseType);
if (fd==nullptr && root->parent())
{
fd=root->parent()->fileDef();
}
if (fd)
{
mmd->setFileDef(fd);
fd->insertMember(md.get());
}
}
else if (cd)
{
if (isRelated || Config_getBool(HIDE_SCOPE_NAMES))
{
mmd->setDefinition(name+baseType);
}
else
{
mmd->setDefinition(cd->name()+"::"+name+baseType);
}
cd->insertMember(md.get());
cd->insertUsedFile(fd);
}
mmd->setDocumentation(root->doc,root->docFile,root->docLine);
mmd->setDocsForDefinition(!root->proto);
mmd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mmd->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
//printf("Adding member=%s\n",qPrint(md->name()));
addMemberToGroups(root,md.get());
ModuleManager::instance().addMemberToModule(root,md.get());
MemberName *mn = mnsd->add(name);
mn->push_back(std::move(md));
}
}
else
{
for (const auto &e : root->children()) findEnums(e.get());
}
}
//----------------------------------------------------------------------
static void addEnumValuesToEnums(const Entry *root)
{
if (root->section.isEnum())
// non anonymous enumeration
{
AUTO_TRACE("name={}",root->name);
ClassDefMutable *cd = nullptr;
FileDef *fd = nullptr;
NamespaceDefMutable *nd = nullptr;
MemberNameLinkedMap *mnsd = nullptr;
bool isGlobal = false;
bool isRelated = false;
//printf("Found enum with name '%s' relates=%s\n",qPrint(root->name),qPrint(root->relates));
QCString name;
QCString scope;
int i = root->name.findRev("::");
if (i!=-1) // scope is specified
{
scope=root->name.left(i); // extract scope
name=root->name.right(root->name.length()-i-2); // extract name
if ((cd=getClassMutable(scope))==nullptr)
{
nd=toNamespaceDefMutable(buildScopeFromQualifiedName(root->name.left(i+2),root->lang,root->tagInfo()));
}
}
else // no scope, check the scope in which the docs where found
{
if (root->parent()->section.isScope() && !root->parent()->name.isEmpty()) // found enum docs inside a compound
{
scope=root->parent()->name;
if ((cd=getClassMutable(scope))==nullptr) nd=getResolvedNamespaceMutable(scope);
}
name=root->name;
}
if (!root->relates.isEmpty())
{ // related member, prefix user specified scope
isRelated=TRUE;
if (getClassMutable(root->relates)==nullptr && !scope.isEmpty())
scope=mergeScopes(scope,root->relates);
else
scope=root->relates;
if ((cd=getClassMutable(scope))==nullptr) nd=getResolvedNamespaceMutable(scope);
}
if (cd && !name.isEmpty()) // found a enum inside a compound
{
//printf("Enum in class '%s'::'%s'\n",qPrint(cd->name()),qPrint(name));
fd=nullptr;
mnsd=Doxygen::memberNameLinkedMap;
isGlobal=false;
}
else if (nd && !nd->isAnonymous()) // found enum inside namespace
{
//printf("Enum in namespace '%s'::'%s'\n",qPrint(nd->name()),qPrint(name));
mnsd=Doxygen::functionNameLinkedMap;
isGlobal=true;
}
else // found a global enum
{
fd=root->fileDef();
//printf("Enum in file '%s': '%s'\n",qPrint(fd->name()),qPrint(name));
mnsd=Doxygen::functionNameLinkedMap;
isGlobal=true;
}
if (!name.isEmpty())
{
//printf("** name=%s\n",qPrint(name));
MemberName *mn = mnsd->find(name); // for all members with this name
if (mn)
{
struct EnumValueInfo
{
EnumValueInfo(const QCString &n,std::unique_ptr<MemberDef> &&md) :
name(n), member(std::move(md)) {}
QCString name;
std::unique_ptr<MemberDef> member;
};
std::vector< EnumValueInfo > extraMembers;
// for each enum in this list
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
// use raw pointer in this loop, since we modify mn and can then invalidate mdp.
if (md && md->isEnumerate() && !root->children().empty())
{
AUTO_TRACE_ADD("enum {} with {} children",md->name(),root->children().size());
for (const auto &e : root->children())
{
SrcLangExt sle = root->lang;
bool isJavaLike = sle==SrcLangExt::CSharp || sle==SrcLangExt::Java || sle==SrcLangExt::XML;
if ( isJavaLike || root->spec.isStrong())
{
// Unlike classic C/C++ enums, for C++11, C# & Java enum
// values are only visible inside the enum scope, so we must create
// them here and only add them to the enum
//printf("md->qualifiedName()=%s e->name=%s tagInfo=%p name=%s\n",
// qPrint(md->qualifiedName()),qPrint(e->name),(void*)e->tagInfo(),qPrint(e->name));
QCString qualifiedName = root->name;
if (isJavaLike)
{
qualifiedName=substitute(qualifiedName,"::",".");
}
if (md->qualifiedName()==qualifiedName) // enum value scope matches that of the enum
{
QCString fileName = e->fileName;
if (fileName.isEmpty() && e->tagInfo())
{
fileName = e->tagInfo()->tagName;
}
AUTO_TRACE_ADD("strong enum value {}",e->name);
auto fmd = createMemberDef(
fileName,e->startLine,e->startColumn,
e->type,e->name,e->args,QCString(),
e->protection, Specifier::Normal,e->isStatic,Relationship::Member,
MemberType::EnumValue,ArgumentList(),ArgumentList(),e->metaData);
auto fmmd = toMemberDefMutable(fmd.get());
NamespaceDef *mnd = md->getNamespaceDef();
if (md->getClassDef())
fmmd->setMemberClass(md->getClassDef());
else if (mnd && (mnd->isLinkable() || mnd->isAnonymous()))
fmmd->setNamespace(mnd);
else if (md->getFileDef())
fmmd->setFileDef(md->getFileDef());
fmmd->setOuterScope(md->getOuterScope());
fmmd->setTagInfo(e->tagInfo());
fmmd->setLanguage(e->lang);
fmmd->setBodySegment(e->startLine,e->bodyLine,e->endBodyLine);
fmmd->setBodyDef(e->fileDef());
fmmd->setId(e->id);
fmmd->setDocumentation(e->doc,e->docFile,e->docLine);
fmmd->setBriefDescription(e->brief,e->briefFile,e->briefLine);
fmmd->addSectionsToDefinition(e->anchors);
std::string init = e->initializer.str();
fmmd->setInitializer(init.c_str());
fmmd->setMaxInitLines(e->initLines);
fmmd->setMemberGroupId(e->mGrpId);
fmmd->setExplicitExternal(e->explicitExternal,fileName,e->startLine,e->startColumn);
fmmd->setRefItems(e->sli);
fmmd->setAnchor();
md->insertEnumField(fmd.get());
fmmd->setEnumScope(md,TRUE);
extraMembers.emplace_back(e->name,std::move(fmd));
}
}
else
{
AUTO_TRACE_ADD("enum value {}",e->name);
//printf("e->name=%s isRelated=%d\n",qPrint(e->name),isRelated);
MemberName *fmn=nullptr;
MemberNameLinkedMap *emnsd = isRelated ? Doxygen::functionNameLinkedMap : mnsd;
if (!e->name.isEmpty() && (fmn=emnsd->find(e->name)))
// get list of members with the same name as the field
{
for (const auto &ifmd : *fmn)
{
MemberDefMutable *fmd = toMemberDefMutable(ifmd.get());
if (fmd && fmd->isEnumValue() && fmd->getOuterScope()==md->getOuterScope()) // in same scope
{
//printf("found enum value with same name %s in scope %s\n",
// qPrint(fmd->name()),qPrint(fmd->getOuterScope()->name()));
if (nd && !nd->isAnonymous())
{
if (!fmd->isStrongEnumValue()) // only non strong enum values can be globally added
{
const NamespaceDef *fnd=fmd->getNamespaceDef();
if (fnd==nd) // enum value is inside a namespace
{
md->insertEnumField(fmd);
fmd->setEnumScope(md);
}
}
}
else if (isGlobal)
{
if (!fmd->isStrongEnumValue()) // only non strong enum values can be globally added
{
const FileDef *ffd=fmd->getFileDef();
if (ffd==fd && ffd==md->getFileDef()) // enum value has file scope
{
md->insertEnumField(fmd);
fmd->setEnumScope(md);
}
}
}
else if (isRelated && cd) // reparent enum value to
// match the enum's scope
{
md->insertEnumField(fmd); // add field def to list
fmd->setEnumScope(md); // cross ref with enum name
fmd->setEnumClassScope(cd); // cross ref with enum name
fmd->setOuterScope(cd);
fmd->makeRelated();
cd->insertMember(fmd);
}
else
{
if (!fmd->isStrongEnumValue()) // only non strong enum values can be globally added
{
const ClassDef *fcd=fmd->getClassDef();
if (fcd==cd) // enum value is inside a class
{
//printf("Inserting enum field %s in enum scope %s\n",
// qPrint(fmd->name()),qPrint(md->name()));
md->insertEnumField(fmd); // add field def to list
fmd->setEnumScope(md); // cross ref with enum name
}
}
}
}
}
}
}
}
}
}
// move the newly added members into mn
for (auto &e : extraMembers)
{
MemberName *emn=mnsd->add(e.name);
emn->push_back(std::move(e.member));
}
}
}
}
else
{
for (const auto &e : root->children()) addEnumValuesToEnums(e.get());
}
}
//----------------------------------------------------------------------
static void addEnumDocs(const Entry *root,MemberDefMutable *md)
{
AUTO_TRACE();
// documentation outside a compound overrides the documentation inside it
{
md->setDocumentation(root->doc,root->docFile,root->docLine);
md->setDocsForDefinition(!root->proto);
}
// brief descriptions inside a compound override the documentation
// outside it
{
md->setBriefDescription(root->brief,root->briefFile,root->briefLine);
}
if (md->inbodyDocumentation().isEmpty() || !root->parent()->name.isEmpty())
{
md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
}
if (root->mGrpId!=-1 && md->getMemberGroupId()==-1)
{
md->setMemberGroupId(root->mGrpId);
}
md->addSectionsToDefinition(root->anchors);
md->setRefItems(root->sli);
const GroupDef *gd=md->getGroupDef();
if (gd==nullptr && !root->groups.empty()) // member not grouped but out-of-line documentation is
{
addMemberToGroups(root,md);
}
ModuleManager::instance().addMemberToModule(root,md);
}
//----------------------------------------------------------------------
// Search for the name in the associated groups. If a matching member
// definition exists, then add the documentation to it and return TRUE,
// otherwise FALSE.
static bool tryAddEnumDocsToGroupMember(const Entry *root,const QCString &name)
{
for (const auto &g : root->groups)
{
const GroupDef *gd = Doxygen::groupLinkedMap->find(g.groupname);
if (gd)
{
MemberList *ml = gd->getMemberList(MemberListType::DecEnumMembers());
if (ml)
{
MemberDefMutable *md = toMemberDefMutable(ml->find(name));
if (md)
{
addEnumDocs(root,md);
return TRUE;
}
}
}
else if (!gd && g.pri == Grouping::GROUPING_INGROUP)
{
warn(root->fileName, root->startLine,
"Found non-existing group '%s' for the command '%s', ignoring command",
qPrint(g.groupname), Grouping::getGroupPriName( g.pri )
);
}
}
return FALSE;
}
//----------------------------------------------------------------------
// find the documentation blocks for the enumerations
static void findEnumDocumentation(const Entry *root)
{
if (root->section.isEnumDoc() &&
!root->name.isEmpty() &&
root->name.at(0)!='@' // skip anonymous enums
)
{
QCString name;
QCString scope;
int i = root->name.findRev("::");
if (i!=-1) // scope is specified as part of the name
{
name=root->name.right(root->name.length()-i-2); // extract name
scope=root->name.left(i); // extract scope
//printf("Scope='%s' Name='%s'\n",qPrint(scope),qPrint(name));
}
else // just the name
{
name=root->name;
}
if (root->parent()->section.isScope() && !root->parent()->name.isEmpty()) // found enum docs inside a compound
{
if (!scope.isEmpty()) scope.prepend("::");
scope.prepend(root->parent()->name);
}
const ClassDef *cd = getClass(scope);
const NamespaceDef *nd=Doxygen::namespaceLinkedMap->find(scope);
const FileDef *fd = root->fileDef();
AUTO_TRACE("Found docs for enum with name '{}' and scope '{}' in context '{}' cd='{}', nd='{}' fd='{}'",
name,scope,root->parent()->name,
cd ? cd->name() : QCString("<none>"),
nd ? nd->name() : QCString("<none>"),
fd ? fd->name() : QCString("<none>"));
if (!name.isEmpty())
{
bool found = tryAddEnumDocsToGroupMember(root, name);
if (!found)
{
MemberName *mn = cd ? Doxygen::memberNameLinkedMap->find(name) : Doxygen::functionNameLinkedMap->find(name);
if (mn)
{
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md && md->isEnumerate())
{
const ClassDef *mcd = md->getClassDef();
const NamespaceDef *mnd = md->getNamespaceDef();
const FileDef *mfd = md->getFileDef();
if (cd && mcd==cd)
{
AUTO_TRACE_ADD("Match found for class scope");
addEnumDocs(root,md);
found = TRUE;
break;
}
else if (cd==nullptr && mcd==nullptr && nd!=nullptr && mnd==nd)
{
AUTO_TRACE_ADD("Match found for namespace scope");
addEnumDocs(root,md);
found = TRUE;
break;
}
else if (cd==nullptr && nd==nullptr && mcd==nullptr && mnd==nullptr && fd==mfd)
{
AUTO_TRACE_ADD("Match found for global scope");
addEnumDocs(root,md);
found = TRUE;
break;
}
}
}
}
}
if (!found)
{
warn(root->fileName,root->startLine,
"Documentation for undefined enum '%s' found.",
qPrint(name)
);
}
}
}
for (const auto &e : root->children()) findEnumDocumentation(e.get());
}
// search for each enum (member or function) in mnl if it has documented
// enum values.
static void findDEV(const MemberNameLinkedMap &mnsd)
{
// for each member name
for (const auto &mn : mnsd)
{
// for each member definition
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md && md->isEnumerate()) // member is an enum
{
int documentedEnumValues=0;
// for each enum value
for (const auto &fmd : md->enumFieldList())
{
if (fmd->isLinkableInProject()) documentedEnumValues++;
}
// at least one enum value is documented
if (documentedEnumValues>0) md->setDocumentedEnumValues(TRUE);
}
}
}
}
// search for each enum (member or function) if it has documented enum
// values.
static void findDocumentedEnumValues()
{
findDEV(*Doxygen::memberNameLinkedMap);
findDEV(*Doxygen::functionNameLinkedMap);
}
//----------------------------------------------------------------------
static void addMembersToIndex()
{
auto &index = Index::instance();
// for each class member name
for (const auto &mn : *Doxygen::memberNameLinkedMap)
{
// for each member definition
for (const auto &md : *mn)
{
index.addClassMemberNameToIndex(md.get());
if (md->getModuleDef())
{
index.addModuleMemberNameToIndex(md.get());
}
}
}
// for each file/namespace function name
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
// for each member definition
for (const auto &md : *mn)
{
if (md->getNamespaceDef())
{
index.addNamespaceMemberNameToIndex(md.get());
}
else
{
index.addFileMemberNameToIndex(md.get());
}
if (md->getModuleDef())
{
index.addModuleMemberNameToIndex(md.get());
}
}
}
index.sortMemberIndexLists();
}
//----------------------------------------------------------------------
static void addToIndices()
{
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkableInProject())
{
Doxygen::indexList->addIndexItem(cd.get(),nullptr);
if (Doxygen::searchIndex.enabled())
{
Doxygen::searchIndex.setCurrentDoc(cd.get(),cd->anchor(),FALSE);
Doxygen::searchIndex.addWord(cd->localName(),TRUE);
}
}
}
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject())
{
Doxygen::indexList->addIndexItem(cd.get(),nullptr);
if (Doxygen::searchIndex.enabled())
{
Doxygen::searchIndex.setCurrentDoc(cd.get(),cd->anchor(),FALSE);
Doxygen::searchIndex.addWord(cd->localName(),TRUE);
}
}
}
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject())
{
Doxygen::indexList->addIndexItem(nd.get(),nullptr);
if (Doxygen::searchIndex.enabled())
{
Doxygen::searchIndex.setCurrentDoc(nd.get(),nd->anchor(),FALSE);
Doxygen::searchIndex.addWord(nd->localName(),TRUE);
}
}
}
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (Doxygen::searchIndex.enabled() && fd->isLinkableInProject())
{
Doxygen::searchIndex.setCurrentDoc(fd.get(),fd->anchor(),FALSE);
Doxygen::searchIndex.addWord(fd->localName(),TRUE);
}
}
}
auto addWordsForTitle = [](const Definition *d,const QCString &anchor,const QCString &title)
{
Doxygen::indexList->addIndexItem(d,nullptr,QCString(),filterTitle(title));
if (Doxygen::searchIndex.enabled())
{
Doxygen::searchIndex.setCurrentDoc(d,anchor,false);
std::string s = title.str();
static const reg::Ex re(R"(\a[\w-]*)");
reg::Iterator it(s,re);
reg::Iterator end;
for (; it!=end ; ++it)
{
const auto &match = *it;
std::string matchStr = match.str();
Doxygen::searchIndex.addWord(matchStr.c_str(),true);
}
}
};
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (gd->isLinkableInProject())
{
addWordsForTitle(gd.get(),gd->anchor(),gd->groupTitle());
}
}
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (pd->isLinkableInProject())
{
addWordsForTitle(pd.get(),pd->anchor(),pd->title());
}
}
if (Doxygen::mainPage)
{
addWordsForTitle(Doxygen::mainPage.get(),Doxygen::mainPage->anchor(),Doxygen::mainPage->title());
}
auto addMemberToSearchIndex = [](const MemberDef *md)
{
if (Doxygen::searchIndex.enabled())
{
Doxygen::searchIndex.setCurrentDoc(md,md->anchor(),FALSE);
QCString ln=md->localName();
QCString qn=md->qualifiedName();
Doxygen::searchIndex.addWord(ln,TRUE);
if (ln!=qn)
{
Doxygen::searchIndex.addWord(qn,TRUE);
if (md->getClassDef())
{
Doxygen::searchIndex.addWord(md->getClassDef()->displayName(),TRUE);
}
if (md->getNamespaceDef())
{
Doxygen::searchIndex.addWord(md->getNamespaceDef()->displayName(),TRUE);
}
}
}
};
auto getScope = [](const MemberDef *md)
{
const Definition *scope = nullptr;
if (md->getGroupDef()) scope = md->getGroupDef();
else if (md->getClassDef()) scope = md->getClassDef();
else if (md->getNamespaceDef()) scope = md->getNamespaceDef();
else if (md->getFileDef()) scope = md->getFileDef();
return scope;
};
auto addMemberToIndices = [addMemberToSearchIndex,getScope](const MemberDef *md)
{
if (md->isLinkableInProject())
{
if (!(md->isEnumerate() && md->isAnonymous()))
{
Doxygen::indexList->addIndexItem(getScope(md),md);
addMemberToSearchIndex(md);
}
if (md->isEnumerate())
{
for (const auto &fmd : md->enumFieldList())
{
Doxygen::indexList->addIndexItem(getScope(fmd),fmd);
addMemberToSearchIndex(fmd);
}
}
}
};
// for each class member name
for (const auto &mn : *Doxygen::memberNameLinkedMap)
{
// for each member definition
for (const auto &md : *mn)
{
addMemberToIndices(md.get());
}
}
// for each file/namespace function name
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
// for each member definition
for (const auto &md : *mn)
{
addMemberToIndices(md.get());
}
}
}
//----------------------------------------------------------------------
static void vhdlCorrectMemberProperties()
{
// for each member name
for (const auto &mn : *Doxygen::memberNameLinkedMap)
{
// for each member definition
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md)
{
VhdlDocGen::correctMemberProperties(md);
}
}
}
// for each member name
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
// for each member definition
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md)
{
VhdlDocGen::correctMemberProperties(md);
}
}
}
}
// recursive helper function looking for reimplements/implemented
// by relations between class cd and direct or indirect base class bcd
static void computeMemberRelationsForBaseClass(const ClassDef *cd,const BaseClassDef *bcd)
{
for (const auto &mn : cd->memberNameInfoLinkedMap()) // for each member in class cd with a unique name
{
for (const auto &imd : *mn) // for each member with a given name
{
MemberDefMutable *md = toMemberDefMutable(imd->memberDef());
if (md && (md->isFunction() || md->isCSharpProperty())) // filter on reimplementable members
{
ClassDef *mbcd = bcd->classDef;
if (mbcd && mbcd->isLinkable()) // filter on linkable classes
{
const auto &bmn = mbcd->memberNameInfoLinkedMap();
const auto &bmni = bmn.find(mn->memberName());
if (bmni) // there are base class members with the same name
{
for (const auto &ibmd : *bmni) // for base class member with that name
{
MemberDefMutable *bmd = toMemberDefMutable(ibmd->memberDef());
if (bmd) // not part of an inline namespace
{
if (bmd->virtualness()!=Specifier::Normal ||
bmd->getLanguage()==SrcLangExt::Python ||
bmd->getLanguage()==SrcLangExt::Java ||
bmd->getLanguage()==SrcLangExt::PHP ||
mbcd->compoundType()==ClassDef::Interface ||
mbcd->compoundType()==ClassDef::Protocol)
{
const ArgumentList &bmdAl = bmd->argumentList();
const ArgumentList &mdAl = md->argumentList();
//printf(" Base argList='%s'\n Super argList='%s'\n",
// qPrint(argListToString(bmdAl)),
// qPrint(argListToString(mdAl))
// );
if (
bmd->getLanguage()==SrcLangExt::Python ||
matchArguments2(bmd->getOuterScope(),bmd->getFileDef(),&bmdAl,
md->getOuterScope(), md->getFileDef(), &mdAl,
TRUE,bmd->getLanguage()
)
)
{
//printf("match!\n");
const MemberDef *rmd = md->reimplements();
if (rmd==nullptr) // not already assigned
{
//printf("%s: setting (new) reimplements member %s\n",qPrint(md->qualifiedName()),qPrint(bmd->qualifiedName()));
md->setReimplements(bmd);
}
//printf("%s: add reimplementedBy member %s\n",qPrint(bmd->qualifiedName()),qPrint(md->qualifiedName()));
bmd->insertReimplementedBy(md);
}
else
{
//printf("no match!\n");
}
}
}
}
}
}
}
}
}
// do also for indirect base classes
for (const auto &bbcd : bcd->classDef->baseClasses())
{
computeMemberRelationsForBaseClass(cd,&bbcd);
}
}
//----------------------------------------------------------------------
// computes the relation between all members. For each member 'm'
// the members that override the implementation of 'm' are searched and
// the member that 'm' overrides is searched.
static void computeMemberRelations()
{
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkable())
{
for (const auto &bcd : cd->baseClasses())
{
computeMemberRelationsForBaseClass(cd.get(),&bcd);
}
}
}
}
//----------------------------------------------------------------------------
static void createTemplateInstanceMembers()
{
// for each class
for (const auto &cd : *Doxygen::classLinkedMap)
{
// that is a template
for (const auto &ti : cd->getTemplateInstances())
{
ClassDefMutable *tcdm = toClassDefMutable(ti.classDef);
if (tcdm)
{
tcdm->addMembersToTemplateInstance(cd.get(),cd->templateArguments(),ti.templSpec);
}
}
}
}
//----------------------------------------------------------------------------
static void mergeCategories()
{
AUTO_TRACE();
// merge members of categories into the class they extend
for (const auto &cd : *Doxygen::classLinkedMap)
{
int i=cd->name().find('(');
if (i!=-1) // it is an Objective-C category
{
QCString baseName=cd->name().left(i);
ClassDefMutable *baseClass=toClassDefMutable(Doxygen::classLinkedMap->find(baseName));
if (baseClass)
{
AUTO_TRACE_ADD("merging members of category {} into {}",cd->name(),baseClass->name());
baseClass->mergeCategory(cd.get());
}
}
}
}
// builds the list of all members for each class
static void buildCompleteMemberLists()
{
// merge the member list of base classes into the inherited classes.
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (// !cd->isReference() && // not an external class
cd->subClasses().empty() && // is a root of the hierarchy
!cd->baseClasses().empty()) // and has at least one base class
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
//printf("*** merging members for %s\n",qPrint(cd->name()));
cdm->mergeMembers();
}
}
}
// now sort the member list of all members for all classes.
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->sortAllMembersList();
}
}
}
//----------------------------------------------------------------------------
static void generateFileSources()
{
auto processSourceFile = [](FileDef *fd,OutputList &ol,ClangTUParser *parser)
{
bool showSources = fd->generateSourceFile() && !Htags::useHtags; // sources need to be shown in the output
bool parseSources = !fd->isReference() && Doxygen::parseSourcesNeeded; // we needed to parse the sources even if we do not show them
if (showSources)
{
msg("Generating code for file %s...\n",qPrint(fd->docName()));
fd->writeSourceHeader(ol);
fd->writeSourceBody(ol,parser);
fd->writeSourceFooter(ol);
}
else if (parseSources)
{
msg("Parsing code for file %s...\n",qPrint(fd->docName()));
fd->parseSource(parser);
}
};
if (!Doxygen::inputNameLinkedMap->empty())
{
#if USE_LIBCLANG
if (Doxygen::clangAssistedParsing)
{
StringUnorderedSet processedFiles;
// create a dictionary with files to process
StringUnorderedSet filesToProcess;
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
filesToProcess.insert(fd->absFilePath().str());
}
}
// process source files (and their include dependencies)
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->isSource() && !fd->isReference() && fd->getLanguage()==SrcLangExt::Cpp &&
(fd->generateSourceFile() ||
(!fd->isReference() && Doxygen::parseSourcesNeeded)
)
)
{
auto clangParser = ClangParser::instance()->createTUParser(fd.get());
clangParser->parse();
processSourceFile(fd.get(),*g_outputList,clangParser.get());
for (auto incFile : clangParser->filesInSameTU())
{
if (filesToProcess.find(incFile)!=filesToProcess.end() && // part of input
fd->absFilePath()!=QCString(incFile) && // not same file
processedFiles.find(incFile)==processedFiles.end()) // not yet marked as processed
{
StringVector moreFiles;
bool ambig = false;
FileDef *ifd=findFileDef(Doxygen::inputNameLinkedMap,incFile.c_str(),ambig);
if (ifd && !ifd->isReference())
{
processSourceFile(ifd,*g_outputList,clangParser.get());
processedFiles.insert(incFile);
}
}
}
processedFiles.insert(fd->absFilePath().str());
}
}
}
// process remaining files
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (processedFiles.find(fd->absFilePath().str())==processedFiles.end()) // not yet processed
{
if (fd->getLanguage()==SrcLangExt::Cpp) // C/C++ file, use clang parser
{
auto clangParser = ClangParser::instance()->createTUParser(fd.get());
clangParser->parse();
processSourceFile(fd.get(),*g_outputList,clangParser.get());
}
else // non C/C++ file, use built-in parser
{
processSourceFile(fd.get(),*g_outputList,nullptr);
}
}
}
}
}
else
#endif
{
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
if (numThreads>1)
{
msg("Generating code files using %zu threads.\n",numThreads);
struct SourceContext
{
SourceContext(FileDef *fd_,bool gen_,const OutputList &ol_)
: fd(fd_), generateSourceFile(gen_), ol(ol_) {}
FileDef *fd;
bool generateSourceFile;
OutputList ol;
};
ThreadPool threadPool(numThreads);
std::vector< std::future< std::shared_ptr<SourceContext> > > results;
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
bool generateSourceFile = fd->generateSourceFile() && !Htags::useHtags;
auto ctx = std::make_shared<SourceContext>(fd.get(),generateSourceFile,*g_outputList);
auto processFile = [ctx]()
{
if (ctx->generateSourceFile)
{
msg("Generating code for file %s...\n",qPrint(ctx->fd->docName()));
}
else
{
msg("Parsing code for file %s...\n",qPrint(ctx->fd->docName()));
}
StringVector filesInSameTu;
ctx->fd->getAllIncludeFilesRecursively(filesInSameTu);
if (ctx->generateSourceFile) // sources need to be shown in the output
{
ctx->fd->writeSourceHeader(ctx->ol);
ctx->fd->writeSourceBody(ctx->ol,nullptr);
ctx->fd->writeSourceFooter(ctx->ol);
}
else if (!ctx->fd->isReference() && Doxygen::parseSourcesNeeded)
// we needed to parse the sources even if we do not show them
{
ctx->fd->parseSource(nullptr);
}
return ctx;
};
results.emplace_back(threadPool.queue(processFile));
}
}
for (auto &f : results)
{
auto ctx = f.get();
}
}
else // single threaded version
{
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
StringVector filesInSameTu;
fd->getAllIncludeFilesRecursively(filesInSameTu);
processSourceFile(fd.get(),*g_outputList,nullptr);
}
}
}
}
}
}
//----------------------------------------------------------------------------
static void generateFileDocs()
{
if (Index::instance().numDocumentedFiles()==0) return;
if (!Doxygen::inputNameLinkedMap->empty())
{
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
if (numThreads>1) // multi threaded processing
{
struct DocContext
{
DocContext(FileDef *fd_,const OutputList &ol_)
: fd(fd_), ol(ol_) {}
FileDef *fd;
OutputList ol;
};
ThreadPool threadPool(numThreads);
std::vector< std::future< std::shared_ptr<DocContext> > > results;
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
bool doc = fd->isLinkableInProject();
if (doc)
{
auto ctx = std::make_shared<DocContext>(fd.get(),*g_outputList);
auto processFile = [ctx]() {
msg("Generating docs for file %s...\n",qPrint(ctx->fd->docName()));
ctx->fd->writeDocumentation(ctx->ol);
return ctx;
};
results.emplace_back(threadPool.queue(processFile));
}
}
}
for (auto &f : results)
{
auto ctx = f.get();
}
}
else // single threaded processing
{
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
bool doc = fd->isLinkableInProject();
if (doc)
{
msg("Generating docs for file %s...\n",qPrint(fd->docName()));
fd->writeDocumentation(*g_outputList);
}
}
}
}
}
}
//----------------------------------------------------------------------------
static void addSourceReferences()
{
// add source references for class definitions
for (const auto &cd : *Doxygen::classLinkedMap)
{
const FileDef *fd=cd->getBodyDef();
if (fd && cd->isLinkableInProject() && cd->getStartDefLine()!=-1)
{
const_cast<FileDef*>(fd)->addSourceRef(cd->getStartDefLine(),cd.get(),nullptr);
}
}
// add source references for concept definitions
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
const FileDef *fd=cd->getBodyDef();
if (fd && cd->isLinkableInProject() && cd->getStartDefLine()!=-1)
{
const_cast<FileDef*>(fd)->addSourceRef(cd->getStartDefLine(),cd.get(),nullptr);
}
}
// add source references for namespace definitions
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
const FileDef *fd=nd->getBodyDef();
if (fd && nd->isLinkableInProject() && nd->getStartDefLine()!=-1)
{
const_cast<FileDef*>(fd)->addSourceRef(nd->getStartDefLine(),nd.get(),nullptr);
}
}
// add source references for member names
for (const auto &mn : *Doxygen::memberNameLinkedMap)
{
for (const auto &md : *mn)
{
//printf("class member %s: def=%s body=%d link?=%d\n",
// qPrint(md->name()),
// md->getBodyDef()?qPrint(md->getBodyDef()->name()):"<none>",
// md->getStartBodyLine(),md->isLinkableInProject());
const FileDef *fd=md->getBodyDef();
if (fd &&
md->getStartDefLine()!=-1 &&
md->isLinkableInProject() &&
(fd->generateSourceFile() || Doxygen::parseSourcesNeeded)
)
{
//printf("Found member '%s' in file '%s' at line '%d' def=%s\n",
// qPrint(md->name()),qPrint(fd->name()),md->getStartBodyLine(),qPrint(md->getOuterScope()->name()));
const_cast<FileDef*>(fd)->addSourceRef(md->getStartDefLine(),md->getOuterScope(),md.get());
}
}
}
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
for (const auto &md : *mn)
{
const FileDef *fd=md->getBodyDef();
//printf("member %s body=[%d,%d] fd=%p link=%d parseSources=%d\n",
// qPrint(md->name()),
// md->getStartBodyLine(),md->getEndBodyLine(),fd,
// md->isLinkableInProject(),
// Doxygen::parseSourcesNeeded);
if (fd &&
md->getStartDefLine()!=-1 &&
md->isLinkableInProject() &&
(fd->generateSourceFile() || Doxygen::parseSourcesNeeded)
)
{
//printf("Found member '%s' in file '%s' at line '%d' def=%s\n",
// qPrint(md->name()),qPrint(fd->name()),md->getStartBodyLine(),qPrint(md->getOuterScope()->name()));
const_cast<FileDef*>(fd)->addSourceRef(md->getStartDefLine(),md->getOuterScope(),md.get());
}
}
}
}
//----------------------------------------------------------------------------
// add the macro definitions found during preprocessing as file members
static void buildDefineList()
{
AUTO_TRACE();
for (const auto &s : g_inputFiles)
{
auto it = Doxygen::macroDefinitions.find(s);
if (it!=Doxygen::macroDefinitions.end())
{
for (const auto &def : it->second)
{
auto md = createMemberDef(
def.fileName,def.lineNr,def.columnNr,
"#define",def.name,def.args,QCString(),
Protection::Public,Specifier::Normal,FALSE,Relationship::Member,MemberType::Define,
ArgumentList(),ArgumentList(),"");
auto mmd = toMemberDefMutable(md.get());
if (!def.args.isEmpty())
{
mmd->moveArgumentList(stringToArgumentList(SrcLangExt::Cpp, def.args));
}
mmd->setInitializer(def.definition);
mmd->setFileDef(def.fileDef);
mmd->setDefinition("#define "+def.name);
MemberName *mn=Doxygen::functionNameLinkedMap->add(def.name);
if (def.fileDef)
{
def.fileDef->insertMember(md.get());
}
AUTO_TRACE_ADD("adding macro {} with definition {}",def.name,def.definition);
mn->push_back(std::move(md));
}
}
}
}
//----------------------------------------------------------------------------
static void sortMemberLists()
{
// sort class member lists
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->sortMemberLists();
}
}
// sort namespace member lists
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->sortMemberLists();
}
}
// sort file member lists
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->sortMemberLists();
}
}
// sort group member lists
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->sortMemberLists();
}
ModuleManager::instance().sortMemberLists();
}
//----------------------------------------------------------------------------
static bool isSymbolHidden(const Definition *d)
{
bool hidden = d->isHidden();
const Definition *parent = d->getOuterScope();
return parent ? hidden || isSymbolHidden(parent) : hidden;
}
static void computeTooltipTexts()
{
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
if (numThreads>1)
{
ThreadPool threadPool(numThreads);
std::vector < std::future< void > > results;
// queue the work
for (const auto &[name,symList] : *Doxygen::symbolMap)
{
for (const auto &def : symList)
{
DefinitionMutable *dm = toDefinitionMutable(def);
if (dm && !isSymbolHidden(def) && !def->isArtificial() && def->isLinkableInProject())
{
auto processTooltip = [dm]() {
dm->computeTooltip();
};
results.emplace_back(threadPool.queue(processTooltip));
}
}
}
// wait for the results
for (auto &f : results)
{
f.get();
}
}
else
{
for (const auto &[name,symList] : *Doxygen::symbolMap)
{
for (const auto &def : symList)
{
DefinitionMutable *dm = toDefinitionMutable(def);
if (dm && !isSymbolHidden(def) && !def->isArtificial() && def->isLinkableInProject())
{
dm->computeTooltip();
}
}
}
}
}
//----------------------------------------------------------------------------
static void setAnonymousEnumType()
{
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->setAnonymousEnumType();
}
}
}
//----------------------------------------------------------------------------
static void countMembers()
{
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->countMembers();
}
}
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->countMembers();
}
}
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->countMembers();
}
}
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->countMembers();
}
auto &mm = ModuleManager::instance();
mm.countMembers();
}
//----------------------------------------------------------------------------
// generate the documentation for all classes
static void generateDocsForClassList(const std::vector<ClassDefMutable*> &classList)
{
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
if (numThreads>1) // multi threaded processing
{
struct DocContext
{
DocContext(ClassDefMutable *cd_,const OutputList &ol_)
: cd(cd_), ol(ol_) {}
ClassDefMutable *cd;
OutputList ol;
};
ThreadPool threadPool(numThreads);
std::vector< std::future< std::shared_ptr<DocContext> > > results;
for (const auto &cd : classList)
{
//printf("cd=%s getOuterScope=%p global=%p\n",qPrint(cd->name()),cd->getOuterScope(),Doxygen::globalScope);
if (cd->getOuterScope()==nullptr || // <-- should not happen, but can if we read an old tag file
cd->getOuterScope()==Doxygen::globalScope // only look at global classes
)
{
auto ctx = std::make_shared<DocContext>(cd,*g_outputList);
auto processFile = [ctx]()
{
msg("Generating docs for compound %s...\n",qPrint(ctx->cd->displayName()));
// skip external references, anonymous compounds and
// template instances
if (!ctx->cd->isHidden() && !ctx->cd->isEmbeddedInOuterScope() &&
ctx->cd->isLinkableInProject() && ctx->cd->templateMaster()==nullptr)
{
ctx->cd->writeDocumentation(ctx->ol);
ctx->cd->writeMemberList(ctx->ol);
}
// even for undocumented classes, the inner classes can be documented.
ctx->cd->writeDocumentationForInnerClasses(ctx->ol);
return ctx;
};
results.emplace_back(threadPool.queue(processFile));
}
}
for (auto &f : results)
{
auto ctx = f.get();
}
}
else // single threaded processing
{
for (const auto &cd : classList)
{
//printf("cd=%s getOuterScope=%p global=%p hidden=%d embeddedInOuterScope=%d\n",
// qPrint(cd->name()),cd->getOuterScope(),Doxygen::globalScope,cd->isHidden(),cd->isEmbeddedInOuterScope());
if (cd->getOuterScope()==nullptr || // <-- should not happen, but can if we read an old tag file
cd->getOuterScope()==Doxygen::globalScope // only look at global classes
)
{
// skip external references, anonymous compounds and
// template instances
if ( !cd->isHidden() && !cd->isEmbeddedInOuterScope() &&
cd->isLinkableInProject() && cd->templateMaster()==nullptr)
{
msg("Generating docs for compound %s...\n",qPrint(cd->displayName()));
cd->writeDocumentation(*g_outputList);
cd->writeMemberList(*g_outputList);
}
// even for undocumented classes, the inner classes can be documented.
cd->writeDocumentationForInnerClasses(*g_outputList);
}
}
}
}
static void addClassAndNestedClasses(std::vector<ClassDefMutable*> &list,ClassDefMutable *cd)
{
list.push_back(cd);
for (const auto &innerCdi : cd->getClasses())
{
ClassDefMutable *innerCd = toClassDefMutable(innerCdi);
if (innerCd && innerCd->isLinkableInProject() && innerCd->templateMaster()==nullptr &&
protectionLevelVisible(innerCd->protection()) &&
!innerCd->isEmbeddedInOuterScope()
)
{
list.push_back(innerCd);
addClassAndNestedClasses(list,innerCd);
}
}
}
static void generateClassDocs()
{
std::vector<ClassDefMutable*> classList;
for (const auto &cdi : *Doxygen::classLinkedMap)
{
ClassDefMutable *cd = toClassDefMutable(cdi.get());
if (cd && (cd->getOuterScope()==nullptr ||
cd->getOuterScope()->definitionType()!=Definition::TypeClass))
{
addClassAndNestedClasses(classList,cd);
}
}
for (const auto &cdi : *Doxygen::hiddenClassLinkedMap)
{
ClassDefMutable *cd = toClassDefMutable(cdi.get());
if (cd && (cd->getOuterScope()==nullptr ||
cd->getOuterScope()->definitionType()!=Definition::TypeClass))
{
addClassAndNestedClasses(classList,cd);
}
}
generateDocsForClassList(classList);
}
//----------------------------------------------------------------------------
static void generateConceptDocs()
{
for (const auto &cdi : *Doxygen::conceptLinkedMap)
{
ConceptDefMutable *cd=toConceptDefMutable(cdi.get());
//printf("cd=%s getOuterScope=%p global=%p\n",qPrint(cd->name()),cd->getOuterScope(),Doxygen::globalScope);
if (cd &&
(cd->getOuterScope()==nullptr || // <-- should not happen, but can if we read an old tag file
cd->getOuterScope()==Doxygen::globalScope // only look at global concepts
) && !cd->isHidden() && cd->isLinkableInProject()
)
{
msg("Generating docs for concept %s...\n",qPrint(cd->displayName()));
cd->writeDocumentation(*g_outputList);
}
}
}
//----------------------------------------------------------------------------
static void inheritDocumentation()
{
for (const auto &mn : *Doxygen::memberNameLinkedMap)
{
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
//static int count=0;
//printf("%04d Member '%s'\n",count++,qPrint(md->qualifiedName()));
if (md && md->documentation().isEmpty() && md->briefDescription().isEmpty())
{ // no documentation yet
const MemberDef *bmd = md->reimplements();
while (bmd && bmd->documentation().isEmpty() &&
bmd->briefDescription().isEmpty()
)
{ // search up the inheritance tree for a documentation member
//printf("bmd=%s class=%s\n",qPrint(bmd->name()),qPrint(bmd->getClassDef()->name()));
bmd = bmd->reimplements();
}
if (bmd) // copy the documentation from the reimplemented member
{
md->setInheritsDocsFrom(bmd);
md->setDocumentation(bmd->documentation(),bmd->docFile(),bmd->docLine());
md->setDocsForDefinition(bmd->isDocsForDefinition());
md->setBriefDescription(bmd->briefDescription(),bmd->briefFile(),bmd->briefLine());
md->copyArgumentNames(bmd);
md->setInbodyDocumentation(bmd->inbodyDocumentation(),bmd->inbodyFile(),bmd->inbodyLine());
}
}
}
}
}
//----------------------------------------------------------------------------
static void combineUsingRelations()
{
// for each file
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->combineUsingRelations();
}
}
// for each namespace
NamespaceDefSet visitedNamespaces;
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->combineUsingRelations(visitedNamespaces);
}
}
}
//----------------------------------------------------------------------------
static void addMembersToMemberGroup()
{
// for each class
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->addMembersToMemberGroup();
}
}
// for each file
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->addMembersToMemberGroup();
}
}
// for each namespace
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->addMembersToMemberGroup();
}
}
// for each group
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->addMembersToMemberGroup();
}
ModuleManager::instance().addMembersToMemberGroup();
}
//----------------------------------------------------------------------------
static void distributeMemberGroupDocumentation()
{
// for each class
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->distributeMemberGroupDocumentation();
}
}
// for each file
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->distributeMemberGroupDocumentation();
}
}
// for each namespace
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->distributeMemberGroupDocumentation();
}
}
// for each group
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->distributeMemberGroupDocumentation();
}
ModuleManager::instance().distributeMemberGroupDocumentation();
}
//----------------------------------------------------------------------------
static void findSectionsInDocumentation()
{
// for each class
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm)
{
cdm->findSectionsInDocumentation();
}
}
// for each concept
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
ConceptDefMutable *cdm = toConceptDefMutable(cd.get());
if (cdm)
{
cdm->findSectionsInDocumentation();
}
}
// for each file
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
fd->findSectionsInDocumentation();
}
}
// for each namespace
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
ndm->findSectionsInDocumentation();
}
}
// for each group
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->findSectionsInDocumentation();
}
// for each page
for (const auto &pd : *Doxygen::pageLinkedMap)
{
pd->findSectionsInDocumentation();
}
ModuleManager::instance().findSectionsInDocumentation();
if (Doxygen::mainPage) Doxygen::mainPage->findSectionsInDocumentation();
}
//----------------------------------------------------------------------
static void flushCachedTemplateRelations()
{
// remove all references to classes from the cache
// as there can be new template instances in the inheritance path
// to this class. Optimization: only remove those classes that
// have inheritance instances as direct or indirect sub classes.
StringVector elementsToRemove;
for (const auto &ci : *Doxygen::typeLookupCache)
{
const LookupInfo &li = ci.second;
if (li.definition)
{
elementsToRemove.push_back(ci.first);
}
}
for (const auto &k : elementsToRemove)
{
Doxygen::typeLookupCache->remove(k);
}
// remove all cached typedef resolutions whose target is a
// template class as this may now be a template instance
// for each global function name
for (const auto &fn : *Doxygen::functionNameLinkedMap)
{
// for each function with that name
for (const auto &ifmd : *fn)
{
MemberDefMutable *fmd = toMemberDefMutable(ifmd.get());
if (fmd && fmd->isTypedefValCached())
{
const ClassDef *cd = fmd->getCachedTypedefVal();
if (cd->isTemplate()) fmd->invalidateTypedefValCache();
}
}
}
// for each class method name
for (const auto &nm : *Doxygen::memberNameLinkedMap)
{
// for each function with that name
for (const auto &imd : *nm)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md && md->isTypedefValCached())
{
const ClassDef *cd = md->getCachedTypedefVal();
if (cd->isTemplate()) md->invalidateTypedefValCache();
}
}
}
}
//----------------------------------------------------------------------------
static void flushUnresolvedRelations()
{
// Remove all unresolved references to classes from the cache.
// This is needed before resolving the inheritance relations, since
// it would otherwise not find the inheritance relation
// for C in the example below, as B::I was already found to be unresolvable
// (which is correct if you ignore the inheritance relation between A and B).
//
// class A { class I {} };
// class B : public A {};
// class C : public B::I {};
StringVector elementsToRemove;
for (const auto &ci : *Doxygen::typeLookupCache)
{
const LookupInfo &li = ci.second;
if (li.definition==nullptr && li.typeDef==nullptr)
{
elementsToRemove.push_back(ci.first);
}
}
for (const auto &k : elementsToRemove)
{
Doxygen::typeLookupCache->remove(k);
}
// for each global function name
for (const auto &fn : *Doxygen::functionNameLinkedMap)
{
// for each function with that name
for (const auto &ifmd : *fn)
{
MemberDefMutable *fmd = toMemberDefMutable(ifmd.get());
if (fmd)
{
fmd->invalidateCachedArgumentTypes();
}
}
}
// for each class method name
for (const auto &nm : *Doxygen::memberNameLinkedMap)
{
// for each function with that name
for (const auto &imd : *nm)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md)
{
md->invalidateCachedArgumentTypes();
}
}
}
}
//----------------------------------------------------------------------------
// Returns TRUE if the entry and member definition have equal file names,
// otherwise FALSE.
static bool haveEqualFileNames(const Entry *root,const MemberDef *md)
{
const FileDef *fd = md->getFileDef();
if (!fd)
{
return FALSE;
}
return fd->absFilePath() == root->fileName;
}
//----------------------------------------------------------------------------
static void addDefineDoc(const Entry *root, MemberDefMutable *md)
{
md->setDocumentation(root->doc,root->docFile,root->docLine);
md->setDocsForDefinition(!root->proto);
md->setBriefDescription(root->brief,root->briefFile,root->briefLine);
if (md->inbodyDocumentation().isEmpty())
{
md->setInbodyDocumentation(root->inbodyDocs,root->inbodyFile,root->inbodyLine);
}
if (md->getStartBodyLine()==-1 && root->bodyLine!=-1)
{
md->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
md->setBodyDef(root->fileDef());
}
md->addSectionsToDefinition(root->anchors);
md->setMaxInitLines(root->initLines);
applyMemberOverrideOptions(root,md);
md->setRefItems(root->sli);
if (root->mGrpId!=-1) md->setMemberGroupId(root->mGrpId);
addMemberToGroups(root,md);
ModuleManager::instance().addMemberToModule(root,md);
}
//----------------------------------------------------------------------------
static void findDefineDocumentation(Entry *root)
{
if ((root->section.isDefineDoc() || root->section.isDefine()) && !root->name.isEmpty())
{
//printf("found define '%s' '%s' brief='%s' doc='%s'\n",
// qPrint(root->name),qPrint(root->args),qPrint(root->brief),qPrint(root->doc));
if (root->tagInfo() && !root->name.isEmpty()) // define read from a tag file
{
auto md = createMemberDef(root->tagInfo()->tagName,1,1,
"#define",root->name,root->args,QCString(),
Protection::Public,Specifier::Normal,FALSE,Relationship::Member,MemberType::Define,
ArgumentList(),ArgumentList(),"");
auto mmd = toMemberDefMutable(md.get());
mmd->setTagInfo(root->tagInfo());
mmd->setLanguage(root->lang);
//printf("Searching for '%s' fd=%p\n",qPrint(filePathName),fd);
mmd->setFileDef(root->parent()->fileDef());
//printf("Adding member=%s\n",qPrint(md->name()));
MemberName *mn = Doxygen::functionNameLinkedMap->add(root->name);
mn->push_back(std::move(md));
}
MemberName *mn=Doxygen::functionNameLinkedMap->find(root->name);
if (mn)
{
int count=0;
for (const auto &md : *mn)
{
if (md->memberType()==MemberType::Define) count++;
}
if (count==1)
{
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md && md->memberType()==MemberType::Define)
{
addDefineDoc(root,md);
}
}
}
else if (count>1 &&
(!root->doc.isEmpty() ||
!root->brief.isEmpty() ||
root->bodyLine!=-1
)
)
// multiple defines don't know where to add docs
// but maybe they are in different files together with their documentation
{
for (const auto &imd : *mn)
{
MemberDefMutable *md = toMemberDefMutable(imd.get());
if (md && md->memberType()==MemberType::Define)
{
if (haveEqualFileNames(root, md) || isEntryInGroupOfMember(root, md))
// doc and define in the same file or group assume they belong together.
{
addDefineDoc(root,md);
}
}
}
//warn("define %s found in the following files:\n",qPrint(root->name));
//warn("Cannot determine where to add the documentation found "
// "at line %d of file %s. \n",
// root->startLine,qPrint(root->fileName));
}
}
else if (!root->doc.isEmpty() || !root->brief.isEmpty()) // define not found
{
bool preEnabled = Config_getBool(ENABLE_PREPROCESSING);
if (preEnabled)
{
warn(root->fileName,root->startLine,
"documentation for unknown define %s found.",
qPrint(root->name)
);
}
else
{
warn(root->fileName,root->startLine,
"found documented #define %s but ignoring it because "
"ENABLE_PREPROCESSING is NO.",
qPrint(root->name)
);
}
}
}
for (const auto &e : root->children()) findDefineDocumentation(e.get());
}
//----------------------------------------------------------------------------
static void findDirDocumentation(const Entry *root)
{
if (root->section.isDirDoc())
{
QCString normalizedName = root->name;
normalizedName = substitute(normalizedName,"\\","/");
//printf("root->docFile=%s normalizedName=%s\n",
// qPrint(root->docFile),qPrint(normalizedName));
if (root->docFile==normalizedName) // current dir?
{
int lastSlashPos=normalizedName.findRev('/');
if (lastSlashPos!=-1) // strip file name
{
normalizedName=normalizedName.left(lastSlashPos);
}
}
if (normalizedName.at(normalizedName.length()-1)!='/')
{
normalizedName+='/';
}
DirDef *matchingDir=nullptr;
for (const auto &dir : *Doxygen::dirLinkedMap)
{
//printf("Dir: %s<->%s\n",qPrint(dir->name()),qPrint(normalizedName));
if (dir->name().right(normalizedName.length())==normalizedName)
{
if (matchingDir)
{
warn(root->fileName,root->startLine,
"\\dir command matches multiple directories.\n"
" Applying the command for directory %s\n"
" Ignoring the command for directory %s",
qPrint(matchingDir->name()),qPrint(dir->name())
);
}
else
{
matchingDir=dir.get();
}
}
}
if (matchingDir)
{
//printf("Match for with dir %s\n",qPrint(matchingDir->name()));
matchingDir->setBriefDescription(root->brief,root->briefFile,root->briefLine);
matchingDir->setDocumentation(root->doc,root->docFile,root->docLine);
matchingDir->setRefItems(root->sli);
root->commandOverrides.apply_directoryGraph([&](bool b) { matchingDir->overrideDirectoryGraph(b); });
addDirToGroups(root,matchingDir);
}
else
{
warn(root->fileName,root->startLine,"No matching "
"directory found for command \\dir %s",qPrint(normalizedName));
}
}
for (const auto &e : root->children()) findDirDocumentation(e.get());
}
//----------------------------------------------------------------------------
// create a (sorted) list of separate documentation pages
static void buildPageList(Entry *root)
{
if (root->section.isPageDoc())
{
if (!root->name.isEmpty())
{
addRelatedPage(root);
}
}
else if (root->section.isMainpageDoc())
{
QCString title=root->args.stripWhiteSpace();
if (title.isEmpty()) title=theTranslator->trMainPage();
//QCString name = Config_getBool(GENERATE_TREEVIEW)?"main":"index";
QCString name = "index";
addRefItem(root->sli,
name,
"page",
name,
title,
QCString(),nullptr
);
}
for (const auto &e : root->children()) buildPageList(e.get());
}
// search for the main page defined in this project
static void findMainPage(Entry *root)
{
if (root->section.isMainpageDoc())
{
if (Doxygen::mainPage==nullptr && root->tagInfo()==nullptr)
{
//printf("mainpage: docLine=%d startLine=%d\n",root->docLine,root->startLine);
//printf("Found main page! \n======\n%s\n=======\n",qPrint(root->doc));
QCString title=root->args.stripWhiteSpace();
if (title.isEmpty()) title = Config_getString(PROJECT_NAME);
//QCString indexName=Config_getBool(GENERATE_TREEVIEW)?"main":"index";
QCString indexName="index";
Doxygen::mainPage = createPageDef(root->docFile,root->docLine,
indexName, root->brief+root->doc+root->inbodyDocs,title);
//setFileNameForSections(root->anchors,"index",Doxygen::mainPage);
Doxygen::mainPage->setBriefDescription(root->brief,root->briefFile,root->briefLine);
Doxygen::mainPage->setBodySegment(root->startLine,root->startLine,-1);
Doxygen::mainPage->setFileName(indexName);
Doxygen::mainPage->setLocalToc(root->localToc);
addPageToContext(Doxygen::mainPage.get(),root);
const SectionInfo *si = SectionManager::instance().find(Doxygen::mainPage->name());
if (si)
{
if (!si->ref().isEmpty()) // we are from a tag file
{
// a page name is a label as well! but should no be double either
SectionManager::instance().replace(
Doxygen::mainPage->name(),
indexName,
root->startLine,
Doxygen::mainPage->title(),
SectionType::Page,
0); // level 0
}
else if (si->lineNr() != -1)
{
warn(root->fileName,root->startLine,"multiple use of section label '%s' for main page, (first occurrence: %s, line %d)",
qPrint(Doxygen::mainPage->name()),qPrint(si->fileName()),si->lineNr());
}
else
{
warn(root->fileName,root->startLine,"multiple use of section label '%s' for main page, (first occurrence: %s)",
qPrint(Doxygen::mainPage->name()),qPrint(si->fileName()));
}
}
else
{
// a page name is a label as well! but should no be double either
SectionManager::instance().add(
Doxygen::mainPage->name(),
indexName,
root->startLine,
Doxygen::mainPage->title(),
SectionType::Page,
0); // level 0
}
Doxygen::mainPage->addSectionsToDefinition(root->anchors);
}
else if (root->tagInfo()==nullptr)
{
warn(root->fileName,root->startLine,
"found more than one \\mainpage comment block! (first occurrence: %s, line %d), Skipping current block!",
qPrint(Doxygen::mainPage->docFile()),Doxygen::mainPage->getStartBodyLine());
}
}
for (const auto &e : root->children()) findMainPage(e.get());
}
// search for the main page imported via tag files and add only the section labels
static void findMainPageTagFiles(Entry *root)
{
if (root->section.isMainpageDoc())
{
if (Doxygen::mainPage && root->tagInfo())
{
Doxygen::mainPage->addSectionsToDefinition(root->anchors);
}
}
for (const auto &e : root->children()) findMainPageTagFiles(e.get());
}
static void computePageRelations(Entry *root)
{
if ((root->section.isPageDoc() || root->section.isMainpageDoc()) && !root->name.isEmpty())
{
PageDef *pd = root->section.isPageDoc() ?
Doxygen::pageLinkedMap->find(root->name) :
Doxygen::mainPage.get();
if (pd)
{
for (const BaseInfo &bi : root->extends)
{
PageDef *subPd = Doxygen::pageLinkedMap->find(bi.name);
if (pd==subPd)
{
term("page defined %s with label %s is a direct "
"subpage of itself! Please remove this cyclic dependency.\n",
qPrint(warn_line(pd->docFile(),pd->docLine())),qPrint(pd->name()));
}
else if (subPd)
{
pd->addInnerCompound(subPd);
//printf("*** Added subpage relation: %s->%s\n",
// qPrint(pd->name()),qPrint(subPd->name()));
}
}
}
}
for (const auto &e : root->children()) computePageRelations(e.get());
}
static void checkPageRelations()
{
for (const auto &pd : *Doxygen::pageLinkedMap)
{
Definition *ppd = pd->getOuterScope();
while (ppd)
{
if (ppd==pd.get())
{
term("page defined %s with label %s is a subpage "
"of itself! Please remove this cyclic dependency.\n",
qPrint(warn_line(pd->docFile(),pd->docLine())),qPrint(pd->name()));
}
ppd=ppd->getOuterScope();
}
}
}
//----------------------------------------------------------------------------
static void resolveUserReferences()
{
for (const auto &si : SectionManager::instance())
{
//printf("si->label='%s' si->definition=%s si->fileName='%s'\n",
// qPrint(si->label),si->definition?qPrint(si->definition->name()):"<none>",
// qPrint(si->fileName));
PageDef *pd=nullptr;
// hack: the items of a todo/test/bug/deprecated list are all fragments from
// different files, so the resulting section's all have the wrong file
// name (not from the todo/test/bug/deprecated list, but from the file in
// which they are defined). We correct this here by looking at the
// generated section labels!
for (const RefListManager::Ptr &rl : RefListManager::instance())
{
QCString label="_"+rl->listName(); // "_todo", "_test", ...
if (si->label().left(label.length())==label)
{
si->setFileName(rl->listName());
si->setGenerated(TRUE);
break;
}
}
//printf("start: si->label=%s si->fileName=%s\n",qPrint(si->label),qPrint(si->fileName));
if (!si->generated())
{
// if this section is in a page and the page is in a group, then we
// have to adjust the link file name to point to the group.
if (!si->fileName().isEmpty() &&
(pd=Doxygen::pageLinkedMap->find(si->fileName())) &&
pd->getGroupDef())
{
si->setFileName(pd->getGroupDef()->getOutputFileBase());
}
if (si->definition())
{
// TODO: there should be one function in Definition that returns
// the file to link to, so we can avoid the following tests.
const GroupDef *gd=nullptr;
if (si->definition()->definitionType()==Definition::TypeMember)
{
gd = (toMemberDef(si->definition()))->getGroupDef();
}
if (gd)
{
si->setFileName(gd->getOutputFileBase());
}
else
{
//si->fileName=si->definition->getOutputFileBase();
//printf("Setting si->fileName to %s\n",qPrint(si->fileName));
}
}
}
//printf("end: si->label=%s si->fileName=%s\n",qPrint(si->label),qPrint(si->fileName));
}
}
//----------------------------------------------------------------------------
// generate all separate documentation pages
static void generatePageDocs()
{
//printf("documentedPages=%d real=%d\n",documentedPages,Doxygen::pageLinkedMap->count());
if (Index::instance().numDocumentedPages()==0) return;
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (!pd->getGroupDef() && !pd->isReference())
{
msg("Generating docs for page %s...\n",qPrint(pd->name()));
pd->writeDocumentation(*g_outputList);
}
}
}
//----------------------------------------------------------------------------
// create a (sorted) list & dictionary of example pages
static void buildExampleList(Entry *root)
{
if ((root->section.isExample() || root->section.isExampleLineno()) && !root->name.isEmpty())
{
if (Doxygen::exampleLinkedMap->find(root->name))
{
warn(root->fileName,root->startLine,
"Example %s was already documented. Ignoring "
"documentation found here.",
qPrint(root->name)
);
}
else
{
PageDef *pd = Doxygen::exampleLinkedMap->add(root->name,
createPageDef(root->fileName,root->startLine,
root->name,root->brief+root->doc+root->inbodyDocs,root->args));
pd->setBriefDescription(root->brief,root->briefFile,root->briefLine);
pd->setFileName(convertNameToFile(pd->name()+"-example",FALSE,TRUE));
pd->addSectionsToDefinition(root->anchors);
pd->setLanguage(root->lang);
pd->setShowLineNo(root->section.isExampleLineno());
//we don't add example to groups
//addExampleToGroups(root,pd);
}
}
for (const auto &e : root->children()) buildExampleList(e.get());
}
//----------------------------------------------------------------------------
// prints the Entry tree (for debugging)
void printNavTree(Entry *root,int indent)
{
if (Debug::isFlagSet(Debug::Entries))
{
QCString indentStr;
indentStr.fill(' ',indent);
Debug::print(Debug::Entries,0,"%s%s at %s:%d (sec=%s, spec=%s)\n",
indentStr.isEmpty()?"":qPrint(indentStr),
root->name.isEmpty()?"<empty>":qPrint(root->name),
qPrint(root->fileName),root->startLine,
root->section.to_string().c_str(),
root->spec.to_string().c_str());
for (const auto &e : root->children())
{
printNavTree(e.get(),indent+2);
}
}
}
void printNavLayout(LayoutNavEntry *root,int indent)
{
if (Debug::isFlagSet(Debug::Layout))
{
QCString indentStr;
indentStr.fill(' ',indent);
Debug::print(Debug::Layout,0,"%skind=%s visible=%d title='%s'\n",
indentStr.isEmpty()?"":qPrint(indentStr),
qPrint(root->navToString()),
root->visible(),
qPrint(root->title())
);
for (const auto &e : root->children())
{
printNavLayout(e.get(),indent+2);
}
}
}
void printLayout()
{
bool extraIndent = false;
Debug::print(Debug::Layout,0,"Part: Navigation index\n");
for (const auto &e : LayoutDocManager::instance().rootNavEntry()->children())
{
printNavLayout(e.get(),2);
}
for (int i = 0; i < LayoutDocManager::NrParts; i++)
{
Debug::print(Debug::Layout,0,"\nPart: %s\n", qPrint(LayoutDocManager::partToString(i)));
for (const auto &lde : LayoutDocManager::instance().docEntries(static_cast<LayoutDocManager::LayoutPart>(i)))
{
if (const LayoutDocEntrySimple *ldes = dynamic_cast<const LayoutDocEntrySimple*>(lde.get()))
{
if (lde->kind() == LayoutDocEntry::MemberDeclEnd || lde->kind() == LayoutDocEntry::MemberDefEnd) extraIndent = false;
Debug::print(Debug::Layout,0," %skind: %s, visible=%d\n",
extraIndent? " " : "",qPrint(lde->entryToString()), ldes->visible());
if (lde->kind() == LayoutDocEntry::MemberDeclStart || lde->kind() == LayoutDocEntry::MemberDefStart) extraIndent = true;
}
else if (const LayoutDocEntryMemberDecl *lmdecl = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get()))
{
Debug::print(Debug::Layout,0," %scomplex kind: %s, type: %s\n",
extraIndent? " " : "",qPrint(lde->entryToString()),qPrint(lmdecl->type.to_string()));
}
else if (const LayoutDocEntryMemberDef *lmdef = dynamic_cast<const LayoutDocEntryMemberDef*>(lde.get()))
{
Debug::print(Debug::Layout,0," %scomplex kind: %s, type: %s\n",
extraIndent? " " : "",qPrint(lde->entryToString()),qPrint(lmdef->type.to_string()));
}
else
{
// should not happen
Debug::print(Debug::Layout,0," %snot handled kind: %s\n",extraIndent? " " : "",qPrint(lde->entryToString()));
}
}
}
}
//----------------------------------------------------------------------------
// prints the Sections tree (for debugging)
void printSectionsTree()
{
if (Debug::isFlagSet(Debug::Sections))
{
for (const auto &si : SectionManager::instance())
{
Debug::print(Debug::Sections,0,"Section = %s, file = %s, title = %s, type = %d, ref = %s\n",
qPrint(si->label()),qPrint(si->fileName()),qPrint(si->title()),
si->type(),qPrint(si->ref()));
}
}
}
//----------------------------------------------------------------------------
// generate the example documentation
static void generateExampleDocs()
{
g_outputList->disable(OutputType::Man);
for (const auto &pd : *Doxygen::exampleLinkedMap)
{
msg("Generating docs for example %s...\n",qPrint(pd->name()));
SrcLangExt lang = getLanguageFromFileName(pd->name(), SrcLangExt::Unknown);
if (lang != SrcLangExt::Unknown)
{
QCString ext = getFileNameExtension(pd->name());
auto intf = Doxygen::parserManager->getCodeParser(ext);
intf->resetCodeParserState();
}
QCString n=pd->getOutputFileBase();
startFile(*g_outputList,n,n,pd->name());
startTitle(*g_outputList,n);
g_outputList->docify(pd->name());
endTitle(*g_outputList,n,QCString());
g_outputList->startContents();
QCString lineNoOptStr;
if (pd->showLineNo())
{
lineNoOptStr="{lineno}";
}
g_outputList->generateDoc(pd->docFile(), // file
pd->docLine(), // startLine
pd.get(), // context
nullptr, // memberDef
(pd->briefDescription().isEmpty()?"":pd->briefDescription()+"\n\n")+
pd->documentation()+"\n\n\\include"+lineNoOptStr+" "+pd->name(), // docs
TRUE, // index words
TRUE, // is example
pd->name(),
FALSE,
FALSE,
Config_getBool(MARKDOWN_SUPPORT)
);
endFile(*g_outputList); // contains g_outputList->endContents()
}
g_outputList->enable(OutputType::Man);
}
//----------------------------------------------------------------------------
// generate module pages
static void generateGroupDocs()
{
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (!gd->isReference())
{
gd->writeDocumentation(*g_outputList);
}
}
}
//----------------------------------------------------------------------------
// generate module pages
static void generateNamespaceClassDocs(const ClassLinkedRefMap &classList)
{
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
if (numThreads>1) // multi threaded processing
{
struct DocContext
{
DocContext(ClassDefMutable *cdm_,const OutputList &ol_)
: cdm(cdm_), ol(ol_) {}
ClassDefMutable *cdm;
OutputList ol;
};
ThreadPool threadPool(numThreads);
std::vector< std::future< std::shared_ptr<DocContext> > > results;
// for each class in the namespace...
for (const auto &cd : classList)
{
ClassDefMutable *cdm = toClassDefMutable(cd);
if (cdm)
{
auto ctx = std::make_shared<DocContext>(cdm,*g_outputList);
auto processFile = [ctx]()
{
if ( ( ctx->cdm->isLinkableInProject() &&
ctx->cdm->templateMaster()==nullptr
) // skip external references, anonymous compounds and
// template instances and nested classes
&& !ctx->cdm->isHidden() && !ctx->cdm->isEmbeddedInOuterScope()
)
{
msg("Generating docs for compound %s...\n",qPrint(ctx->cdm->displayName()));
ctx->cdm->writeDocumentation(ctx->ol);
ctx->cdm->writeMemberList(ctx->ol);
}
ctx->cdm->writeDocumentationForInnerClasses(ctx->ol);
return ctx;
};
results.emplace_back(threadPool.queue(processFile));
}
}
// wait for the results
for (auto &f : results)
{
auto ctx = f.get();
}
}
else // single threaded processing
{
// for each class in the namespace...
for (const auto &cd : classList)
{
ClassDefMutable *cdm = toClassDefMutable(cd);
if (cdm)
{
if ( ( cd->isLinkableInProject() &&
cd->templateMaster()==nullptr
) // skip external references, anonymous compounds and
// template instances and nested classes
&& !cd->isHidden() && !cd->isEmbeddedInOuterScope()
)
{
msg("Generating docs for compound %s...\n",qPrint(cd->displayName()));
cdm->writeDocumentation(*g_outputList);
cdm->writeMemberList(*g_outputList);
}
cdm->writeDocumentationForInnerClasses(*g_outputList);
}
}
}
}
static void generateNamespaceConceptDocs(const ConceptLinkedRefMap &conceptList)
{
// for each concept in the namespace...
for (const auto &cd : conceptList)
{
ConceptDefMutable *cdm = toConceptDefMutable(cd);
if ( cdm && cd->isLinkableInProject() && !cd->isHidden())
{
msg("Generating docs for concept %s...\n",qPrint(cd->name()));
cdm->writeDocumentation(*g_outputList);
}
}
}
static void generateNamespaceDocs()
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
//writeNamespaceIndex(*g_outputList);
// for each namespace...
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject())
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm)
{
msg("Generating docs for namespace %s\n",qPrint(nd->displayName()));
ndm->writeDocumentation(*g_outputList);
}
}
generateNamespaceClassDocs(nd->getClasses());
if (sliceOpt)
{
generateNamespaceClassDocs(nd->getInterfaces());
generateNamespaceClassDocs(nd->getStructs());
generateNamespaceClassDocs(nd->getExceptions());
}
generateNamespaceConceptDocs(nd->getConcepts());
}
}
static void runHtmlHelpCompiler()
{
std::string oldDir = Dir::currentDirPath();
Dir::setCurrent(Config_getString(HTML_OUTPUT).str());
Portable::setShortDir();
if (Portable::system(Config_getString(HHC_LOCATION).data(), qPrint(HtmlHelp::hhpFileName), Debug::isFlagSet(Debug::ExtCmd))!=1)
{
err("failed to run html help compiler on %s\n", qPrint(HtmlHelp::hhpFileName));
}
Dir::setCurrent(oldDir);
}
static void runQHelpGenerator()
{
QCString args = Qhp::qhpFileName + " -o \"" + Qhp::getQchFileName() + "\"";
std::string oldDir = Dir::currentDirPath();
Dir::setCurrent(Config_getString(HTML_OUTPUT).str());
QCString qhgLocation=Config_getString(QHG_LOCATION);
if (Debug::isFlagSet(Debug::Qhp)) // produce info for debugging
{
// run qhelpgenerator -v and extract the Qt version used
QCString cmd=qhgLocation+ " -v 2>&1";
Debug::print(Debug::ExtCmd,0,"Executing popen(`%s`)\n",qPrint(cmd));
FILE *f=Portable::popen(cmd,"r");
if (!f)
{
err("could not execute %s\n",qPrint(qhgLocation));
}
else
{
const size_t bufSize = 1024;
char inBuf[bufSize+1];
size_t numRead=fread(inBuf,1,bufSize,f);
inBuf[numRead] = '\0';
Debug::print(Debug::Qhp,0,inBuf);
Portable::pclose(f);
int qtVersion=0;
static const reg::Ex versionReg(R"(Qt (\d+)\.(\d+)\.(\d+))");
reg::Match match;
std::string s = inBuf;
if (reg::search(inBuf,match,versionReg))
{
qtVersion = 10000*QCString(match[1].str()).toInt() +
100*QCString(match[2].str()).toInt() +
QCString(match[3].str()).toInt();
}
if (qtVersion>0 && (qtVersion<60000 || qtVersion >= 60205))
{
// dump the output of qhelpgenerator -c file.qhp
// Qt<6 or Qt>=6.2.5 or higher, see https://bugreports.qt.io/browse/QTBUG-101070
cmd=qhgLocation+ " -c " + Qhp::qhpFileName + " 2>&1";
Debug::print(Debug::ExtCmd,0,"Executing popen(`%s`)\n",qPrint(cmd));
f=Portable::popen(cmd,"r");
if (!f)
{
err("could not execute %s\n",qPrint(qhgLocation));
}
else
{
std::string output;
while ((numRead=fread(inBuf,1,bufSize,f))>0)
{
inBuf[numRead] = '\0';
output += inBuf;
}
Portable::pclose(f);
Debug::print(Debug::Qhp,0,output.c_str());
}
}
}
}
if (Portable::system(qhgLocation, args, FALSE))
{
err("failed to run qhelpgenerator on %s\n",qPrint(Qhp::qhpFileName));
}
Dir::setCurrent(oldDir);
}
//----------------------------------------------------------------------------
static void computeVerifiedDotPath()
{
// check dot path
QCString dotPath = Config_getString(DOT_PATH);
if (!dotPath.isEmpty())
{
FileInfo fi(dotPath.str());
if (!(fi.exists() && fi.isFile()) )// not an existing user specified path + exec
{
dotPath = dotPath+"/dot"+Portable::commandExtension();
FileInfo dp(dotPath.str());
if (!dp.exists() || !dp.isFile())
{
warn_uncond("the dot tool could not be found as '%s'\n",qPrint(dotPath));
dotPath = "dot";
dotPath += Portable::commandExtension();
}
}
#if defined(_WIN32) // convert slashes
size_t l=dotPath.length();
for (size_t i=0;i<l;i++) if (dotPath.at(i)=='/') dotPath.at(i)='\\';
#endif
}
else
{
dotPath = "dot";
dotPath += Portable::commandExtension();
}
Doxygen::verifiedDotPath = dotPath;
TRACE("{}",Doxygen::verifiedDotPath);
}
//----------------------------------------------------------------------------
/*! Generate a template version of the configuration file.
* If the \a shortList parameter is TRUE a configuration file without
* comments will be generated.
*/
static void generateConfigFile(const QCString &configFile,bool shortList,
bool updateOnly=FALSE)
{
std::ofstream f;
bool fileOpened=openOutputFile(configFile,f);
bool writeToStdout=configFile=="-";
if (fileOpened)
{
TextStream t(&f);
Config::writeTemplate(t,shortList,updateOnly);
if (!writeToStdout)
{
if (!updateOnly)
{
msg("\n\nConfiguration file '%s' created.\n\n",qPrint(configFile));
msg("Now edit the configuration file and enter\n\n");
if (configFile!="Doxyfile" && configFile!="doxyfile")
msg(" doxygen %s\n\n",qPrint(configFile));
else
msg(" doxygen\n\n");
msg("to generate the documentation for your project\n\n");
}
else
{
msg("\n\nConfiguration file '%s' updated.\n\n",qPrint(configFile));
}
}
}
else
{
term("Cannot open file %s for writing\n",qPrint(configFile));
}
}
static void compareDoxyfile(Config::CompareMode diffList)
{
std::ofstream f;
bool fileOpened=openOutputFile("-",f);
if (fileOpened)
{
TextStream t(&f);
Config::compareDoxyfile(t,diffList);
}
else
{
term("Cannot open stdout for writing\n");
}
}
//----------------------------------------------------------------------------
// read and parse a tag file
static void readTagFile(const std::shared_ptr<Entry> &root,const QCString &tagLine)
{
QCString fileName;
QCString destName;
int eqPos = tagLine.find('=');
if (eqPos!=-1) // tag command contains a destination
{
fileName = tagLine.left(eqPos).stripWhiteSpace();
destName = tagLine.right(tagLine.length()-eqPos-1).stripWhiteSpace();
if (fileName.isEmpty() || destName.isEmpty()) return;
//printf("insert tagDestination %s->%s\n",qPrint(fi.fileName()),qPrint(destName));
}
else
{
fileName = tagLine;
}
FileInfo fi(fileName.str());
if (!fi.exists() || !fi.isFile())
{
err("Tag file '%s' does not exist or is not a file. Skipping it...\n",
qPrint(fileName));
return;
}
if (Doxygen::tagFileSet.find(fi.absFilePath().c_str()) != Doxygen::tagFileSet.end()) return;
Doxygen::tagFileSet.emplace(fi.absFilePath());
if (!destName.isEmpty())
{
Doxygen::tagDestinationMap.emplace(fi.absFilePath(), destName.str());
msg("Reading tag file '%s', location '%s'...\n",qPrint(fileName),qPrint(destName));
}
else
msg("Reading tag file '%s'...\n",qPrint(fileName));
parseTagFile(root,fi.absFilePath().c_str());
}
//----------------------------------------------------------------------------
static void copyLatexStyleSheet()
{
const StringVector &latexExtraStyleSheet = Config_getList(LATEX_EXTRA_STYLESHEET);
for (const auto &sheet : latexExtraStyleSheet)
{
std::string fileName = sheet;
if (!fileName.empty())
{
FileInfo fi(fileName);
if (!fi.exists())
{
err("Style sheet '%s' specified by LATEX_EXTRA_STYLESHEET does not exist!\n",qPrint(fileName));
}
else if (fi.isDir())
{
err("Style sheet '%s' specified by LATEX_EXTRA_STYLESHEET is a directory, it has to be a file!\n", qPrint(fileName));
}
else
{
QCString destFileName = Config_getString(LATEX_OUTPUT)+"/"+fi.fileName();
if (!checkExtension(fi.fileName().c_str(), LATEX_STYLE_EXTENSION))
{
destFileName += LATEX_STYLE_EXTENSION;
}
copyFile(QCString(fileName), destFileName);
}
}
}
}
//----------------------------------------------------------------------------
static void copyStyleSheet()
{
QCString htmlStyleSheet = Config_getString(HTML_STYLESHEET);
if (!htmlStyleSheet.isEmpty())
{
if (!htmlStyleSheet.startsWith("http:") && !htmlStyleSheet.startsWith("https:"))
{
FileInfo fi(htmlStyleSheet.str());
if (!fi.exists())
{
err("Style sheet '%s' specified by HTML_STYLESHEET does not exist!\n",qPrint(htmlStyleSheet));
htmlStyleSheet = Config_updateString(HTML_STYLESHEET,""); // revert to the default
}
else if (fi.isDir())
{
err("Style sheet '%s' specified by HTML_STYLESHEET is a directory, it has to be a file!\n",qPrint(htmlStyleSheet));
htmlStyleSheet = Config_updateString(HTML_STYLESHEET,""); // revert to the default
}
else
{
QCString destFileName = Config_getString(HTML_OUTPUT)+"/"+fi.fileName();
copyFile(htmlStyleSheet,destFileName);
}
}
}
const StringVector &htmlExtraStyleSheet = Config_getList(HTML_EXTRA_STYLESHEET);
for (const auto &sheet : htmlExtraStyleSheet)
{
QCString fileName(sheet);
if (!fileName.isEmpty() && !fileName.startsWith("http:") && !fileName.startsWith("https:"))
{
FileInfo fi(fileName.str());
if (!fi.exists())
{
err("Style sheet '%s' specified by HTML_EXTRA_STYLESHEET does not exist!\n",qPrint(fileName));
}
else if (fi.fileName()=="doxygen.css" || fi.fileName()=="tabs.css" || fi.fileName()=="navtree.css")
{
err("Style sheet %s specified by HTML_EXTRA_STYLESHEET is already a built-in stylesheet. Please use a different name\n",qPrint(fi.fileName()));
}
else if (fi.isDir())
{
err("Style sheet '%s' specified by HTML_EXTRA_STYLESHEET is a directory, it has to be a file!\n",qPrint(fileName));
}
else
{
QCString destFileName = Config_getString(HTML_OUTPUT)+"/"+fi.fileName();
copyFile(QCString(fileName), destFileName);
}
}
}
}
static void copyLogo(const QCString &outputOption)
{
QCString projectLogo = projectLogoFile();
if (!projectLogo.isEmpty())
{
FileInfo fi(projectLogo.str());
if (!fi.exists())
{
err("Project logo '%s' specified by PROJECT_LOGO does not exist!\n",qPrint(projectLogo));
projectLogo = Config_updateString(PROJECT_LOGO,""); // revert to the default
}
else if (fi.isDir())
{
err("Project logo '%s' specified by PROJECT_LOGO is a directory, it has to be a file!\n",qPrint(projectLogo));
projectLogo = Config_updateString(PROJECT_LOGO,""); // revert to the default
}
else
{
QCString destFileName = outputOption+"/"+fi.fileName();
copyFile(projectLogo,destFileName);
Doxygen::indexList->addImageFile(fi.fileName().c_str());
}
}
}
static void copyIcon(const QCString &outputOption)
{
QCString projectIcon = Config_getString(PROJECT_ICON);
if (!projectIcon.isEmpty())
{
FileInfo fi(projectIcon.str());
if (!fi.exists())
{
err("Project icon '%s' specified by PROJECT_ICON does not exist!\n",qPrint(projectIcon));
projectIcon = Config_updateString(PROJECT_ICON,""); // revert to the default
}
else if (fi.isDir())
{
err("Project icon '%s' specified by PROJECT_ICON is a directory, it has to be a file!\n",qPrint(projectIcon));
projectIcon = Config_updateString(PROJECT_ICON,""); // revert to the default
}
else
{
QCString destFileName = outputOption+"/"+fi.fileName();
copyFile(projectIcon,destFileName);
Doxygen::indexList->addImageFile(fi.fileName().c_str());
}
}
}
static void copyExtraFiles(const StringVector &files,const QCString &filesOption,const QCString &outputOption)
{
for (const auto &fileName : files)
{
if (!fileName.empty())
{
FileInfo fi(fileName);
if (!fi.exists())
{
err("Extra file '%s' specified in %s does not exist!\n", fileName.c_str(),qPrint(filesOption));
}
else if (fi.isDir())
{
err("Extra file '%s' specified in %s is a directory, it has to be a file!\n", fileName.c_str(),qPrint(filesOption));
}
else
{
QCString destFileName = outputOption+"/"+fi.fileName();
Doxygen::indexList->addImageFile(fi.fileName().c_str());
copyFile(QCString(fileName), destFileName);
}
}
}
}
//----------------------------------------------------------------------------
static void generateDiskNames()
{
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
struct FileEntry
{
FileEntry(const QCString &p,FileDef *fd) : path(p), fileDef(fd) {}
QCString path;
FileDef *fileDef;
};
// collect the entry for which to compute the longest common prefix (LCP) of the path
std::vector<FileEntry> fileEntries;
for (const auto &fd : *fn)
{
if (!fd->isReference()) // skip external references
{
fileEntries.emplace_back(fd->getPath(),fd.get());
}
}
size_t size = fileEntries.size();
if (size==1) // name if unique, so diskname is simply the name
{
FileDef *fd = fileEntries[0].fileDef;
fd->setDiskName(fn->fileName());
}
else if (size>1) // multiple occurrences of the same file name
{
// sort the array
std::stable_sort(fileEntries.begin(),
fileEntries.end(),
[](const FileEntry &fe1,const FileEntry &fe2)
{ return qstricmp_sort(fe1.path,fe2.path)<0; }
);
// since the entries are sorted, the common prefix of the whole array is same
// as the common prefix between the first and last entry
const FileEntry &first = fileEntries[0];
const FileEntry &last = fileEntries[size-1];
int first_path_size = static_cast<int>(first.path.size())-1; // -1 to skip trailing slash
int last_path_size = static_cast<int>(last.path.size())-1; // -1 to skip trailing slash
int j=0;
int i=0;
for (i=0;i<first_path_size && i<last_path_size;i++)
{
if (first.path[i]=='/') j=i;
if (first.path[i]!=last.path[i]) break;
}
if (i==first_path_size && i<last_path_size && last.path[i]=='/')
{
// case first='some/path' and last='some/path/more' => match is 'some/path'
j=first_path_size;
}
else if (i==last_path_size && i<first_path_size && first.path[i]=='/')
{
// case first='some/path/more' and last='some/path' => match is 'some/path'
j=last_path_size;
}
// add non-common part of the path to the name
for (auto &fileEntry : fileEntries)
{
QCString prefix = fileEntry.path.right(fileEntry.path.length()-j-1);
fileEntry.fileDef->setName(prefix+fn->fileName());
//printf("!!!!!!!! non unique disk name=%s:%s\n",qPrint(prefix),fn->fileName());
fileEntry.fileDef->setDiskName(prefix+fn->fileName());
}
}
}
}
//----------------------------------------------------------------------------
static std::unique_ptr<OutlineParserInterface> getParserForFile(const QCString &fn)
{
QCString fileName=fn;
QCString extension;
int sep = fileName.findRev('/');
int ei = fileName.findRev('.');
if (ei!=-1 && (sep==-1 || ei>sep)) // matches dir/file.ext but not dir.1/file
{
extension=fileName.right(fileName.length()-ei);
}
else
{
extension = ".no_extension";
}
return Doxygen::parserManager->getOutlineParser(extension);
}
static std::shared_ptr<Entry> parseFile(OutlineParserInterface &parser,
FileDef *fd,const QCString &fn,
ClangTUParser *clangParser,bool newTU)
{
QCString fileName=fn;
AUTO_TRACE("fileName={}",fileName);
QCString extension;
int ei = fileName.findRev('.');
if (ei!=-1)
{
extension=fileName.right(fileName.length()-ei);
}
else
{
extension = ".no_extension";
}
FileInfo fi(fileName.str());
std::string preBuf;
if (Config_getBool(ENABLE_PREPROCESSING) &&
parser.needsPreprocessing(extension))
{
Preprocessor preprocessor;
const StringVector &includePath = Config_getList(INCLUDE_PATH);
for (const auto &s : includePath)
{
std::string absPath = FileInfo(s).absFilePath();
preprocessor.addSearchDir(absPath.c_str());
}
std::string inBuf;
msg("Preprocessing %s...\n",qPrint(fn));
readInputFile(fileName,inBuf);
addTerminalCharIfMissing(inBuf,'\n');
preprocessor.processFile(fileName,inBuf,preBuf);
}
else // no preprocessing
{
msg("Reading %s...\n",qPrint(fn));
readInputFile(fileName,preBuf);
addTerminalCharIfMissing(preBuf,'\n');
}
std::string convBuf;
convBuf.reserve(preBuf.size()+1024);
// convert multi-line C++ comments to C style comments
convertCppComments(preBuf,convBuf,fileName.str());
std::shared_ptr<Entry> fileRoot = std::make_shared<Entry>();
// use language parse to parse the file
if (clangParser)
{
if (newTU) clangParser->parse();
clangParser->switchToFile(fd);
}
parser.parseInput(fileName,convBuf.data(),fileRoot,clangParser);
fileRoot->setFileDef(fd);
return fileRoot;
}
//! parse the list of input files
static void parseFilesMultiThreading(const std::shared_ptr<Entry> &root)
{
AUTO_TRACE();
#if USE_LIBCLANG
if (Doxygen::clangAssistedParsing)
{
StringUnorderedSet processedFiles;
// create a dictionary with files to process
StringUnorderedSet filesToProcess;
for (const auto &s : g_inputFiles)
{
filesToProcess.insert(s);
}
std::mutex processedFilesLock;
// process source files (and their include dependencies)
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
msg("Processing input using %zu threads.\n",numThreads);
ThreadPool threadPool(numThreads);
using FutureType = std::vector< std::shared_ptr<Entry> >;
std::vector< std::future< FutureType > > results;
for (const auto &s : g_inputFiles)
{
bool ambig = false;
FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,s.c_str(),ambig);
ASSERT(fd!=nullptr);
if (fd->isSource() && !fd->isReference() && fd->getLanguage()==SrcLangExt::Cpp) // this is a source file
{
// lambda representing the work to executed by a thread
auto processFile = [s,&filesToProcess,&processedFilesLock,&processedFiles]() {
bool ambig_l = false;
std::vector< std::shared_ptr<Entry> > roots;
FileDef *fd_l = findFileDef(Doxygen::inputNameLinkedMap,s.c_str(),ambig_l);
auto clangParser = ClangParser::instance()->createTUParser(fd_l);
auto parser = getParserForFile(s.c_str());
auto fileRoot { parseFile(*parser.get(),fd_l,s.c_str(),clangParser.get(),true) };
roots.push_back(fileRoot);
// Now process any include files in the same translation unit
// first. When libclang is used this is much more efficient.
for (auto incFile : clangParser->filesInSameTU())
{
if (filesToProcess.find(incFile)!=filesToProcess.end())
{
bool needsToBeProcessed = false;
{
std::lock_guard<std::mutex> lock(processedFilesLock);
needsToBeProcessed = processedFiles.find(incFile)==processedFiles.end();
if (needsToBeProcessed) processedFiles.insert(incFile);
}
if (incFile!=s && needsToBeProcessed)
{
FileDef *ifd=findFileDef(Doxygen::inputNameLinkedMap,incFile.c_str(),ambig_l);
if (ifd && !ifd->isReference())
{
//printf(" Processing %s in same translation unit as %s\n",incFile,s->c_str());
fileRoot = parseFile(*parser.get(),ifd,incFile.c_str(),clangParser.get(),false);
roots.push_back(fileRoot);
}
}
}
}
return roots;
};
// dispatch the work and collect the future results
results.emplace_back(threadPool.queue(processFile));
}
}
// synchronize with the Entry result lists produced and add them to the root
for (auto &f : results)
{
auto l = f.get();
for (auto &e : l)
{
root->moveToSubEntryAndKeep(e);
}
}
// process remaining files
results.clear();
for (const auto &s : g_inputFiles)
{
if (processedFiles.find(s)==processedFiles.end()) // not yet processed
{
// lambda representing the work to executed by a thread
auto processFile = [s]() {
bool ambig = false;
std::vector< std::shared_ptr<Entry> > roots;
FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,s.c_str(),ambig);
auto parser { getParserForFile(s.c_str()) };
bool useClang = getLanguageFromFileName(s.c_str())==SrcLangExt::Cpp;
if (useClang)
{
auto clangParser = ClangParser::instance()->createTUParser(fd);
auto fileRoot = parseFile(*parser.get(),fd,s.c_str(),clangParser.get(),true);
roots.push_back(fileRoot);
}
else
{
auto fileRoot = parseFile(*parser.get(),fd,s.c_str(),nullptr,true);
roots.push_back(fileRoot);
}
return roots;
};
results.emplace_back(threadPool.queue(processFile));
}
}
// synchronize with the Entry result lists produced and add them to the root
for (auto &f : results)
{
auto l = f.get();
for (auto &e : l)
{
root->moveToSubEntryAndKeep(e);
}
}
}
else // normal processing
#endif
{
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
msg("Processing input using %zu threads.\n",numThreads);
ThreadPool threadPool(numThreads);
using FutureType = std::shared_ptr<Entry>;
std::vector< std::future< FutureType > > results;
for (const auto &s : g_inputFiles)
{
// lambda representing the work to executed by a thread
auto processFile = [s]() {
bool ambig = false;
FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,s.c_str(),ambig);
auto parser = getParserForFile(s.c_str());
auto fileRoot = parseFile(*parser.get(),fd,s.c_str(),nullptr,true);
return fileRoot;
};
// dispatch the work and collect the future results
results.emplace_back(threadPool.queue(processFile));
}
// synchronize with the Entry results produced and add them to the root
for (auto &f : results)
{
root->moveToSubEntryAndKeep(f.get());
}
}
}
//! parse the list of input files
static void parseFilesSingleThreading(const std::shared_ptr<Entry> &root)
{
AUTO_TRACE();
#if USE_LIBCLANG
if (Doxygen::clangAssistedParsing)
{
StringUnorderedSet processedFiles;
// create a dictionary with files to process
StringUnorderedSet filesToProcess;
for (const auto &s : g_inputFiles)
{
filesToProcess.insert(s);
}
// process source files (and their include dependencies)
for (const auto &s : g_inputFiles)
{
bool ambig = false;
FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,s.c_str(),ambig);
ASSERT(fd!=nullptr);
if (fd->isSource() && !fd->isReference() && getLanguageFromFileName(s.c_str())==SrcLangExt::Cpp) // this is a source file
{
auto clangParser = ClangParser::instance()->createTUParser(fd);
auto parser { getParserForFile(s.c_str()) };
auto fileRoot = parseFile(*parser.get(),fd,s.c_str(),clangParser.get(),true);
root->moveToSubEntryAndKeep(fileRoot);
processedFiles.insert(s);
// Now process any include files in the same translation unit
// first. When libclang is used this is much more efficient.
for (auto incFile : clangParser->filesInSameTU())
{
//printf(" file %s\n",incFile.c_str());
if (filesToProcess.find(incFile)!=filesToProcess.end() && // file need to be processed
processedFiles.find(incFile)==processedFiles.end()) // and is not processed already
{
FileDef *ifd=findFileDef(Doxygen::inputNameLinkedMap,incFile.c_str(),ambig);
if (ifd && !ifd->isReference())
{
//printf(" Processing %s in same translation unit as %s\n",incFile.c_str(),s.c_str());
fileRoot = parseFile(*parser.get(),ifd,incFile.c_str(),clangParser.get(),false);
root->moveToSubEntryAndKeep(fileRoot);
processedFiles.insert(incFile);
}
}
}
}
}
// process remaining files
for (const auto &s : g_inputFiles)
{
if (processedFiles.find(s)==processedFiles.end()) // not yet processed
{
bool ambig = false;
FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,s.c_str(),ambig);
if (getLanguageFromFileName(s.c_str())==SrcLangExt::Cpp) // not yet processed
{
auto clangParser = ClangParser::instance()->createTUParser(fd);
auto parser { getParserForFile(s.c_str()) };
auto fileRoot = parseFile(*parser.get(),fd,s.c_str(),clangParser.get(),true);
root->moveToSubEntryAndKeep(fileRoot);
}
else
{
std::unique_ptr<OutlineParserInterface> parser { getParserForFile(s.c_str()) };
std::shared_ptr<Entry> fileRoot = parseFile(*parser.get(),fd,s.c_str(),nullptr,true);
root->moveToSubEntryAndKeep(fileRoot);
}
processedFiles.insert(s);
}
}
}
else // normal processing
#endif
{
for (const auto &s : g_inputFiles)
{
bool ambig = false;
FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,s.c_str(),ambig);
ASSERT(fd!=nullptr);
std::unique_ptr<OutlineParserInterface> parser { getParserForFile(s.c_str()) };
std::shared_ptr<Entry> fileRoot = parseFile(*parser.get(),fd,s.c_str(),nullptr,true);
root->moveToSubEntryAndKeep(std::move(fileRoot));
}
}
}
// resolves a path that may include symlinks, if a recursive symlink is
// found an empty string is returned.
static std::string resolveSymlink(const std::string &path)
{
int sepPos=0;
int oldPos=0;
StringUnorderedSet nonSymlinks;
StringUnorderedSet known;
QCString result(path);
QCString oldPrefix = "/";
do
{
#if defined(_WIN32)
// UNC path, skip server and share name
if (sepPos==0 && (result.startsWith("//") || result.startsWith("\\\\")))
sepPos = result.find('/',2);
if (sepPos!=-1)
sepPos = result.find('/',sepPos+1);
#else
sepPos = result.find('/',sepPos+1);
#endif
QCString prefix = sepPos==-1 ? result : result.left(sepPos);
if (nonSymlinks.find(prefix.str())==nonSymlinks.end())
{
FileInfo fi(prefix.str());
if (fi.isSymLink())
{
QCString target = fi.readLink();
bool isRelative = FileInfo(target.str()).isRelative();
if (isRelative)
{
target = Dir::cleanDirPath(oldPrefix.str()+"/"+target.str());
}
if (sepPos!=-1)
{
if (fi.isDir() && target.length()>0 && target.at(target.length()-1)!='/')
{
target+='/';
}
target+=result.mid(sepPos);
}
result = Dir::cleanDirPath(target.str());
if (known.find(result.str())!=known.end()) return std::string(); // recursive symlink!
known.insert(result.str());
if (isRelative)
{
sepPos = oldPos;
}
else // link to absolute path
{
sepPos = 0;
oldPrefix = "/";
}
}
else
{
nonSymlinks.insert(prefix.str());
oldPrefix = prefix;
}
oldPos = sepPos;
}
}
while (sepPos!=-1);
return Dir::cleanDirPath(result.str());
}
static StringUnorderedSet g_pathsVisited(1009);
//----------------------------------------------------------------------------
// Read all files matching at least one pattern in 'patList' in the
// directory represented by 'fi'.
// The directory is read iff the recursiveFlag is set.
// The contents of all files is append to the input string
static void readDir(FileInfo *fi,
FileNameLinkedMap *fnMap,
StringUnorderedSet *exclSet,
const StringVector *patList,
const StringVector *exclPatList,
StringVector *resultList,
StringUnorderedSet *resultSet,
bool errorIfNotExist,
bool recursive,
StringUnorderedSet *killSet,
StringUnorderedSet *paths
)
{
std::string dirName = fi->absFilePath();
if (paths && !dirName.empty())
{
paths->insert(dirName);
}
//printf("%s isSymLink()=%d\n",qPrint(dirName),fi->isSymLink());
if (fi->isSymLink())
{
dirName = resolveSymlink(dirName);
if (dirName.empty())
{
//printf("RECURSIVE SYMLINK: %s\n",qPrint(dirName));
return; // recursive symlink
}
}
if (g_pathsVisited.find(dirName)!=g_pathsVisited.end())
{
//printf("PATH ALREADY VISITED: %s\n",qPrint(dirName));
return; // already visited path
}
g_pathsVisited.insert(dirName);
Dir dir(dirName);
msg("Searching for files in directory %s\n", qPrint(fi->absFilePath()));
//printf("killSet=%p count=%d\n",killSet,killSet ? (int)killSet->count() : -1);
StringVector dirResultList;
for (const auto &dirEntry : dir.iterator())
{
FileInfo cfi(dirEntry.path());
if (exclSet==nullptr || exclSet->find(cfi.absFilePath())==exclSet->end())
{ // file should not be excluded
//printf("killSet->find(%s)\n",qPrint(cfi->absFilePath()));
if (Config_getBool(EXCLUDE_SYMLINKS) && cfi.isSymLink())
{
}
else if (!cfi.exists() || !cfi.isReadable())
{
if (errorIfNotExist)
{
warn_uncond("source '%s' is not a readable file or directory... skipping.\n",cfi.absFilePath().c_str());
}
}
else if (cfi.isFile() &&
(patList==nullptr || patternMatch(cfi,*patList)) &&
(exclPatList==nullptr || !patternMatch(cfi,*exclPatList)) &&
(killSet==nullptr || killSet->find(cfi.absFilePath())==killSet->end())
)
{
std::string name=cfi.fileName();
std::string path=cfi.dirPath()+"/";
std::string fullName=path+name;
if (fnMap)
{
auto fd = createFileDef(QCString(path),QCString(name));
FileName *fn=nullptr;
if (!name.empty())
{
fn = fnMap->add(QCString(name),QCString(fullName));
fn->push_back(std::move(fd));
}
}
dirResultList.push_back(fullName);
if (resultSet) resultSet->insert(fullName);
if (killSet) killSet->insert(fullName);
}
else if (recursive &&
cfi.isDir() &&
(exclPatList==nullptr || !patternMatch(cfi,*exclPatList)) &&
cfi.fileName().at(0)!='.') // skip "." ".." and ".dir"
{
FileInfo acfi(cfi.absFilePath());
readDir(&acfi,fnMap,exclSet,
patList,exclPatList,&dirResultList,resultSet,errorIfNotExist,
recursive,killSet,paths);
}
}
}
if (resultList && !dirResultList.empty())
{
// sort the resulting list to make the order platform independent.
std::stable_sort(dirResultList.begin(),
dirResultList.end(),
[](const auto &f1,const auto &f2) { return qstricmp_sort(f1.c_str(),f2.c_str())<0; });
// append the sorted results to resultList
resultList->insert(resultList->end(), dirResultList.begin(), dirResultList.end());
}
}
//----------------------------------------------------------------------------
// read a file or all files in a directory and append their contents to the
// input string. The names of the files are appended to the 'fiList' list.
void readFileOrDirectory(const QCString &s,
FileNameLinkedMap *fnMap,
StringUnorderedSet *exclSet,
const StringVector *patList,
const StringVector *exclPatList,
StringVector *resultList,
StringUnorderedSet *resultSet,
bool recursive,
bool errorIfNotExist,
StringUnorderedSet *killSet,
StringUnorderedSet *paths
)
{
//printf("killSet count=%d\n",killSet ? (int)killSet->size() : -1);
// strip trailing slashes
if (s.isEmpty()) return;
g_pathsVisited.clear();
FileInfo fi(s.str());
//printf("readFileOrDirectory(%s)\n",s);
{
if (exclSet==nullptr || exclSet->find(fi.absFilePath())==exclSet->end())
{
if (Config_getBool(EXCLUDE_SYMLINKS) && fi.isSymLink())
{
}
else if (!fi.exists() || !fi.isReadable())
{
if (errorIfNotExist)
{
warn_uncond("source '%s' is not a readable file or directory... skipping.\n",qPrint(s));
}
}
else if (fi.isFile())
{
std::string dirPath = fi.dirPath(true);
std::string filePath = fi.absFilePath();
if (paths && !dirPath.empty())
{
paths->insert(dirPath);
}
//printf("killSet.find(%s)=%d\n",qPrint(fi.absFilePath()),killSet.find(fi.absFilePath())!=killSet.end());
if (killSet==nullptr || killSet->find(filePath)==killSet->end())
{
std::string name=fi.fileName();
if (fnMap)
{
auto fd = createFileDef(QCString(dirPath+"/"),QCString(name));
if (!name.empty())
{
FileName *fn = fnMap->add(QCString(name),QCString(filePath));
fn->push_back(std::move(fd));
}
}
if (resultList || resultSet)
{
if (resultList) resultList->push_back(filePath);
if (resultSet) resultSet->insert(filePath);
}
if (killSet) killSet->insert(fi.absFilePath());
}
}
else if (fi.isDir()) // readable dir
{
readDir(&fi,fnMap,exclSet,patList,
exclPatList,resultList,resultSet,errorIfNotExist,
recursive,killSet,paths);
}
}
}
}
//----------------------------------------------------------------------------
static void dumpSymbol(TextStream &t,Definition *d)
{
QCString anchor;
if (d->definitionType()==Definition::TypeMember)
{
MemberDef *md = toMemberDef(d);
anchor=":"+md->anchor();
}
QCString scope;
QCString fn = d->getOutputFileBase();
addHtmlExtensionIfMissing(fn);
if (d->getOuterScope() && d->getOuterScope()!=Doxygen::globalScope)
{
scope = fn;
}
t << "REPLACE INTO symbols (symbol_id,scope_id,name,file,line) VALUES('"
<< fn+anchor << "','"
<< scope << "','"
<< d->name() << "','"
<< d->getDefFileName() << "','"
<< d->getDefLine()
<< "');\n";
}
static void dumpSymbolMap()
{
std::ofstream f = Portable::openOutputStream("symbols.sql");
if (f.is_open())
{
TextStream t(&f);
for (const auto &[name,symList] : *Doxygen::symbolMap)
{
for (const auto &def : symList)
{
dumpSymbol(t,def);
}
}
}
}
// print developer options of Doxygen
static void devUsage()
{
Debug::clearFlag(Debug::Time);
msg("Developer parameters:\n");
msg(" -m dump symbol map\n");
msg(" -b making messages output unbuffered\n");
#if ENABLE_TRACING
msg(" -t [<file|stdout|stderr>] trace debug info to file, stdout, or stderr (default file stdout)\n");
msg(" -t_time [<file|stdout|stderr>] trace debug info to file, stdout, or stderr (default file stdout),\n"
" and include time and thread information\n");
#endif
msg(" -d <level> enable a debug level, such as (multiple invocations of -d are possible):\n");
Debug::printFlags();
}
//----------------------------------------------------------------------------
// print the version of Doxygen
static void version(const bool extended)
{
Debug::clearFlag(Debug::Time);
QCString versionString = getFullVersion();
msg("%s\n",qPrint(versionString));
if (extended)
{
QCString extVers;
if (!extVers.isEmpty()) extVers+= ", ";
extVers += "sqlite3 ";
extVers += sqlite3_libversion();
#if USE_LIBCLANG
if (!extVers.isEmpty()) extVers+= ", ";
extVers += "clang support ";
extVers += CLANG_VERSION_STRING;
#endif
if (!extVers.isEmpty())
{
int lastComma = extVers.findRev(',');
if (lastComma != -1) extVers = extVers.replace(lastComma,1," and");
msg(" with %s.\n",qPrint(extVers));
}
}
}
//----------------------------------------------------------------------------
// print the usage of Doxygen
static void usage(const QCString &name,const QCString &versionString)
{
Debug::clearFlag(Debug::Time);
msg("Doxygen version %s\nCopyright Dimitri van Heesch 1997-2024\n\n",qPrint(versionString));
msg("You can use Doxygen in a number of ways:\n\n");
msg("1) Use Doxygen to generate a template configuration file*:\n");
msg(" %s [-s] -g [configName]\n\n",qPrint(name));
msg("2) Use Doxygen to update an old configuration file*:\n");
msg(" %s [-s] -u [configName]\n\n",qPrint(name));
msg("3) Use Doxygen to generate documentation using an existing ");
msg("configuration file*:\n");
msg(" %s [configName]\n\n",qPrint(name));
msg("4) Use Doxygen to generate a template file controlling the layout of the\n");
msg(" generated documentation:\n");
msg(" %s -l [layoutFileName]\n\n",qPrint(name));
msg(" In case layoutFileName is omitted DoxygenLayout.xml will be used as filename.\n");
msg(" If - is used for layoutFileName Doxygen will write to standard output.\n\n");
msg("5) Use Doxygen to generate a template style sheet file for RTF, HTML or Latex.\n");
msg(" RTF: %s -w rtf styleSheetFile\n",qPrint(name));
msg(" HTML: %s -w html headerFile footerFile styleSheetFile [configFile]\n",qPrint(name));
msg(" LaTeX: %s -w latex headerFile footerFile styleSheetFile [configFile]\n\n",qPrint(name));
msg("6) Use Doxygen to generate a rtf extensions file\n");
msg(" %s -e rtf extensionsFile\n\n",qPrint(name));
msg(" If - is used for extensionsFile Doxygen will write to standard output.\n\n");
msg("7) Use Doxygen to compare the used configuration file with the template configuration file\n");
msg(" %s -x [configFile]\n\n",qPrint(name));
msg(" Use Doxygen to compare the used configuration file with the template configuration file\n");
msg(" without replacing the environment variables or CMake type replacement variables\n");
msg(" %s -x_noenv [configFile]\n\n",qPrint(name));
msg("8) Use Doxygen to show a list of built-in emojis.\n");
msg(" %s -f emoji outputFileName\n\n",qPrint(name));
msg(" If - is used for outputFileName Doxygen will write to standard output.\n\n");
msg("*) If -s is specified the comments of the configuration items in the config file will be omitted.\n");
msg(" If configName is omitted 'Doxyfile' will be used as a default.\n");
msg(" If - is used for configFile Doxygen will write / read the configuration to /from standard output / input.\n\n");
msg("If -q is used for a Doxygen documentation run, Doxygen will see this as if QUIET=YES has been set.\n\n");
msg("-v print version string, -V print extended version information\n");
msg("-h,-? prints usage help information\n");
msg("%s -d prints additional usage flags for debugging purposes\n",qPrint(name));
}
//----------------------------------------------------------------------------
// read the argument of option 'c' from the comment argument list and
// update the option index 'optInd'.
static const char *getArg(int argc,char **argv,int &optInd)
{
char *s=nullptr;
if (qstrlen(&argv[optInd][2])>0)
s=&argv[optInd][2];
else if (optInd+1<argc && argv[optInd+1][0]!='-')
s=argv[++optInd];
return s;
}
//----------------------------------------------------------------------------
/** @brief /dev/null outline parser */
class NullOutlineParser : public OutlineParserInterface
{
public:
void parseInput(const QCString &/* file */, const char * /* buf */,const std::shared_ptr<Entry> &, ClangTUParser*) override {}
bool needsPreprocessing(const QCString &) const override { return FALSE; }
void parsePrototype(const QCString &) override {}
};
template<class T> std::function< std::unique_ptr<T>() > make_parser_factory()
{
return []() { return std::make_unique<T>(); };
}
void initDoxygen()
{
initResources();
QCString lang = Portable::getenv("LC_ALL");
if (!lang.isEmpty()) Portable::setenv("LANG",lang);
std::setlocale(LC_ALL,"");
std::setlocale(LC_CTYPE,"C"); // to get isspace(0xA0)==0, needed for UTF-8
std::setlocale(LC_NUMERIC,"C");
Doxygen::symbolMap = new SymbolMap<Definition>;
Debug::startTimer();
Doxygen::parserManager = new ParserManager( make_parser_factory<NullOutlineParser>(),
make_parser_factory<FileCodeParser>());
Doxygen::parserManager->registerParser("c", make_parser_factory<COutlineParser>(),
make_parser_factory<CCodeParser>());
Doxygen::parserManager->registerParser("python", make_parser_factory<PythonOutlineParser>(),
make_parser_factory<PythonCodeParser>());
Doxygen::parserManager->registerParser("fortran", make_parser_factory<FortranOutlineParser>(),
make_parser_factory<FortranCodeParser>());
Doxygen::parserManager->registerParser("fortranfree", make_parser_factory<FortranOutlineParserFree>(),
make_parser_factory<FortranCodeParserFree>());
Doxygen::parserManager->registerParser("fortranfixed", make_parser_factory<FortranOutlineParserFixed>(),
make_parser_factory<FortranCodeParserFixed>());
Doxygen::parserManager->registerParser("vhdl", make_parser_factory<VHDLOutlineParser>(),
make_parser_factory<VHDLCodeParser>());
Doxygen::parserManager->registerParser("xml", make_parser_factory<NullOutlineParser>(),
make_parser_factory<XMLCodeParser>());
Doxygen::parserManager->registerParser("sql", make_parser_factory<NullOutlineParser>(),
make_parser_factory<SQLCodeParser>());
Doxygen::parserManager->registerParser("md", make_parser_factory<MarkdownOutlineParser>(),
make_parser_factory<FileCodeParser>());
Doxygen::parserManager->registerParser("lex", make_parser_factory<LexOutlineParser>(),
make_parser_factory<LexCodeParser>());
// register any additional parsers here...
initDefaultExtensionMapping();
#if USE_LIBCLANG
Doxygen::clangUsrMap = new ClangUsrMap;
#endif
Doxygen::memberNameLinkedMap = new MemberNameLinkedMap;
Doxygen::functionNameLinkedMap = new MemberNameLinkedMap;
Doxygen::groupLinkedMap = new GroupLinkedMap;
Doxygen::namespaceLinkedMap = new NamespaceLinkedMap;
Doxygen::classLinkedMap = new ClassLinkedMap;
Doxygen::hiddenClassLinkedMap = new ClassLinkedMap;
Doxygen::conceptLinkedMap = new ConceptLinkedMap;
Doxygen::dirLinkedMap = new DirLinkedMap;
Doxygen::pageLinkedMap = new PageLinkedMap; // all doc pages
Doxygen::exampleLinkedMap = new PageLinkedMap; // all examples
//Doxygen::tagDestinationDict.setAutoDelete(TRUE);
Doxygen::indexList = new IndexList;
// initialization of these globals depends on
// configuration switches so we need to postpone these
Doxygen::globalScope = nullptr;
Doxygen::inputNameLinkedMap = nullptr;
Doxygen::includeNameLinkedMap = nullptr;
Doxygen::exampleNameLinkedMap = nullptr;
Doxygen::imageNameLinkedMap = nullptr;
Doxygen::dotFileNameLinkedMap = nullptr;
Doxygen::mscFileNameLinkedMap = nullptr;
Doxygen::diaFileNameLinkedMap = nullptr;
Doxygen::plantUmlFileNameLinkedMap = nullptr;
}
void cleanUpDoxygen()
{
FormulaManager::instance().clear();
SectionManager::instance().clear();
ModuleManager::instance().clear();
delete Doxygen::indexList;
delete Doxygen::inputNameLinkedMap;
delete Doxygen::includeNameLinkedMap;
delete Doxygen::exampleNameLinkedMap;
delete Doxygen::imageNameLinkedMap;
delete Doxygen::dotFileNameLinkedMap;
delete Doxygen::mscFileNameLinkedMap;
delete Doxygen::diaFileNameLinkedMap;
delete Doxygen::plantUmlFileNameLinkedMap;
Doxygen::mainPage.reset();
delete Doxygen::pageLinkedMap;
delete Doxygen::exampleLinkedMap;
Doxygen::globalNamespaceDef.reset();
Doxygen::globalScope = nullptr;
delete Doxygen::parserManager;
delete theTranslator;
delete g_outputList;
delete Doxygen::memberNameLinkedMap;
delete Doxygen::functionNameLinkedMap;
delete Doxygen::groupLinkedMap;
delete Doxygen::namespaceLinkedMap;
delete Doxygen::dirLinkedMap;
delete Doxygen::symbolMap;
}
static int computeIdealCacheParam(size_t v)
{
//printf("computeIdealCacheParam(v=%u)\n",v);
int r=0;
while (v!=0) v>>=1,r++;
// r = log2(v)
// convert to a valid cache size value
return std::max(0,std::min(r-16,9));
}
void readConfiguration(int argc, char **argv)
{
QCString versionString = getFullVersion();
// helper that calls \a func to write to file \a fileName via a TextStream
auto writeFile = [](const char *fileName,std::function<void(TextStream&)> func) -> bool
{
std::ofstream f;
if (openOutputFile(fileName,f))
{
TextStream t(&f);
func(t);
return true;
}
return false;
};
/**************************************************************************
* Handle arguments *
**************************************************************************/
int optInd=1;
QCString configName;
QCString traceName;
bool genConfig=false;
bool shortList=false;
bool traceTiming=false;
Config::CompareMode diffList=Config::CompareMode::Full;
bool updateConfig=false;
bool quiet = false;
while (optInd<argc && argv[optInd][0]=='-' &&
(isalpha(argv[optInd][1]) || argv[optInd][1]=='?' ||
argv[optInd][1]=='-')
)
{
switch(argv[optInd][1])
{
case 'g':
{
genConfig=TRUE;
}
break;
case 'l':
{
QCString layoutName;
if (optInd+1>=argc)
{
layoutName="DoxygenLayout.xml";
}
else
{
layoutName=argv[optInd+1];
}
writeDefaultLayoutFile(layoutName);
cleanUpDoxygen();
exit(0);
}
break;
case 'd':
{
QCString debugLabel=getArg(argc,argv,optInd);
if (debugLabel.isEmpty())
{
devUsage();
cleanUpDoxygen();
exit(0);
}
int retVal = Debug::setFlagStr(debugLabel);
if (!retVal)
{
err("option \"-d\" has unknown debug specifier: \"%s\".\n",qPrint(debugLabel));
devUsage();
cleanUpDoxygen();
exit(1);
}
}
break;
case 't':
{
#if ENABLE_TRACING
if (!strcmp(argv[optInd]+1,"t_time"))
{
traceTiming = true;
}
else if (!strcmp(argv[optInd]+1,"t"))
{
traceTiming = false;
}
else
{
err("option should be \"-t\" or \"-t_time\", found: \"%s\".\n",argv[optInd]);
cleanUpDoxygen();
exit(1);
}
if (optInd+1>=argc || argv[optInd+1][0] == '-') // no file name given
{
traceName="stdout";
}
else
{
traceName=argv[optInd+1];
optInd++;
}
#else
err("support for option \"-t\" has not been compiled in (use a debug build or a release build with tracing enabled).\n");
cleanUpDoxygen();
exit(1);
#endif
}
break;
case 'x':
if (!strcmp(argv[optInd]+1,"x_noenv")) diffList=Config::CompareMode::CompressedNoEnv;
else if (!strcmp(argv[optInd]+1,"x")) diffList=Config::CompareMode::Compressed;
else
{
err("option should be \"-x\" or \"-x_noenv\", found: \"%s\".\n",argv[optInd]);
cleanUpDoxygen();
exit(1);
}
break;
case 's':
shortList=TRUE;
break;
case 'u':
updateConfig=TRUE;
break;
case 'e':
{
QCString formatName=getArg(argc,argv,optInd);
if (formatName.isEmpty())
{
err("option \"-e\" is missing format specifier rtf.\n");
cleanUpDoxygen();
exit(1);
}
if (qstricmp(formatName.data(),"rtf")==0)
{
if (optInd+1>=argc)
{
err("option \"-e rtf\" is missing an extensions file name\n");
cleanUpDoxygen();
exit(1);
}
writeFile(argv[optInd+1],RTFGenerator::writeExtensionsFile);
cleanUpDoxygen();
exit(0);
}
err("option \"-e\" has invalid format specifier.\n");
cleanUpDoxygen();
exit(1);
}
break;
case 'f':
{
QCString listName=getArg(argc,argv,optInd);
if (listName.isEmpty())
{
err("option \"-f\" is missing list specifier.\n");
cleanUpDoxygen();
exit(1);
}
if (qstricmp(listName.data(),"emoji")==0)
{
if (optInd+1>=argc)
{
err("option \"-f emoji\" is missing an output file name\n");
cleanUpDoxygen();
exit(1);
}
writeFile(argv[optInd+1],[](TextStream &t) { EmojiEntityMapper::instance().writeEmojiFile(t); });
cleanUpDoxygen();
exit(0);
}
err("option \"-f\" has invalid list specifier.\n");
cleanUpDoxygen();
exit(1);
}
break;
case 'w':
{
QCString formatName=getArg(argc,argv,optInd);
if (formatName.isEmpty())
{
err("option \"-w\" is missing format specifier rtf, html or latex\n");
cleanUpDoxygen();
exit(1);
}
if (qstricmp(formatName.data(),"rtf")==0)
{
if (optInd+1>=argc)
{
err("option \"-w rtf\" is missing a style sheet file name\n");
cleanUpDoxygen();
exit(1);
}
if (!writeFile(argv[optInd+1],RTFGenerator::writeStyleSheetFile))
{
err("error opening RTF style sheet file %s!\n",argv[optInd+1]);
cleanUpDoxygen();
exit(1);
}
cleanUpDoxygen();
exit(0);
}
else if (qstricmp(formatName.data(),"html")==0)
{
Config::init();
if (optInd+4<argc || FileInfo("Doxyfile").exists() || FileInfo("doxyfile").exists())
// explicit config file mentioned or default found on disk
{
QCString df = optInd+4<argc ? argv[optInd+4] : (FileInfo("Doxyfile").exists() ? QCString("Doxyfile") : QCString("doxyfile"));
if (!Config::parse(df)) // parse the config file
{
err("error opening or reading configuration file %s!\n",argv[optInd+4]);
cleanUpDoxygen();
exit(1);
}
}
if (optInd+3>=argc)
{
err("option \"-w html\" does not have enough arguments\n");
cleanUpDoxygen();
exit(1);
}
Config::postProcess(TRUE);
Config::updateObsolete();
Config::checkAndCorrect(Config_getBool(QUIET), false);
setTranslator(Config_getEnum(OUTPUT_LANGUAGE));
writeFile(argv[optInd+1],[&](TextStream &t) { HtmlGenerator::writeHeaderFile(t,argv[optInd+3]); });
writeFile(argv[optInd+2],HtmlGenerator::writeFooterFile);
writeFile(argv[optInd+3],HtmlGenerator::writeStyleSheetFile);
cleanUpDoxygen();
exit(0);
}
else if (qstricmp(formatName.data(),"latex")==0)
{
Config::init();
if (optInd+4<argc || FileInfo("Doxyfile").exists() || FileInfo("doxyfile").exists())
{
QCString df = optInd+4<argc ? argv[optInd+4] : (FileInfo("Doxyfile").exists() ? QCString("Doxyfile") : QCString("doxyfile"));
if (!Config::parse(df))
{
err("error opening or reading configuration file %s!\n",argv[optInd+4]);
cleanUpDoxygen();
exit(1);
}
}
if (optInd+3>=argc)
{
err("option \"-w latex\" does not have enough arguments\n");
cleanUpDoxygen();
exit(1);
}
Config::postProcess(TRUE);
Config::updateObsolete();
Config::checkAndCorrect(Config_getBool(QUIET), false);
setTranslator(Config_getEnum(OUTPUT_LANGUAGE));
writeFile(argv[optInd+1],LatexGenerator::writeHeaderFile);
writeFile(argv[optInd+2],LatexGenerator::writeFooterFile);
writeFile(argv[optInd+3],LatexGenerator::writeStyleSheetFile);
cleanUpDoxygen();
exit(0);
}
else
{
err("Illegal format specifier \"%s\": should be one of rtf, html or latex\n",qPrint(formatName));
cleanUpDoxygen();
exit(1);
}
}
break;
case 'm':
g_dumpSymbolMap = TRUE;
break;
case 'v':
version(false);
cleanUpDoxygen();
exit(0);
break;
case 'V':
version(true);
cleanUpDoxygen();
exit(0);
break;
case '-':
if (qstrcmp(&argv[optInd][2],"help")==0)
{
usage(argv[0],versionString);
exit(0);
}
else if (qstrcmp(&argv[optInd][2],"version")==0)
{
version(false);
cleanUpDoxygen();
exit(0);
}
else if ((qstrcmp(&argv[optInd][2],"Version")==0) ||
(qstrcmp(&argv[optInd][2],"VERSION")==0))
{
version(true);
cleanUpDoxygen();
exit(0);
}
else
{
err("Unknown option \"-%s\"\n",&argv[optInd][1]);
usage(argv[0],versionString);
exit(1);
}
break;
case 'b':
setvbuf(stdout,nullptr,_IONBF,0);
break;
case 'q':
quiet = true;
break;
case 'h':
case '?':
usage(argv[0],versionString);
exit(0);
break;
default:
err("Unknown option \"-%c\"\n",argv[optInd][1]);
usage(argv[0],versionString);
exit(1);
}
optInd++;
}
/**************************************************************************
* Parse or generate the config file *
**************************************************************************/
initTracing(traceName.data(),traceTiming);
TRACE("Doxygen version used: {}",getFullVersion());
Config::init();
FileInfo configFileInfo1("Doxyfile"),configFileInfo2("doxyfile");
if (optInd>=argc)
{
if (configFileInfo1.exists())
{
configName="Doxyfile";
}
else if (configFileInfo2.exists())
{
configName="doxyfile";
}
else if (genConfig)
{
configName="Doxyfile";
}
else
{
err("Doxyfile not found and no input file specified!\n");
usage(argv[0],versionString);
exit(1);
}
}
else
{
FileInfo fi(argv[optInd]);
if (fi.exists() || qstrcmp(argv[optInd],"-")==0 || genConfig)
{
configName=argv[optInd];
}
else
{
err("configuration file %s not found!\n",argv[optInd]);
usage(argv[0],versionString);
exit(1);
}
}
if (genConfig)
{
generateConfigFile(configName,shortList);
cleanUpDoxygen();
exit(0);
}
if (!Config::parse(configName,updateConfig,diffList))
{
err("could not open or read configuration file %s!\n",qPrint(configName));
cleanUpDoxygen();
exit(1);
}
if (diffList!=Config::CompareMode::Full)
{
Config::updateObsolete();
compareDoxyfile(diffList);
cleanUpDoxygen();
exit(0);
}
if (updateConfig)
{
Config::updateObsolete();
generateConfigFile(configName,shortList,TRUE);
cleanUpDoxygen();
exit(0);
}
/* Perlmod wants to know the path to the config file.*/
FileInfo configFileInfo(configName.str());
setPerlModDoxyfile(configFileInfo.absFilePath());
/* handle -q option */
if (quiet) Config_updateBool(QUIET,TRUE);
}
/** check and resolve config options */
void checkConfiguration()
{
AUTO_TRACE();
Config::postProcess(FALSE);
Config::updateObsolete();
Config::checkAndCorrect(Config_getBool(QUIET), true);
initWarningFormat();
}
/** adjust globals that depend on configuration settings. */
void adjustConfiguration()
{
AUTO_TRACE();
Doxygen::globalNamespaceDef = createNamespaceDef("<globalScope>",1,1,"<globalScope>");
Doxygen::globalScope = toNamespaceDefMutable(Doxygen::globalNamespaceDef.get());
Doxygen::inputNameLinkedMap = new FileNameLinkedMap;
Doxygen::includeNameLinkedMap = new FileNameLinkedMap;
Doxygen::exampleNameLinkedMap = new FileNameLinkedMap;
Doxygen::imageNameLinkedMap = new FileNameLinkedMap;
Doxygen::dotFileNameLinkedMap = new FileNameLinkedMap;
Doxygen::mscFileNameLinkedMap = new FileNameLinkedMap;
Doxygen::diaFileNameLinkedMap = new FileNameLinkedMap;
Doxygen::plantUmlFileNameLinkedMap = new FileNameLinkedMap;
setTranslator(Config_getEnum(OUTPUT_LANGUAGE));
/* Set the global html file extension. */
Doxygen::htmlFileExtension = Config_getString(HTML_FILE_EXTENSION);
Doxygen::parseSourcesNeeded = Config_getBool(CALL_GRAPH) ||
Config_getBool(CALLER_GRAPH) ||
Config_getBool(REFERENCES_RELATION) ||
Config_getBool(REFERENCED_BY_RELATION);
/**************************************************************************
* Add custom extension mappings
**************************************************************************/
const StringVector &extMaps = Config_getList(EXTENSION_MAPPING);
for (const auto &mapping : extMaps)
{
QCString mapStr = mapping.c_str();
int i=mapStr.find('=');
if (i==-1)
{
continue;
}
else
{
QCString ext = mapStr.left(i).stripWhiteSpace().lower();
QCString language = mapStr.mid(i+1).stripWhiteSpace().lower();
if (ext.isEmpty() || language.isEmpty())
{
continue;
}
if (!updateLanguageMapping(ext,language))
{
err("Failed to map file extension '%s' to unsupported language '%s'.\n"
"Check the EXTENSION_MAPPING setting in the config file.\n",
qPrint(ext),qPrint(language));
}
else
{
msg("Adding custom extension mapping: '%s' will be treated as language '%s'\n",
qPrint(ext),qPrint(language));
}
}
}
// create input file exncodings
// check INPUT_ENCODING
void *cd = portable_iconv_open("UTF-8",Config_getString(INPUT_ENCODING).data());
if (cd==reinterpret_cast<void *>(-1))
{
term("unsupported character conversion: '%s'->'%s': %s\n"
"Check the 'INPUT_ENCODING' setting in the config file!\n",
qPrint(Config_getString(INPUT_ENCODING)),qPrint("UTF-8"),strerror(errno));
}
else
{
portable_iconv_close(cd);
}
// check and split INPUT_FILE_ENCODING
const StringVector &fileEncod = Config_getList(INPUT_FILE_ENCODING);
for (const auto &mapping : fileEncod)
{
QCString mapStr = mapping.c_str();
int i=mapStr.find('=');
if (i==-1)
{
continue;
}
else
{
QCString pattern = mapStr.left(i).stripWhiteSpace().lower();
QCString encoding = mapStr.mid(i+1).stripWhiteSpace().lower();
if (pattern.isEmpty() || encoding.isEmpty())
{
continue;
}
cd = portable_iconv_open("UTF-8",encoding.data());
if (cd==reinterpret_cast<void *>(-1))
{
term("unsupported character conversion: '%s'->'%s': %s\n"
"Check the 'INPUT_FILE_ENCODING' setting in the config file!\n",
qPrint(encoding),qPrint("UTF-8"),strerror(errno));
}
else
{
portable_iconv_close(cd);
}
Doxygen::inputFileEncodingList.emplace_back(pattern, encoding);
}
}
// add predefined macro name to a dictionary
const StringVector &expandAsDefinedList =Config_getList(EXPAND_AS_DEFINED);
for (const auto &s : expandAsDefinedList)
{
Doxygen::expandAsDefinedSet.insert(s.c_str());
}
// read aliases and store them in a dictionary
readAliases();
// store number of spaces in a tab into Doxygen::spaces
int tabSize = Config_getInt(TAB_SIZE);
Doxygen::spaces.resize(tabSize);
for (int sp=0; sp<tabSize; sp++) Doxygen::spaces.at(sp)=' ';
Doxygen::spaces.at(tabSize)='\0';
}
#ifdef HAS_SIGNALS
static void stopDoxygen(int)
{
signal(SIGINT,SIG_DFL); // Re-register signal handler for default action
Dir thisDir;
msg("Cleaning up...\n");
if (!Doxygen::filterDBFileName.isEmpty())
{
thisDir.remove(Doxygen::filterDBFileName.str());
}
killpg(0,SIGINT);
cleanUpDoxygen();
exitTracing();
exit(1);
}
#endif
static void writeTagFile()
{
QCString generateTagFile = Config_getString(GENERATE_TAGFILE);
if (generateTagFile.isEmpty()) return;
std::ofstream f = Portable::openOutputStream(generateTagFile);
if (!f.is_open())
{
err("cannot open tag file %s for writing\n",
qPrint(generateTagFile)
);
return;
}
TextStream tagFile(&f);
tagFile << "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\n";
tagFile << "<tagfile doxygen_version=\"" << getDoxygenVersion() << "\"";
std::string gitVersion = getGitVersion();
if (!gitVersion.empty())
{
tagFile << " doxygen_gitid=\"" << gitVersion << "\"";
}
tagFile << ">\n";
// for each file
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->isLinkableInProject()) fd->writeTagFile(tagFile);
}
}
// for each class
for (const auto &cd : *Doxygen::classLinkedMap)
{
ClassDefMutable *cdm = toClassDefMutable(cd.get());
if (cdm && cdm->isLinkableInProject())
{
cdm->writeTagFile(tagFile);
}
}
// for each concept
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
ConceptDefMutable *cdm = toConceptDefMutable(cd.get());
if (cdm && cdm->isLinkableInProject())
{
cdm->writeTagFile(tagFile);
}
}
// for each namespace
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
NamespaceDefMutable *ndm = toNamespaceDefMutable(nd.get());
if (ndm && nd->isLinkableInProject())
{
ndm->writeTagFile(tagFile);
}
}
// for each group
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (gd->isLinkableInProject()) gd->writeTagFile(tagFile);
}
// for each module
for (const auto &mod : ModuleManager::instance().modules())
{
if (mod->isLinkableInProject()) mod->writeTagFile(tagFile);
}
// for each page
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (pd->isLinkableInProject()) pd->writeTagFile(tagFile);
}
if (Doxygen::mainPage) Doxygen::mainPage->writeTagFile(tagFile);
tagFile << "</tagfile>\n";
}
static void exitDoxygen() noexcept
{
if (!g_successfulRun) // premature exit
{
Dir thisDir;
msg("Exiting...\n");
if (!Doxygen::filterDBFileName.isEmpty())
{
thisDir.remove(Doxygen::filterDBFileName.str());
}
}
}
static QCString createOutputDirectory(const QCString &baseDirName,
const QCString &formatDirName,
const char *defaultDirName)
{
QCString result = formatDirName;
if (result.isEmpty())
{
result = baseDirName + defaultDirName;
}
else if (formatDirName[0]!='/' && (formatDirName.length()==1 || formatDirName[1]!=':'))
{
result.prepend(baseDirName+"/");
}
Dir formatDir(result.str());
if (!formatDir.exists() && !formatDir.mkdir(result.str()))
{
term("Could not create output directory %s\n", qPrint(result));
}
return result;
}
void searchInputFiles()
{
StringUnorderedSet killSet;
const StringVector &exclPatterns = Config_getList(EXCLUDE_PATTERNS);
bool alwaysRecursive = Config_getBool(RECURSIVE);
StringUnorderedSet excludeNameSet;
// gather names of all files in the include path
g_s.begin("Searching for include files...\n");
killSet.clear();
const StringVector &includePathList = Config_getList(INCLUDE_PATH);
for (const auto &s : includePathList)
{
size_t plSize = Config_getList(INCLUDE_FILE_PATTERNS).size();
const StringVector &pl = plSize==0 ? Config_getList(FILE_PATTERNS) :
Config_getList(INCLUDE_FILE_PATTERNS);
readFileOrDirectory(s.c_str(), // s
Doxygen::includeNameLinkedMap, // fnDict
nullptr, // exclSet
&pl, // patList
&exclPatterns, // exclPatList
nullptr, // resultList
nullptr, // resultSet
false, // INCLUDE_PATH isn't recursive
TRUE, // errorIfNotExist
&killSet); // killSet
}
g_s.end();
g_s.begin("Searching for example files...\n");
killSet.clear();
const StringVector &examplePathList = Config_getList(EXAMPLE_PATH);
for (const auto &s : examplePathList)
{
readFileOrDirectory(s.c_str(), // s
Doxygen::exampleNameLinkedMap, // fnDict
nullptr, // exclSet
&Config_getList(EXAMPLE_PATTERNS), // patList
nullptr, // exclPatList
nullptr, // resultList
nullptr, // resultSet
(alwaysRecursive || Config_getBool(EXAMPLE_RECURSIVE)), // recursive
TRUE, // errorIfNotExist
&killSet); // killSet
}
g_s.end();
g_s.begin("Searching for images...\n");
killSet.clear();
const StringVector &imagePathList=Config_getList(IMAGE_PATH);
for (const auto &s : imagePathList)
{
readFileOrDirectory(s.c_str(), // s
Doxygen::imageNameLinkedMap, // fnDict
nullptr, // exclSet
nullptr, // patList
nullptr, // exclPatList
nullptr, // resultList
nullptr, // resultSet
alwaysRecursive, // recursive
TRUE, // errorIfNotExist
&killSet); // killSet
}
g_s.end();
g_s.begin("Searching for dot files...\n");
killSet.clear();
const StringVector &dotFileList=Config_getList(DOTFILE_DIRS);
for (const auto &s : dotFileList)
{
readFileOrDirectory(s.c_str(), // s
Doxygen::dotFileNameLinkedMap, // fnDict
nullptr, // exclSet
nullptr, // patList
nullptr, // exclPatList
nullptr, // resultList
nullptr, // resultSet
alwaysRecursive, // recursive
TRUE, // errorIfNotExist
&killSet); // killSet
}
g_s.end();
g_s.begin("Searching for msc files...\n");
killSet.clear();
const StringVector &mscFileList=Config_getList(MSCFILE_DIRS);
for (const auto &s : mscFileList)
{
readFileOrDirectory(s.c_str(), // s
Doxygen::mscFileNameLinkedMap, // fnDict
nullptr, // exclSet
nullptr, // patList
nullptr, // exclPatList
nullptr, // resultList
nullptr, // resultSet
alwaysRecursive, // recursive
TRUE, // errorIfNotExist
&killSet); // killSet
}
g_s.end();
g_s.begin("Searching for dia files...\n");
killSet.clear();
const StringVector &diaFileList=Config_getList(DIAFILE_DIRS);
for (const auto &s : diaFileList)
{
readFileOrDirectory(s.c_str(), // s
Doxygen::diaFileNameLinkedMap, // fnDict
nullptr, // exclSet
nullptr, // patList
nullptr, // exclPatList
nullptr, // resultList
nullptr, // resultSet
alwaysRecursive, // recursive
TRUE, // errorIfNotExist
&killSet); // killSet
}
g_s.end();
g_s.begin("Searching for plantuml files...\n");
killSet.clear();
const StringVector &plantUmlFileList=Config_getList(PLANTUMLFILE_DIRS);
for (const auto &s : plantUmlFileList)
{
readFileOrDirectory(s.c_str(), // s
Doxygen::plantUmlFileNameLinkedMap,// fnDict
nullptr, // exclSet
nullptr, // patList
nullptr, // exclPatList
nullptr, // resultList
nullptr, // resultSet
alwaysRecursive, // recursive
TRUE, // errorIfNotExist
&killSet); // killSet
}
g_s.end();
g_s.begin("Searching for files to exclude\n");
const StringVector &excludeList = Config_getList(EXCLUDE);
for (const auto &s : excludeList)
{
readFileOrDirectory(s.c_str(), // s
nullptr, // fnDict
nullptr, // exclSet
&Config_getList(FILE_PATTERNS), // patList
nullptr, // exclPatList
nullptr, // resultList
&excludeNameSet, // resultSet
alwaysRecursive, // recursive
FALSE); // errorIfNotExist
}
g_s.end();
/**************************************************************************
* Determine Input Files *
**************************************************************************/
g_s.begin("Searching INPUT for files to process...\n");
killSet.clear();
Doxygen::inputPaths.clear();
const StringVector &inputList=Config_getList(INPUT);
for (const auto &s : inputList)
{
QCString path=s.c_str();
size_t l = path.length();
if (l>0)
{
// strip trailing slashes
if (path.at(l-1)=='\\' || path.at(l-1)=='/') path=path.left(l-1);
readFileOrDirectory(
path, // s
Doxygen::inputNameLinkedMap, // fnDict
&excludeNameSet, // exclSet
&Config_getList(FILE_PATTERNS), // patList
&exclPatterns, // exclPatList
&g_inputFiles, // resultList
nullptr, // resultSet
alwaysRecursive, // recursive
TRUE, // errorIfNotExist
&killSet, // killSet
&Doxygen::inputPaths); // paths
}
}
// Sort the FileDef objects by full path to get a predictable ordering over multiple runs
std::stable_sort(Doxygen::inputNameLinkedMap->begin(),
Doxygen::inputNameLinkedMap->end(),
[](const auto &f1,const auto &f2)
{
return qstricmp_sort(f1->fullName(),f2->fullName())<0;
});
for (auto &fileName : *Doxygen::inputNameLinkedMap)
{
if (fileName->size()>1)
{
std::stable_sort(fileName->begin(),fileName->end(),[](const auto &f1,const auto &f2)
{
return qstricmp_sort(f1->absFilePath(),f2->absFilePath())<0;
});
}
}
if (Doxygen::inputNameLinkedMap->empty())
{
warn_uncond("No files to be processed, please check your settings, in particular INPUT, FILE_PATTERNS, and RECURSIVE\n");
}
g_s.end();
}
static void checkMarkdownMainfile()
{
if (Config_getBool(MARKDOWN_SUPPORT))
{
QCString mdfileAsMainPage = Config_getString(USE_MDFILE_AS_MAINPAGE);
if (mdfileAsMainPage.isEmpty()) return;
FileInfo fi(mdfileAsMainPage.data());
if (!fi.exists())
{
warn_uncond("Specified markdown mainpage '%s' does not exist\n",qPrint(mdfileAsMainPage));
return;
}
bool ambig = false;
if (findFileDef(Doxygen::inputNameLinkedMap,fi.absFilePath(),ambig)==nullptr)
{
warn_uncond("Specified markdown mainpage '%s' has not been defined as input file\n",qPrint(mdfileAsMainPage));
return;
}
}
}
void parseInput()
{
AUTO_TRACE();
std::atexit(exitDoxygen);
Portable::correctPath(Config_getList(EXTERNAL_TOOL_PATH));
#if USE_LIBCLANG
Doxygen::clangAssistedParsing = Config_getBool(CLANG_ASSISTED_PARSING);
#endif
// we would like to show the versionString earlier, but we first have to handle the configuration file
// to know the value of the QUIET setting.
QCString versionString = getFullVersion();
msg("Doxygen version used: %s\n",qPrint(versionString));
computeVerifiedDotPath();
/**************************************************************************
* Make sure the output directory exists
**************************************************************************/
QCString outputDirectory = Config_getString(OUTPUT_DIRECTORY);
if (outputDirectory.isEmpty())
{
outputDirectory = Config_updateString(OUTPUT_DIRECTORY,Dir::currentDirPath().c_str());
}
else
{
Dir dir(outputDirectory.str());
if (!dir.exists())
{
dir.setPath(Dir::currentDirPath());
if (!dir.mkdir(outputDirectory.str()))
{
term("tag OUTPUT_DIRECTORY: Output directory '%s' does not "
"exist and cannot be created\n",qPrint(outputDirectory));
}
else
{
msg("Notice: Output directory '%s' does not exist. "
"I have created it for you.\n", qPrint(outputDirectory));
}
dir.setPath(outputDirectory.str());
}
outputDirectory = Config_updateString(OUTPUT_DIRECTORY,dir.absPath().c_str());
}
AUTO_TRACE_ADD("outputDirectory={}",outputDirectory);
/**************************************************************************
* Initialize global lists and dictionaries
**************************************************************************/
// also scale lookup cache with SYMBOL_CACHE_SIZE
int cacheSize = Config_getInt(LOOKUP_CACHE_SIZE);
if (cacheSize<0) cacheSize=0;
if (cacheSize>9) cacheSize=9;
uint32_t lookupSize = 65536 << cacheSize;
Doxygen::typeLookupCache = new Cache<std::string,LookupInfo>(lookupSize);
Doxygen::symbolLookupCache = new Cache<std::string,LookupInfo>(lookupSize);
#ifdef HAS_SIGNALS
signal(SIGINT, stopDoxygen);
#endif
uint32_t pid = Portable::pid();
Doxygen::filterDBFileName.sprintf("doxygen_filterdb_%d.tmp",pid);
Doxygen::filterDBFileName.prepend(outputDirectory+"/");
/**************************************************************************
* Check/create output directories *
**************************************************************************/
QCString htmlOutput;
bool generateHtml = Config_getBool(GENERATE_HTML);
if (generateHtml)
{
htmlOutput = createOutputDirectory(outputDirectory,Config_getString(HTML_OUTPUT),"/html");
Config_updateString(HTML_OUTPUT,htmlOutput);
QCString sitemapUrl = Config_getString(SITEMAP_URL);
bool generateSitemap = !sitemapUrl.isEmpty();
if (generateSitemap && !sitemapUrl.endsWith("/"))
{
Config_updateString(SITEMAP_URL,sitemapUrl+"/");
}
// add HTML indexers that are enabled
bool generateHtmlHelp = Config_getBool(GENERATE_HTMLHELP);
bool generateEclipseHelp = Config_getBool(GENERATE_ECLIPSEHELP);
bool generateQhp = Config_getBool(GENERATE_QHP);
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
bool generateDocSet = Config_getBool(GENERATE_DOCSET);
if (generateEclipseHelp) Doxygen::indexList->addIndex<EclipseHelp>();
if (generateHtmlHelp) Doxygen::indexList->addIndex<HtmlHelp>();
if (generateQhp) Doxygen::indexList->addIndex<Qhp>();
if (generateSitemap) Doxygen::indexList->addIndex<Sitemap>();
if (generateTreeView) Doxygen::indexList->addIndex<FTVHelp>(TRUE);
if (generateDocSet) Doxygen::indexList->addIndex<DocSets>();
Doxygen::indexList->addIndex<Crawlmap>();
Doxygen::indexList->initialize();
}
QCString docbookOutput;
bool generateDocbook = Config_getBool(GENERATE_DOCBOOK);
if (generateDocbook)
{
docbookOutput = createOutputDirectory(outputDirectory,Config_getString(DOCBOOK_OUTPUT),"/docbook");
Config_updateString(DOCBOOK_OUTPUT,docbookOutput);
}
QCString xmlOutput;
bool generateXml = Config_getBool(GENERATE_XML);
if (generateXml)
{
xmlOutput = createOutputDirectory(outputDirectory,Config_getString(XML_OUTPUT),"/xml");
Config_updateString(XML_OUTPUT,xmlOutput);
}
QCString latexOutput;
bool generateLatex = Config_getBool(GENERATE_LATEX);
if (generateLatex)
{
latexOutput = createOutputDirectory(outputDirectory,Config_getString(LATEX_OUTPUT), "/latex");
Config_updateString(LATEX_OUTPUT,latexOutput);
}
QCString rtfOutput;
bool generateRtf = Config_getBool(GENERATE_RTF);
if (generateRtf)
{
rtfOutput = createOutputDirectory(outputDirectory,Config_getString(RTF_OUTPUT),"/rtf");
Config_updateString(RTF_OUTPUT,rtfOutput);
}
QCString manOutput;
bool generateMan = Config_getBool(GENERATE_MAN);
if (generateMan)
{
manOutput = createOutputDirectory(outputDirectory,Config_getString(MAN_OUTPUT),"/man");
Config_updateString(MAN_OUTPUT,manOutput);
}
QCString sqlOutput;
bool generateSql = Config_getBool(GENERATE_SQLITE3);
if (generateSql)
{
sqlOutput = createOutputDirectory(outputDirectory,Config_getString(SQLITE3_OUTPUT),"/sqlite3");
Config_updateString(SQLITE3_OUTPUT,sqlOutput);
}
if (Config_getBool(HAVE_DOT))
{
QCString curFontPath = Config_getString(DOT_FONTPATH);
if (curFontPath.isEmpty())
{
Portable::getenv("DOTFONTPATH");
QCString newFontPath = ".";
if (!curFontPath.isEmpty())
{
newFontPath+=Portable::pathListSeparator();
newFontPath+=curFontPath;
}
Portable::setenv("DOTFONTPATH",qPrint(newFontPath));
}
else
{
Portable::setenv("DOTFONTPATH",qPrint(curFontPath));
}
}
/**************************************************************************
* Handle layout file *
**************************************************************************/
LayoutDocManager::instance().init();
QCString layoutFileName = Config_getString(LAYOUT_FILE);
bool defaultLayoutUsed = FALSE;
if (layoutFileName.isEmpty())
{
layoutFileName = Config_updateString(LAYOUT_FILE,"DoxygenLayout.xml");
defaultLayoutUsed = TRUE;
}
AUTO_TRACE_ADD("defaultLayoutUsed={}, layoutFileName={}",defaultLayoutUsed,layoutFileName);
FileInfo fi(layoutFileName.str());
if (fi.exists())
{
msg("Parsing layout file %s...\n",qPrint(layoutFileName));
LayoutDocManager::instance().parse(layoutFileName);
}
else if (!defaultLayoutUsed)
{
warn_uncond("failed to open layout file '%s' for reading! Using default settings.\n",qPrint(layoutFileName));
}
printLayout();
/**************************************************************************
* Read and preprocess input *
**************************************************************************/
// prevent search in the output directories
StringVector exclPatterns = Config_getList(EXCLUDE_PATTERNS);
if (generateHtml) exclPatterns.push_back(htmlOutput.str());
if (generateDocbook) exclPatterns.push_back(docbookOutput.str());
if (generateXml) exclPatterns.push_back(xmlOutput.str());
if (generateLatex) exclPatterns.push_back(latexOutput.str());
if (generateRtf) exclPatterns.push_back(rtfOutput.str());
if (generateMan) exclPatterns.push_back(manOutput.str());
Config_updateList(EXCLUDE_PATTERNS,exclPatterns);
searchInputFiles();
checkMarkdownMainfile();
// Notice: the order of the function calls below is very important!
if (Config_getBool(GENERATE_HTML) && !Config_getBool(USE_MATHJAX))
{
FormulaManager::instance().initFromRepository(Config_getString(HTML_OUTPUT));
}
if (Config_getBool(GENERATE_RTF))
{
FormulaManager::instance().initFromRepository(Config_getString(RTF_OUTPUT));
}
if (Config_getBool(GENERATE_DOCBOOK))
{
FormulaManager::instance().initFromRepository(Config_getString(DOCBOOK_OUTPUT));
}
FormulaManager::instance().checkRepositories();
/**************************************************************************
* Handle Tag Files *
**************************************************************************/
std::shared_ptr<Entry> root = std::make_shared<Entry>();
msg("Reading and parsing tag files\n");
const StringVector &tagFileList = Config_getList(TAGFILES);
for (const auto &s : tagFileList)
{
readTagFile(root,s.c_str());
}
/**************************************************************************
* Parse source files *
**************************************************************************/
addSTLSupport(root);
g_s.begin("Parsing files\n");
if (Config_getInt(NUM_PROC_THREADS)==1)
{
parseFilesSingleThreading(root);
}
else
{
parseFilesMultiThreading(root);
}
g_s.end();
/**************************************************************************
* Gather information *
**************************************************************************/
g_s.begin("Building macro definition list...\n");
buildDefineList();
g_s.end();
g_s.begin("Building group list...\n");
buildGroupList(root.get());
organizeSubGroups(root.get());
g_s.end();
g_s.begin("Building directory list...\n");
buildDirectories();
findDirDocumentation(root.get());
g_s.end();
g_s.begin("Building namespace list...\n");
buildNamespaceList(root.get());
findUsingDirectives(root.get());
g_s.end();
g_s.begin("Building file list...\n");
buildFileList(root.get());
g_s.end();
g_s.begin("Building class list...\n");
buildClassList(root.get());
g_s.end();
g_s.begin("Building concept list...\n");
buildConceptList(root.get());
g_s.end();
// build list of using declarations here (global list)
buildListOfUsingDecls(root.get());
g_s.end();
g_s.begin("Computing nesting relations for classes...\n");
resolveClassNestingRelations();
g_s.end();
// 1.8.2-20121111: no longer add nested classes to the group as well
//distributeClassGroupRelations();
// calling buildClassList may result in cached relations that
// become invalid after resolveClassNestingRelations(), that's why
// we need to clear the cache here
Doxygen::typeLookupCache->clear();
// we don't need the list of using declaration anymore
g_usingDeclarations.clear();
g_s.begin("Associating documentation with classes...\n");
buildClassDocList(root.get());
g_s.end();
g_s.begin("Associating documentation with concepts...\n");
buildConceptDocList(root.get());
distributeConceptGroups();
g_s.end();
g_s.begin("Associating documentation with modules...\n");
findModuleDocumentation(root.get());
g_s.end();
g_s.begin("Building example list...\n");
buildExampleList(root.get());
g_s.end();
g_s.begin("Searching for enumerations...\n");
findEnums(root.get());
g_s.end();
// Since buildVarList calls isVarWithConstructor
// and this calls getResolvedClass we need to process
// typedefs first so the relations between classes via typedefs
// are properly resolved. See bug 536385 for an example.
g_s.begin("Searching for documented typedefs...\n");
buildTypedefList(root.get());
g_s.end();
if (Config_getBool(OPTIMIZE_OUTPUT_SLICE))
{
g_s.begin("Searching for documented sequences...\n");
buildSequenceList(root.get());
g_s.end();
g_s.begin("Searching for documented dictionaries...\n");
buildDictionaryList(root.get());
g_s.end();
}
g_s.begin("Searching for members imported via using declarations...\n");
// this should be after buildTypedefList in order to properly import
// used typedefs
findUsingDeclarations(root.get(),TRUE); // do for python packages first
findUsingDeclarations(root.get(),FALSE); // then the rest
g_s.end();
g_s.begin("Searching for included using directives...\n");
findIncludedUsingDirectives();
g_s.end();
g_s.begin("Searching for documented variables...\n");
buildVarList(root.get());
g_s.end();
g_s.begin("Building interface member list...\n");
buildInterfaceAndServiceList(root.get()); // UNO IDL
g_s.begin("Building member list...\n"); // using class info only !
buildFunctionList(root.get());
g_s.end();
g_s.begin("Searching for friends...\n");
findFriends();
g_s.end();
g_s.begin("Searching for documented defines...\n");
findDefineDocumentation(root.get());
g_s.end();
g_s.begin("Computing class inheritance relations...\n");
findClassEntries(root.get());
findInheritedTemplateInstances();
g_s.end();
g_s.begin("Computing class usage relations...\n");
findUsedTemplateInstances();
g_s.end();
if (Config_getBool(INLINE_SIMPLE_STRUCTS))
{
g_s.begin("Searching for tag less structs...\n");
findTagLessClasses();
g_s.end();
}
g_s.begin("Flushing cached template relations that have become invalid...\n");
flushCachedTemplateRelations();
g_s.end();
g_s.begin("Warn for undocumented namespaces...\n");
warnUndocumentedNamespaces();
g_s.end();
g_s.begin("Computing class relations...\n");
computeTemplateClassRelations();
flushUnresolvedRelations();
if (Config_getBool(OPTIMIZE_OUTPUT_VHDL))
{
VhdlDocGen::computeVhdlComponentRelations();
}
computeClassRelations();
g_classEntries.clear();
g_s.end();
g_s.begin("Add enum values to enums...\n");
addEnumValuesToEnums(root.get());
findEnumDocumentation(root.get());
g_s.end();
g_s.begin("Searching for member function documentation...\n");
findObjCMethodDefinitions(root.get());
findMemberDocumentation(root.get()); // may introduce new members !
findUsingDeclImports(root.get()); // may introduce new members !
g_usingClassMap.clear();
transferRelatedFunctionDocumentation();
transferFunctionDocumentation();
transferStaticInstanceInitializers();
g_s.end();
// moved to after finding and copying documentation,
// as this introduces new members see bug 722654
g_s.begin("Creating members for template instances...\n");
createTemplateInstanceMembers();
g_s.end();
g_s.begin("Building page list...\n");
buildPageList(root.get());
g_s.end();
g_s.begin("Search for main page...\n");
findMainPage(root.get());
findMainPageTagFiles(root.get());
g_s.end();
g_s.begin("Computing page relations...\n");
computePageRelations(root.get());
checkPageRelations();
g_s.end();
g_s.begin("Determining the scope of groups...\n");
findGroupScope(root.get());
g_s.end();
g_s.begin("Computing module relations...\n");
auto &mm = ModuleManager::instance();
mm.resolvePartitions();
mm.resolveImports();
mm.collectExportedSymbols();
g_s.end();
auto memberNameComp = [](const MemberNameLinkedMap::Ptr &n1,const MemberNameLinkedMap::Ptr &n2)
{
return qstricmp_sort(n1->memberName().data()+getPrefixIndex(n1->memberName()),
n2->memberName().data()+getPrefixIndex(n2->memberName())
)<0;
};
auto classComp = [](const ClassLinkedMap::Ptr &c1,const ClassLinkedMap::Ptr &c2)
{
if (Config_getBool(SORT_BY_SCOPE_NAME))
{
return qstricmp_sort(c1->name(), c2->name())<0;
}
else
{
int i = qstricmp_sort(c1->className(), c2->className());
return i==0 ? qstricmp_sort(c1->name(), c2->name())<0 : i<0;
}
};
auto namespaceComp = [](const NamespaceLinkedMap::Ptr &n1,const NamespaceLinkedMap::Ptr &n2)
{
return qstricmp_sort(n1->name(),n2->name())<0;
};
auto conceptComp = [](const ConceptLinkedMap::Ptr &c1,const ConceptLinkedMap::Ptr &c2)
{
return qstricmp_sort(c1->name(),c2->name())<0;
};
g_s.begin("Sorting lists...\n");
std::stable_sort(Doxygen::memberNameLinkedMap->begin(),
Doxygen::memberNameLinkedMap->end(),
memberNameComp);
std::stable_sort(Doxygen::functionNameLinkedMap->begin(),
Doxygen::functionNameLinkedMap->end(),
memberNameComp);
std::stable_sort(Doxygen::hiddenClassLinkedMap->begin(),
Doxygen::hiddenClassLinkedMap->end(),
classComp);
std::stable_sort(Doxygen::classLinkedMap->begin(),
Doxygen::classLinkedMap->end(),
classComp);
std::stable_sort(Doxygen::conceptLinkedMap->begin(),
Doxygen::conceptLinkedMap->end(),
conceptComp);
std::stable_sort(Doxygen::namespaceLinkedMap->begin(),
Doxygen::namespaceLinkedMap->end(),
namespaceComp);
g_s.end();
g_s.begin("Determining which enums are documented\n");
findDocumentedEnumValues();
g_s.end();
g_s.begin("Computing member relations...\n");
mergeCategories();
computeMemberRelations();
g_s.end();
g_s.begin("Building full member lists recursively...\n");
buildCompleteMemberLists();
g_s.end();
g_s.begin("Adding members to member groups.\n");
addMembersToMemberGroup();
g_s.end();
if (Config_getBool(DISTRIBUTE_GROUP_DOC))
{
g_s.begin("Distributing member group documentation.\n");
distributeMemberGroupDocumentation();
g_s.end();
}
g_s.begin("Computing member references...\n");
computeMemberReferences();
g_s.end();
if (Config_getBool(INHERIT_DOCS))
{
g_s.begin("Inheriting documentation...\n");
inheritDocumentation();
g_s.end();
}
// compute the shortest possible names of all files
// without losing the uniqueness of the file names.
g_s.begin("Generating disk names...\n");
generateDiskNames();
g_s.end();
g_s.begin("Adding source references...\n");
addSourceReferences();
g_s.end();
g_s.begin("Adding xrefitems...\n");
addListReferences();
generateXRefPages();
g_s.end();
g_s.begin("Sorting member lists...\n");
sortMemberLists();
g_s.end();
g_s.begin("Setting anonymous enum type...\n");
setAnonymousEnumType();
g_s.end();
g_s.begin("Computing dependencies between directories...\n");
computeDirDependencies();
g_s.end();
g_s.begin("Generating citations page...\n");
CitationManager::instance().generatePage();
g_s.end();
g_s.begin("Counting members...\n");
countMembers();
g_s.end();
g_s.begin("Counting data structures...\n");
Index::instance().countDataStructures();
g_s.end();
g_s.begin("Resolving user defined references...\n");
resolveUserReferences();
g_s.end();
g_s.begin("Finding anchors and sections in the documentation...\n");
findSectionsInDocumentation();
g_s.end();
g_s.begin("Transferring function references...\n");
transferFunctionReferences();
g_s.end();
g_s.begin("Combining using relations...\n");
combineUsingRelations();
g_s.end();
initSearchIndexer();
g_s.begin("Adding members to index pages...\n");
addMembersToIndex();
addToIndices();
g_s.end();
g_s.begin("Correcting members for VHDL...\n");
vhdlCorrectMemberProperties();
g_s.end();
g_s.begin("Computing tooltip texts...\n");
computeTooltipTexts();
g_s.end();
if (Config_getBool(SORT_GROUP_NAMES))
{
std::stable_sort(Doxygen::groupLinkedMap->begin(),
Doxygen::groupLinkedMap->end(),
[](const auto &g1,const auto &g2)
{ return g1->groupTitle() < g2->groupTitle(); });
for (const auto &gd : *Doxygen::groupLinkedMap)
{
gd->sortSubGroups();
}
}
printNavTree(root.get(),0);
printSectionsTree();
}
void generateOutput()
{
AUTO_TRACE();
/**************************************************************************
* Initialize output generators *
**************************************************************************/
/// add extra languages for which we can only produce syntax highlighted code
addCodeOnlyMappings();
//// dump all symbols
if (g_dumpSymbolMap)
{
dumpSymbolMap();
exit(0);
}
bool generateHtml = Config_getBool(GENERATE_HTML);
bool generateLatex = Config_getBool(GENERATE_LATEX);
bool generateMan = Config_getBool(GENERATE_MAN);
bool generateRtf = Config_getBool(GENERATE_RTF);
bool generateDocbook = Config_getBool(GENERATE_DOCBOOK);
g_outputList = new OutputList;
if (generateHtml)
{
g_outputList->add<HtmlGenerator>();
HtmlGenerator::init();
HtmlGenerator::writeTabData();
}
if (generateLatex)
{
g_outputList->add<LatexGenerator>();
LatexGenerator::init();
}
if (generateDocbook)
{
g_outputList->add<DocbookGenerator>();
DocbookGenerator::init();
}
if (generateMan)
{
g_outputList->add<ManGenerator>();
ManGenerator::init();
}
if (generateRtf)
{
g_outputList->add<RTFGenerator>();
RTFGenerator::init();
}
if (Config_getBool(USE_HTAGS))
{
Htags::useHtags = TRUE;
QCString htmldir = Config_getString(HTML_OUTPUT);
if (!Htags::execute(htmldir))
err("USE_HTAGS is YES but htags(1) failed. \n");
else if (!Htags::loadFilemap(htmldir))
err("htags(1) ended normally but failed to load the filemap. \n");
}
/**************************************************************************
* Generate documentation *
**************************************************************************/
g_s.begin("Generating style sheet...\n");
//printf("writing style info\n");
g_outputList->writeStyleInfo(0); // write first part
g_s.end();
bool searchEngine = Config_getBool(SEARCHENGINE);
bool serverBasedSearch = Config_getBool(SERVER_BASED_SEARCH);
g_s.begin("Generating search indices...\n");
if (searchEngine && !serverBasedSearch && generateHtml)
{
createJavaScriptSearchIndex();
}
// generate search indices (need to do this before writing other HTML
// pages as these contain a drop down menu with options depending on
// what categories we find in this function.
if (generateHtml && searchEngine)
{
QCString searchDirName = Config_getString(HTML_OUTPUT)+"/search";
Dir searchDir(searchDirName.str());
if (!searchDir.exists() && !searchDir.mkdir(searchDirName.str()))
{
term("Could not create search results directory '%s' $PWD='%s'\n",
qPrint(searchDirName),Dir::currentDirPath().c_str());
}
HtmlGenerator::writeSearchData(searchDirName);
if (!serverBasedSearch) // client side search index
{
writeJavaScriptSearchIndex();
}
}
g_s.end();
// copy static stuff
if (generateHtml)
{
FTVHelp::generateTreeViewImages();
copyStyleSheet();
copyLogo(Config_getString(HTML_OUTPUT));
copyIcon(Config_getString(HTML_OUTPUT));
copyExtraFiles(Config_getList(HTML_EXTRA_FILES),"HTML_EXTRA_FILES",Config_getString(HTML_OUTPUT));
}
if (generateLatex)
{
copyLatexStyleSheet();
copyLogo(Config_getString(LATEX_OUTPUT));
copyIcon(Config_getString(LATEX_OUTPUT));
copyExtraFiles(Config_getList(LATEX_EXTRA_FILES),"LATEX_EXTRA_FILES",Config_getString(LATEX_OUTPUT));
}
if (generateDocbook)
{
copyLogo(Config_getString(DOCBOOK_OUTPUT));
copyIcon(Config_getString(DOCBOOK_OUTPUT));
}
if (generateRtf)
{
copyLogo(Config_getString(RTF_OUTPUT));
copyIcon(Config_getString(RTF_OUTPUT));
copyExtraFiles(Config_getList(RTF_EXTRA_FILES),"RTF_EXTRA_FILES",Config_getString(RTF_OUTPUT));
}
FormulaManager &fm = FormulaManager::instance();
if (fm.hasFormulas() && generateHtml
&& !Config_getBool(USE_MATHJAX))
{
g_s.begin("Generating images for formulas in HTML...\n");
fm.generateImages(Config_getString(HTML_OUTPUT), Config_getEnum(HTML_FORMULA_FORMAT)==HTML_FORMULA_FORMAT_t::svg ?
FormulaManager::Format::Vector : FormulaManager::Format::Bitmap, FormulaManager::HighDPI::On);
g_s.end();
}
if (fm.hasFormulas() && generateRtf)
{
g_s.begin("Generating images for formulas in RTF...\n");
fm.generateImages(Config_getString(RTF_OUTPUT),FormulaManager::Format::Bitmap);
g_s.end();
}
if (fm.hasFormulas() && generateDocbook)
{
g_s.begin("Generating images for formulas in Docbook...\n");
fm.generateImages(Config_getString(DOCBOOK_OUTPUT),FormulaManager::Format::Bitmap);
g_s.end();
}
g_s.begin("Generating example documentation...\n");
generateExampleDocs();
g_s.end();
g_s.begin("Generating file sources...\n");
generateFileSources();
g_s.end();
g_s.begin("Generating file documentation...\n");
generateFileDocs();
g_s.end();
g_s.begin("Generating page documentation...\n");
generatePageDocs();
g_s.end();
g_s.begin("Generating group documentation...\n");
generateGroupDocs();
g_s.end();
g_s.begin("Generating class documentation...\n");
generateClassDocs();
g_s.end();
g_s.begin("Generating concept documentation...\n");
generateConceptDocs();
g_s.end();
g_s.begin("Generating module documentation...\n");
ModuleManager::instance().writeDocumentation(*g_outputList);
g_s.end();
g_s.begin("Generating namespace documentation...\n");
generateNamespaceDocs();
g_s.end();
if (Config_getBool(GENERATE_LEGEND))
{
g_s.begin("Generating graph info page...\n");
writeGraphInfo(*g_outputList);
g_s.end();
}
g_s.begin("Generating directory documentation...\n");
generateDirDocs(*g_outputList);
g_s.end();
if (g_outputList->size()>0)
{
writeIndexHierarchy(*g_outputList);
}
g_s.begin("finalizing index lists...\n");
Doxygen::indexList->finalize();
g_s.end();
g_s.begin("writing tag file...\n");
writeTagFile();
g_s.end();
if (Config_getBool(GENERATE_XML))
{
g_s.begin("Generating XML output...\n");
Doxygen::generatingXmlOutput=TRUE;
generateXML();
Doxygen::generatingXmlOutput=FALSE;
g_s.end();
}
if (Config_getBool(GENERATE_SQLITE3))
{
g_s.begin("Generating SQLITE3 output...\n");
generateSqlite3();
g_s.end();
}
if (Config_getBool(GENERATE_AUTOGEN_DEF))
{
g_s.begin("Generating AutoGen DEF output...\n");
generateDEF();
g_s.end();
}
if (Config_getBool(GENERATE_PERLMOD))
{
g_s.begin("Generating Perl module output...\n");
generatePerlMod();
g_s.end();
}
if (generateHtml && searchEngine && serverBasedSearch)
{
g_s.begin("Generating search index\n");
if (Doxygen::searchIndex.kind()==SearchIndexIntf::Internal) // write own search index
{
HtmlGenerator::writeSearchPage();
Doxygen::searchIndex.write(Config_getString(HTML_OUTPUT)+"/search/search.idx");
}
else // write data for external search index
{
HtmlGenerator::writeExternalSearchPage();
QCString searchDataFile = Config_getString(SEARCHDATA_FILE);
if (searchDataFile.isEmpty())
{
searchDataFile="searchdata.xml";
}
if (!Portable::isAbsolutePath(searchDataFile.data()))
{
searchDataFile.prepend(Config_getString(OUTPUT_DIRECTORY)+"/");
}
Doxygen::searchIndex.write(searchDataFile);
}
g_s.end();
}
if (generateRtf)
{
g_s.begin("Combining RTF output...\n");
if (!RTFGenerator::preProcessFileInplace(Config_getString(RTF_OUTPUT),"refman.rtf"))
{
err("An error occurred during post-processing the RTF files!\n");
}
g_s.end();
}
g_s.begin("Running plantuml with JAVA...\n");
PlantumlManager::instance().run();
g_s.end();
if (Config_getBool(HAVE_DOT))
{
g_s.begin("Running dot...\n");
DotManager::instance()->run();
g_s.end();
}
if (generateHtml &&
Config_getBool(GENERATE_HTMLHELP) &&
!Config_getString(HHC_LOCATION).isEmpty())
{
g_s.begin("Running html help compiler...\n");
runHtmlHelpCompiler();
g_s.end();
}
if ( generateHtml &&
Config_getBool(GENERATE_QHP) &&
!Config_getString(QHG_LOCATION).isEmpty())
{
g_s.begin("Running qhelpgenerator...\n");
runQHelpGenerator();
g_s.end();
}
g_outputList->cleanup();
msg("type lookup cache used %zu/%zu hits=%" PRIu64 " misses=%" PRIu64 "\n",
Doxygen::typeLookupCache->size(),
Doxygen::typeLookupCache->capacity(),
Doxygen::typeLookupCache->hits(),
Doxygen::typeLookupCache->misses());
msg("symbol lookup cache used %zu/%zu hits=%" PRIu64 " misses=%" PRIu64 "\n",
Doxygen::symbolLookupCache->size(),
Doxygen::symbolLookupCache->capacity(),
Doxygen::symbolLookupCache->hits(),
Doxygen::symbolLookupCache->misses());
int typeCacheParam = computeIdealCacheParam(static_cast<size_t>(Doxygen::typeLookupCache->misses()*2/3)); // part of the cache is flushed, hence the 2/3 correction factor
int symbolCacheParam = computeIdealCacheParam(static_cast<size_t>(Doxygen::symbolLookupCache->misses()));
int cacheParam = std::max(typeCacheParam,symbolCacheParam);
if (cacheParam>Config_getInt(LOOKUP_CACHE_SIZE))
{
msg("Note: based on cache misses the ideal setting for LOOKUP_CACHE_SIZE is %d at the cost of higher memory usage.\n",cacheParam);
}
if (Debug::isFlagSet(Debug::Time))
{
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
if (numThreads<1) numThreads=1;
msg("Total elapsed time: %.6f seconds\n(of which an average of %.6f seconds per thread waiting for external tools to finish)\n",
(static_cast<double>(Debug::elapsedTime())),
Portable::getSysElapsedTime()/static_cast<double>(numThreads)
);
g_s.print();
Debug::clearFlag(Debug::Time);
msg("finished...\n");
Debug::setFlag(Debug::Time);
}
else
{
msg("finished...\n");
}
/**************************************************************************
* Start cleaning up *
**************************************************************************/
cleanUpDoxygen();
finalizeSearchIndexer();
Dir thisDir;
thisDir.remove(Doxygen::filterDBFileName.str());
finishWarnExit();
exitTracing();
Config::deinit();
delete Doxygen::clangUsrMap;
g_successfulRun=TRUE;
//dumpDocNodeSizes();
}
| 457,511
|
C++
|
.cpp
| 12,382
| 29.475691
| 174
| 0.590016
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,394
|
dotgroupcollaboration.cpp
|
doxygen_doxygen/src/dotgroupcollaboration.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include "dotgroupcollaboration.h"
#include "classlist.h"
#include "doxygen.h"
#include "namespacedef.h"
#include "pagedef.h"
#include "util.h"
#include "config.h"
#include "textstream.h"
DotGroupCollaboration::DotGroupCollaboration(const GroupDef* gd)
{
QCString tmp_url = gd->getReference()+"$"+gd->getOutputFileBase();
QCString tooltip = gd->briefDescriptionAsTooltip();
m_rootNode = new DotNode(this, gd->groupTitle(), tooltip, tmp_url, TRUE );
m_rootNode->markAsVisible();
m_usedNodes.emplace(gd->name().str(), m_rootNode);
m_diskName = gd->getOutputFileBase();
buildGraph( gd );
}
DotGroupCollaboration::~DotGroupCollaboration()
{
// delete all created Nodes saved in m_usedNodes map
for (const auto &[name,node] : m_usedNodes)
{
delete node;
}
}
static void makeURL(const Definition *def,QCString &url)
{
QCString fn = def->getOutputFileBase();
addHtmlExtensionIfMissing(fn);
url = def->getReference()+"$"+fn;
if (!def->anchor().isEmpty())
{
url+="#"+def->anchor();
}
}
void DotGroupCollaboration::buildGraph(const GroupDef* gd)
{
QCString url;
//===========================
// hierarchy.
// Write parents
for (const auto &d : gd->partOfGroups())
{
DotNode *nnode = nullptr;
auto it = m_usedNodes.find(d->name().str());
if ( it==m_usedNodes.end())
{ // add node
makeURL(d,url);
QCString tooltip = d->briefDescriptionAsTooltip();
nnode = new DotNode(this, d->groupTitle(), tooltip, url );
nnode->markAsVisible();
m_usedNodes.emplace(d->name().str(), nnode);
}
else
{
nnode = it->second;
}
url = "";
addEdge( nnode, m_rootNode, DotGroupCollaboration::thierarchy, url, url );
}
// Add subgroups
for (const auto &def : gd->getSubGroups())
{
DotNode *nnode = nullptr;
auto it = m_usedNodes.find(def->name().str());
if ( it==m_usedNodes.end())
{ // add node
makeURL(def,url);
QCString tooltip = def->briefDescriptionAsTooltip();
nnode = new DotNode(this, def->groupTitle(), tooltip, url );
nnode->markAsVisible();
m_usedNodes.emplace(def->name().str(), nnode);
}
else
{
nnode = it->second;
}
url = "";
addEdge( m_rootNode, nnode, DotGroupCollaboration::thierarchy, url, url );
}
//=======================
// Write collaboration
// Add members
addMemberList( gd->getMemberList(MemberListType::AllMembersList()) );
// Add classes
for (const auto &def : gd->getClasses())
{
makeURL(def,url);
addCollaborationMember( def, url, DotGroupCollaboration::tclass );
}
// Add namespaces
for (const auto &def : gd->getNamespaces())
{
makeURL(def,url);
addCollaborationMember( def, url, DotGroupCollaboration::tnamespace );
}
// Add files
for (const auto &def : gd->getFiles())
{
makeURL(def,url);
addCollaborationMember( def, url, DotGroupCollaboration::tfile );
}
// Add pages
for (const auto &def : gd->getPages())
{
makeURL(def,url);
addCollaborationMember( def, url, DotGroupCollaboration::tpages );
}
// Add directories
if ( !gd->getDirs().empty() )
{
for(const auto def : gd->getDirs())
{
makeURL(def,url);
addCollaborationMember( def, url, DotGroupCollaboration::tdir );
}
}
}
void DotGroupCollaboration::addMemberList( MemberList* ml )
{
QCString url;
if ( ml==nullptr || ml->empty() ) return;
for (const auto &def : *ml)
{
makeURL(def,url);
addCollaborationMember( def, url, DotGroupCollaboration::tmember );
}
}
DotGroupCollaboration::Edge* DotGroupCollaboration::addEdge(
DotNode* _pNStart, DotNode* _pNEnd, EdgeType _eType,
const QCString& _label, const QCString& _url )
{
// search a existing link.
auto it = std::find_if(m_edges.begin(),m_edges.end(),
[&_pNStart,&_pNEnd,&_eType](const auto &edge)
{ return edge->pNStart==_pNStart && edge->pNEnd==_pNEnd && edge->eType==_eType; });
if (it==m_edges.end()) // new link
{
m_edges.emplace_back(std::make_unique<Edge>(_pNStart,_pNEnd,_eType));
it = m_edges.end()-1;
}
if (!_label.isEmpty()) // add label
{
(*it)->links.emplace_back(_label,_url);
}
// return found or added edge
return (*it).get();
}
void DotGroupCollaboration::addCollaborationMember(
const Definition* def, QCString& url, EdgeType eType )
{
// Create group nodes
QCString tmp_str;
for (const auto &d : def->partOfGroups())
{
auto it = m_usedNodes.find(d->name().str());
DotNode* nnode = it!=m_usedNodes.end() ? it->second : nullptr;
if ( nnode != m_rootNode )
{
if ( nnode==nullptr )
{ // add node
tmp_str = d->getReference()+"$"+d->getOutputFileBase();
QCString tooltip = d->briefDescriptionAsTooltip();
nnode = new DotNode(this, d->groupTitle(), tooltip, tmp_str );
nnode->markAsVisible();
m_usedNodes.emplace(d->name().str(), nnode);
}
tmp_str = def->qualifiedName();
addEdge( m_rootNode, nnode, eType, tmp_str, url );
}
}
}
QCString DotGroupCollaboration::getBaseName() const
{
return m_diskName;
}
void DotGroupCollaboration::computeTheGraph()
{
TextStream md5stream;
writeGraphHeader(md5stream,m_rootNode->label());
// clean write flags
for (const auto &[name,node] : m_usedNodes)
{
node->clearWriteFlag();
}
// write other nodes.
for (const auto &[name,node] : m_usedNodes)
{
node->write(md5stream,GraphType::Inheritance,m_graphFormat,TRUE,FALSE,FALSE);
}
// write edges
for (const auto &edge : m_edges)
{
edge->write( md5stream );
}
writeGraphFooter(md5stream);
m_theGraph = md5stream.str();
}
QCString DotGroupCollaboration::getMapLabel() const
{
return escapeCharsInString(m_baseName, FALSE);
}
QCString DotGroupCollaboration::writeGraph( TextStream &t,
GraphOutputFormat graphFormat, EmbeddedOutputFormat textFormat,
const QCString &path, const QCString &fileName, const QCString &relPath,
bool generateImageMap,int graphId)
{
m_doNotAddImageToIndex = textFormat!=EmbeddedOutputFormat::Html;
return DotGraph::writeGraph(t, graphFormat, textFormat, path, fileName, relPath, generateImageMap, graphId);
}
void DotGroupCollaboration::Edge::write( TextStream &t ) const
{
const char* linkTypeColor[] = {
"darkorchid3"
,"orange"
,"blueviolet"
,"darkgreen"
,"firebrick4"
,"grey75"
,"midnightblue"
};
QCString arrowStyle = "dir=\"none\", style=\"dashed\"";
t << " Node" << pNStart->number();
t << "->";
t << "Node" << pNEnd->number();
t << " [shape=plaintext";
if (!links.empty()) // there are links
{
t << ", ";
// HTML-like edge labels crash on my Mac with Graphviz 2.0! and
// are not supported by older version of dot.
//
//t << label=<<TABLE BORDER=\"0\" CELLBORDER=\"0\">";
//for (const auto &link : links)
//{
// t << "<TR><TD";
// if ( !link.url.isEmpty() )
// t << " HREF=\"" << link.url << "\"";
// t << ">" << DotNode::convertLabel(link->label) << "</TD></TR>";
//}
//t << "</TABLE>>";
t << "label=\"";
bool first=TRUE;
int count=0;
const int maxLabels = 10;
for (const auto &link : links)
{
if (first) first=FALSE; else t << "\\n";
t << DotNode::convertLabel(link.label);
count++;
}
if (count==maxLabels) t << "\\n...";
t << "\"";
}
switch( eType )
{
case thierarchy:
arrowStyle = "dir=\"back\", style=\"solid\"";
break;
default:
t << ", color=\"" << linkTypeColor[static_cast<int>(eType)] << "\"";
break;
}
t << ", " << arrowStyle;
t << "];\n";
}
bool DotGroupCollaboration::isTrivial() const
{
return m_usedNodes.size() <= 1;
}
bool DotGroupCollaboration::isTooBig() const
{
return numNodes()>=Config_getInt(DOT_GRAPH_MAX_NODES);
}
int DotGroupCollaboration::numNodes() const
{
return static_cast<int>(m_usedNodes.size());
}
void DotGroupCollaboration::writeGraphHeader(TextStream &t,const QCString &title) const
{
DotGraph::writeGraphHeader(t, title);
t << " rankdir=LR;\n";
}
| 8,755
|
C++
|
.cpp
| 298
| 25.721477
| 110
| 0.650588
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,395
|
condparser.cpp
|
doxygen_doxygen/src/condparser.cpp
|
/**
* Copyright (C) 1997-2015 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.
*
* C++ Expression parser for ENABLED_SECTIONS in Doxygen
*
* Features used:
* Operators:
* && AND operator
* || OR operator
* ! NOT operator
*/
#include <algorithm>
#include "condparser.h"
#include "config.h"
#include "message.h"
// declarations
/**
* parses and evaluates the given expression.
* @returns
* - On error, an error message is returned.
* - On success, the result of the expression is either "1" or "0".
*/
bool CondParser::parse(const QCString &fileName,int lineNr,const QCString &expr)
{
if (expr.isEmpty()) return false;
m_expr = expr;
m_tokenType = NOTHING;
// initialize all variables
m_e = m_expr.data(); // let m_e point to the start of the expression
bool answer=false;
getToken();
if (m_tokenType==DELIMITER && m_token.isEmpty())
{
// empty expression: answer==FALSE
}
else if (m_err.isEmpty())
{
answer = parseLevel1();
}
if (!m_err.isEmpty())
{
warn(fileName,lineNr,"problem evaluating expression '%s': %s",
qPrint(expr),qPrint(m_err));
}
//printf("expr='%s' answer=%d\n",expr,answer);
return answer;
}
/**
* checks if the given char c is a delimiter
* minus is checked apart, can be unary minus
*/
static bool isDelimiter(const char c)
{
return c=='&' || c=='|' || c=='!';
}
/**
* checks if the given char c is a letter or underscore
*/
static bool isAlpha(const char c)
{
return (c>='A' && c<='Z') || (c>='a' && c<='z') || c=='_';
}
static bool isAlphaNumSpec(const char c)
{
return isAlpha(c) || (c>='0' && c<='9') || c=='-' || c=='.' || (static_cast<unsigned char>(c)>=0x80);
}
/**
* returns the id of the given operator
* returns -1 if the operator is not recognized
*/
int CondParser::getOperatorId(const QCString &opName)
{
// level 2
if (opName=="&&") { return AND; }
if (opName=="||") { return OR; }
// not operator
if (opName=="!") { return NOT; }
return UNKNOWN_OP;
}
/**
* Get next token in the current string expr.
* Uses the data in m_expr pointed to by m_e to
* produce m_tokenType and m_token, set m_err in case of an error
*/
void CondParser::getToken()
{
m_tokenType = NOTHING;
m_token.clear();
//printf("\tgetToken e:{%c}, ascii=%i, col=%i\n", *e, *e, e-expr);
// skip over whitespaces
while (*m_e == ' ' || *m_e == '\t' || *m_e == '\n') // space or tab or newline
{
m_e++;
}
// check for end of expression
if (*m_e=='\0')
{
// token is still empty
m_tokenType = DELIMITER;
return;
}
// check for parentheses
if (*m_e == '(' || *m_e == ')')
{
m_tokenType = DELIMITER;
m_token += *m_e++;
return;
}
// check for operators (delimiters)
if (isDelimiter(*m_e))
{
m_tokenType = DELIMITER;
while (isDelimiter(*m_e))
{
m_token += *m_e++;
}
return;
}
// check for variables
if (isAlpha(*m_e))
{
m_tokenType = VARIABLE;
while (isAlphaNumSpec(*m_e))
{
m_token += *m_e++;
}
return;
}
// something unknown is found, wrong characters -> a syntax error
m_tokenType = UNKNOWN;
while (*m_e)
{
m_token += *m_e++;
}
m_err = QCString("Syntax error in part '")+m_token+"'";
return;
}
/**
* conditional operators AND and OR
*/
bool CondParser::parseLevel1()
{
bool ans = parseLevel2();
int opId = getOperatorId(m_token);
while (opId==AND || opId==OR)
{
getToken();
ans = evalOperator(opId, ans, parseLevel2());
opId = getOperatorId(m_token);
}
return ans;
}
/**
* NOT
*/
bool CondParser::parseLevel2()
{
int opId = getOperatorId(m_token);
if (opId == NOT)
{
getToken();
return !parseLevel3();
}
else
{
return parseLevel3();
}
}
/**
* parenthesized expression or variable
*/
bool CondParser::parseLevel3()
{
// check if it is a parenthesized expression
if (m_tokenType == DELIMITER)
{
if (m_token=="(")
{
getToken();
bool ans = parseLevel1();
if (m_tokenType!=DELIMITER || m_token!=")")
{
m_err="Parenthesis ) missing";
return FALSE;
}
getToken();
return ans;
}
}
// if not parenthesized then the expression is a variable
return parseVar();
}
bool CondParser::parseVar()
{
bool ans = false;
switch (m_tokenType)
{
case VARIABLE:
// this is a variable
ans = evalVariable(m_token);
getToken();
break;
default:
// syntax error or unexpected end of expression
if (m_token.isEmpty())
{
m_err="Unexpected end of expression";
return FALSE;
}
else
{
m_err="Value expected";
return FALSE;
}
break;
}
return ans;
}
/**
* evaluate an operator for given values
*/
bool CondParser::evalOperator(int opId, bool lhs, bool rhs)
{
switch (opId)
{
// level 2
case AND: return lhs && rhs;
case OR: return lhs || rhs;
}
m_err = "Internal error unknown operator: id="+QCString().setNum(opId);
return FALSE;
}
/**
* evaluate a variable
*/
bool CondParser::evalVariable(const QCString &varName)
{
const StringVector &list = Config_getList(ENABLED_SECTIONS);
return std::find(list.begin(),list.end(),varName.str())!=list.end();
}
| 5,821
|
C++
|
.cpp
| 249
| 20.048193
| 103
| 0.629335
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,396
|
textdocvisitor.cpp
|
doxygen_doxygen/src/textdocvisitor.cpp
|
/******************************************************************************
*
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include "textdocvisitor.h"
#include "message.h"
#include "util.h"
#include "htmlentity.h"
#include "cite.h"
#include "emoji.h"
//-------------------------------------------------------------------------
void TextDocVisitor::operator()(const DocSymbol &s)
{
const char *res = HtmlEntityMapper::instance().html(s.symbol());
if (res)
{
m_t << res;
}
else
{
err("text: non supported HTML-entity found: %s\n",HtmlEntityMapper::instance().html(s.symbol(),TRUE));
}
}
void TextDocVisitor::operator()(const DocEmoji &s)
{
// the TextDocVisitor is only invoked for the JS part of the HTML output
const char *res = EmojiEntityMapper::instance().unicode(s.index());
if (res)
{
const char *p = res;
while (*p)
{
switch(*p)
{
case '&': case '#':
break;
case 'x':
m_t << "\\u{";
break;
case ';':
m_t << "}";
break;
default:
m_t << *p;
break;
}
p++;
}
}
else
{
filter(s.name());
}
}
void TextDocVisitor::operator()(const DocCite &cite)
{
if (!cite.file().isEmpty())
{
QCString anchor = cite.anchor();
QCString anchorPrefix = CitationManager::instance().anchorPrefix();
anchor = anchor.mid(anchorPrefix.length()); // strip prefix
m_t << anchor;
}
else
{
filter(cite.text());
}
}
void TextDocVisitor::filter(const QCString &str)
{
if (str.isEmpty()) return;
//printf("TextDocVisitor::filter(%s)\n",str);
const char *p=str.data();
while (*p)
{
char c = *p++;
if (c=='\n') c=' ';
else m_t << c;
}
}
| 2,293
|
C++
|
.cpp
| 93
| 20.827957
| 106
| 0.587779
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,397
|
cmdmapper.cpp
|
doxygen_doxygen/src/cmdmapper.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 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.
*
*/
#include "cmdmapper.h"
static const CommandMap<CommandType> g_cmdMap =
{
{ "a", CommandType::CMD_EMPHASIS },
{ "addindex", CommandType::CMD_ADDINDEX },
{ "anchor", CommandType::CMD_ANCHOR },
{ "arg", CommandType::CMD_LI },
{ "attention", CommandType::CMD_ATTENTION },
{ "author", CommandType::CMD_AUTHOR },
{ "authors", CommandType::CMD_AUTHORS },
{ "b", CommandType::CMD_BOLD },
{ "c", CommandType::CMD_CODE },
{ "cite", CommandType::CMD_CITE },
{ "icode", CommandType::CMD_ISTARTCODE },
{ "code", CommandType::CMD_STARTCODE },
{ "copydoc", CommandType::CMD_COPYDOC },
{ "copybrief", CommandType::CMD_COPYBRIEF },
{ "copydetails", CommandType::CMD_COPYDETAILS },
{ "copyright", CommandType::CMD_COPYRIGHT },
{ "date", CommandType::CMD_DATE },
{ "showdate", CommandType::CMD_SHOWDATE },
{ "dontinclude", CommandType::CMD_DONTINCLUDE },
{ "dotfile", CommandType::CMD_DOTFILE },
{ "doxyconfig", CommandType::CMD_DOXYCONFIG },
{ "e", CommandType::CMD_EMPHASIS },
{ "em", CommandType::CMD_EMPHASIS },
{ "endicode", CommandType::CMD_ENDICODE },
{ "endcode", CommandType::CMD_ENDCODE },
{ "endhtmlonly", CommandType::CMD_ENDHTMLONLY },
{ "endlatexonly", CommandType::CMD_ENDLATEXONLY },
{ "endlink", CommandType::CMD_ENDLINK },
{ "endsecreflist", CommandType::CMD_ENDSECREFLIST },
{ "endiverbatim", CommandType::CMD_ENDIVERBATIM },
{ "endverbatim", CommandType::CMD_ENDVERBATIM },
{ "endxmlonly", CommandType::CMD_ENDXMLONLY },
{ "exception", CommandType::CMD_EXCEPTION },
{ "_form", CommandType::CMD_FORMULA },
{ "htmlinclude", CommandType::CMD_HTMLINCLUDE },
{ "htmlonly", CommandType::CMD_HTMLONLY },
{ "image", CommandType::CMD_IMAGE },
{ "important", CommandType::CMD_IMPORTANT },
{ "include", CommandType::CMD_INCLUDE },
{ "internal", CommandType::CMD_INTERNAL },
{ "invariant", CommandType::CMD_INVARIANT },
{ "javalink", CommandType::CMD_JAVALINK },
{ "javalinkplain", CommandType::CMD_JAVALINK },
{ "latexinclude", CommandType::CMD_LATEXINCLUDE },
{ "latexonly", CommandType::CMD_LATEXONLY },
{ "li", CommandType::CMD_LI },
{ "line", CommandType::CMD_LINE },
{ "link", CommandType::CMD_LINK },
{ "n", CommandType::CMD_LINEBREAK },
{ "note", CommandType::CMD_NOTE },
{ "p", CommandType::CMD_CODE },
{ "par", CommandType::CMD_PAR },
{ "param", CommandType::CMD_PARAM },
{ "post", CommandType::CMD_POST },
{ "pre", CommandType::CMD_PRE },
{ "ref", CommandType::CMD_REF },
{ "refitem", CommandType::CMD_SECREFITEM },
{ "remark", CommandType::CMD_REMARK },
{ "remarks", CommandType::CMD_REMARK },
{ "result", CommandType::CMD_RETURN },
{ "return", CommandType::CMD_RETURN },
{ "returns", CommandType::CMD_RETURN },
{ "retval", CommandType::CMD_RETVAL },
{ "sa", CommandType::CMD_SA },
{ "secreflist", CommandType::CMD_SECREFLIST },
{ "section", CommandType::CMD_SECTION },
{ "snippet", CommandType::CMD_SNIPPET },
{ "snippetlineno", CommandType::CMD_SNIPWITHLINES },
{ "subpage", CommandType::CMD_SUBPAGE },
{ "subsection", CommandType::CMD_SUBSECTION },
{ "subsubsection", CommandType::CMD_SUBSUBSECTION },
{ "paragraph", CommandType::CMD_PARAGRAPH },
{ "subparagraph", CommandType::CMD_SUBPARAGRAPH },
{ "subsubparagraph", CommandType::CMD_SUBSUBPARAGRAPH },
{ "see", CommandType::CMD_SA },
{ "since", CommandType::CMD_SINCE },
{ "skip", CommandType::CMD_SKIP },
{ "skipline", CommandType::CMD_SKIPLINE },
{ "xmlonly", CommandType::CMD_XMLONLY },
{ "xrefitem", CommandType::CMD_XREFITEM },
{ "throw", CommandType::CMD_EXCEPTION },
{ "until", CommandType::CMD_UNTIL },
{ "iverbatim", CommandType::CMD_IVERBATIM },
{ "verbatim", CommandType::CMD_VERBATIM },
{ "verbinclude", CommandType::CMD_VERBINCLUDE },
{ "version", CommandType::CMD_VERSION },
{ "warning", CommandType::CMD_WARNING },
{ "throws", CommandType::CMD_EXCEPTION },
{ "tparam", CommandType::CMD_TPARAM },
{ "\\", CommandType::CMD_BSLASH },
{ "@", CommandType::CMD_AT },
{ "<", CommandType::CMD_LESS },
{ "=", CommandType::CMD_EQUAL },
{ ">", CommandType::CMD_GREATER },
{ "&", CommandType::CMD_AMP },
{ "$", CommandType::CMD_DOLLAR },
{ "#", CommandType::CMD_HASH },
{ "%", CommandType::CMD_PERCENT },
{ "|", CommandType::CMD_PIPE },
{ ".", CommandType::CMD_PUNT },
{ "+", CommandType::CMD_PLUS },
{ "-", CommandType::CMD_MINUS },
{ "::", CommandType::CMD_DCOLON },
{ "\"", CommandType::CMD_QUOTE },
{ "_internalref", CommandType::CMD_INTERNALREF },
{ "dot", CommandType::CMD_DOT },
{ "msc", CommandType::CMD_MSC },
{ "startuml", CommandType::CMD_STARTUML },
{ "enddot", CommandType::CMD_ENDDOT },
{ "endmsc", CommandType::CMD_ENDMSC },
{ "enduml", CommandType::CMD_ENDUML },
{ "plantumlfile", CommandType::CMD_PLANTUMLFILE },
{ "manonly", CommandType::CMD_MANONLY },
{ "endmanonly", CommandType::CMD_ENDMANONLY },
{ "includelineno", CommandType::CMD_INCWITHLINES },
{ "inheritdoc", CommandType::CMD_INHERITDOC },
{ "mscfile", CommandType::CMD_MSCFILE },
{ "rtfonly", CommandType::CMD_RTFONLY },
{ "endrtfonly", CommandType::CMD_ENDRTFONLY },
{ "vhdlflow", CommandType::CMD_VHDLFLOW },
{ "docbookonly", CommandType::CMD_DBONLY },
{ "enddocbookonly",CommandType::CMD_ENDDBONLY },
{ "endinternal", CommandType::CMD_ENDINTERNAL },
{ "parblock", CommandType::CMD_PARBLOCK },
{ "endparblock", CommandType::CMD_ENDPARBLOCK },
{ "diafile", CommandType::CMD_DIAFILE },
{ "--", CommandType::CMD_NDASH },
{ "---", CommandType::CMD_MDASH },
{ "_setscope", CommandType::CMD_SETSCOPE },
{ "emoji", CommandType::CMD_EMOJI },
{ "rtfinclude", CommandType::CMD_RTFINCLUDE },
{ "docbookinclude",CommandType::CMD_DOCBOOKINCLUDE },
{ "maninclude", CommandType::CMD_MANINCLUDE },
{ "xmlinclude", CommandType::CMD_XMLINCLUDE },
{ "iline", CommandType::CMD_ILINE },
{ "ifile", CommandType::CMD_IFILE },
{ "iliteral", CommandType::CMD_ILITERAL },
{ "endiliteral", CommandType::CMD_ENDILITERAL },
{ "ianchor" , CommandType::CMD_IANCHOR },
{ "iprefix" , CommandType::CMD_IPREFIX },
};
//----------------------------------------------------------------------------
static const CommandMap<HtmlTagType> g_htmlTagMap =
{
{ "strong", HtmlTagType::HTML_BOLD },
{ "center", HtmlTagType::HTML_CENTER },
{ "table", HtmlTagType::HTML_TABLE },
{ "caption", HtmlTagType::HTML_CAPTION },
{ "small", HtmlTagType::HTML_SMALL },
{ "cite", HtmlTagType::HTML_CITE },
{ "code", HtmlTagType::HTML_CODE },
{ "dfn", HtmlTagType::HTML_CODE },
{ "var", HtmlTagType::HTML_EMPHASIS },
{ "img", HtmlTagType::HTML_IMG },
{ "pre", HtmlTagType::HTML_PRE },
{ "sub", HtmlTagType::HTML_SUB },
{ "sup", HtmlTagType::HTML_SUP },
{ "tr", HtmlTagType::HTML_TR },
{ "td", HtmlTagType::HTML_TD },
{ "th", HtmlTagType::HTML_TH },
{ "ol", HtmlTagType::HTML_OL },
{ "ul", HtmlTagType::HTML_UL },
{ "li", HtmlTagType::HTML_LI },
{ "tt", HtmlTagType::XML_C /*HtmlTagType::HTML_CODE*/ },
{ "kbd", HtmlTagType::HTML_KBD },
{ "em", HtmlTagType::HTML_EMPHASIS },
{ "hr", HtmlTagType::HTML_HR },
{ "dl", HtmlTagType::HTML_DL },
{ "dt", HtmlTagType::HTML_DT },
{ "dd", HtmlTagType::HTML_DD },
{ "br", HtmlTagType::HTML_BR },
{ "i", HtmlTagType::HTML_EMPHASIS },
{ "a", HtmlTagType::HTML_A },
{ "b", HtmlTagType::HTML_BOLD },
{ "p", HtmlTagType::HTML_P },
{ "h1", HtmlTagType::HTML_H1 },
{ "h2", HtmlTagType::HTML_H2 },
{ "h3", HtmlTagType::HTML_H3 },
{ "h4", HtmlTagType::HTML_H4 },
{ "h5", HtmlTagType::HTML_H5 },
{ "h6", HtmlTagType::HTML_H6 },
{ "span", HtmlTagType::HTML_SPAN },
{ "div", HtmlTagType::HTML_DIV },
{ "blockquote", HtmlTagType::HTML_BLOCKQUOTE },
{ "strike", HtmlTagType::HTML_STRIKE },
{ "s", HtmlTagType::HTML_S },
{ "u", HtmlTagType::HTML_UNDERLINE },
{ "ins", HtmlTagType::HTML_INS },
{ "del", HtmlTagType::HTML_DEL },
{ "thead", HtmlTagType::HTML_THEAD },
{ "tbody", HtmlTagType::HTML_TBODY },
{ "tfoot", HtmlTagType::HTML_TFOOT },
{ "details", HtmlTagType::HTML_DETAILS },
{ "c", HtmlTagType::XML_C },
// { "code", HtmlTagType::XML_CODE }, <= ambiguous <code> is also a HTML tag
{ "description", HtmlTagType::XML_DESCRIPTION },
{ "example", HtmlTagType::XML_EXAMPLE },
{ "exception", HtmlTagType::XML_EXCEPTION },
{ "include", HtmlTagType::XML_INCLUDE },
{ "item", HtmlTagType::XML_ITEM },
{ "list", HtmlTagType::XML_LIST }, // type="table|bullet|number"
{ "listheader", HtmlTagType::XML_LISTHEADER },
{ "para", HtmlTagType::XML_PARA },
{ "param", HtmlTagType::XML_PARAM },
{ "paramref", HtmlTagType::XML_PARAMREF },
{ "typeparam", HtmlTagType::XML_TYPEPARAM },
{ "typeparamref", HtmlTagType::XML_TYPEPARAMREF },
{ "permission", HtmlTagType::XML_PERMISSION },
{ "remarks", HtmlTagType::XML_REMARKS },
{ "returns", HtmlTagType::XML_RETURNS },
{ "see", HtmlTagType::XML_SEE },
{ "seealso", HtmlTagType::XML_SEEALSO },
{ "summary", HtmlTagType::XML_SUMMARY },
{ "term", HtmlTagType::XML_TERM },
{ "value", HtmlTagType::XML_VALUE },
{ "inheritdoc", HtmlTagType::XML_INHERITDOC },
};
//----------------------------------------------------------------------------
static Mapper<CommandType> g_cmdMapper(g_cmdMap,true);
static Mapper<HtmlTagType> g_htmlTagMapper(g_htmlTagMap,false);
namespace Mappers
{
const Mapper<CommandType> *cmdMapper = &g_cmdMapper;
const Mapper<HtmlTagType> *htmlTagMapper = &g_htmlTagMapper;
}
| 11,470
|
C++
|
.cpp
| 242
| 44.533058
| 85
| 0.570868
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,398
|
outputlist.cpp
|
doxygen_doxygen/src/outputlist.cpp
|
/******************************************************************************
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
/*! \file
* This class represents a list of output generators that work in "parallel".
* The class only knows about the abstract base class OutputGenerators.
* All output is produced by calling a method of this class, which forwards
* the call to all output generators.
*/
#include <atomic>
#include "outputlist.h"
#include "outputgen.h"
#include "config.h"
#include "message.h"
#include "definition.h"
#include "docparser.h"
#include "vhdldocgen.h"
#include "doxygen.h"
static AtomicInt g_outId;
OutputList::OutputList()
{
newId();
m_codeGenList.setId(m_id);
}
OutputList::OutputList(const OutputList &ol) : m_outputGenList(ol.m_outputGenList)
{
m_id = ol.m_id;
refreshCodeGenerators();
}
OutputList &OutputList::operator=(const OutputList &ol)
{
if (this!=&ol)
{
m_id = ol.m_id;
m_outputGenList = ol.m_outputGenList;
refreshCodeGenerators();
}
return *this;
}
void OutputList::refreshCodeGenerators()
{
m_codeGenList.clear();
for (auto &e : m_outputGenList)
{
e.intf->addCodeGen(m_codeGenList);
}
m_codeGenList.setId(m_id);
}
void OutputList::newId()
{
m_id = ++g_outId;
}
void OutputList::syncEnabled()
{
for (const auto &e : m_outputGenList)
{
//printf("output %d isEnabled=%d\n",og->type(),og->isEnabled());
m_codeGenList.setEnabledFiltered(e.intf->type(),e.enabled);
}
}
void OutputList::disableAllBut(OutputType o)
{
//printf("disableAllBut(%d)\n",o);
for (auto &e : m_outputGenList)
{
if (e.intf->type()!=o) e.setEnabled(false);
}
syncEnabled();
}
void OutputList::enableAll()
{
//printf("enableAll()\n");
for (auto &e : m_outputGenList)
{
e.setEnabled(true);
}
syncEnabled();
}
void OutputList::disableAll()
{
//printf("enableAll()\n");
for (auto &e : m_outputGenList)
{
e.setEnabled(false);
}
syncEnabled();
}
void OutputList::disable(OutputType o)
{
//printf("disable(%d)\n",o);
for (auto &e : m_outputGenList)
{
if (e.intf->type()==o) e.setEnabled(false);
}
syncEnabled();
}
void OutputList::enable(OutputType o)
{
//printf("enable(%d)\n",o);
for (auto &e : m_outputGenList)
{
if (e.intf->type()==o) e.setEnabled(true);
}
syncEnabled();
}
bool OutputList::isEnabled(OutputType o)
{
for (const auto &e : m_outputGenList)
{
if (e.intf->type()==o) { return e.enabled; }
}
return false;
}
void OutputList::pushGeneratorState()
{
//printf("pushGeneratorState()\n");
for (auto &e : m_outputGenList)
{
e.enabledStack.push(e.enabled);
}
syncEnabled();
}
void OutputList::popGeneratorState()
{
//printf("popGeneratorState()\n");
for (auto &e : m_outputGenList)
{
if (!e.enabledStack.empty())
{
e.enabled = e.enabledStack.top();
e.enabledStack.pop();
}
}
syncEnabled();
}
void OutputList::generateDoc(const QCString &fileName,int startLine,
const Definition *ctx,const MemberDef * md,
const QCString &docStr,bool indexWords,
bool isExample,const QCString &exampleName,
bool singleLine,bool linkFromIndex,
bool markdownSupport)
{
if (docStr.isEmpty()) return;
auto count=std::count_if(m_outputGenList.begin(),m_outputGenList.end(),
[](const auto &e) { return e.enabled; });
// we want to validate irrespective of the number of output formats
// specified as:
// - when only XML format there should be warnings as well (XML has its own write routines)
// - no formats there should be warnings as well
auto parser { createDocParser() };
auto ast { validatingParseDoc(*parser.get(),
fileName,startLine,
ctx,md,docStr,indexWords,isExample,exampleName,
singleLine,linkFromIndex,markdownSupport) };
if (ast && count>0) writeDoc(ast.get(),ctx,md);
}
void OutputList::startFile(const QCString &name,const QCString &manName,const QCString &title, int hierarchyLevel)
{
newId();
m_codeGenList.setId(m_id);
foreach(&OutputGenIntf::startFile,name,manName,title,m_id,hierarchyLevel);
}
void OutputList::parseText(const QCString &textStr)
{
auto count=std::count_if(m_outputGenList.begin(),m_outputGenList.end(),
[](const auto &e) { return e.enabled; });
// we want to validate irrespective of the number of output formats
// specified as:
// - when only XML format there should be warnings as well (XML has its own write routines)
// - no formats there should be warnings as well
auto parser { createDocParser() };
auto ast { validatingParseText(*parser.get(), textStr) };
if (ast && count>0) writeDoc(ast.get(),nullptr,nullptr);
}
//--------------------------------------------------------------------------
void OutputCodeRecorder::startNewLine(int lineNr)
{
int orgSize = static_cast<int>(m_lineOffset.size());
if (orgSize<lineNr)
{
m_lineOffset.resize(lineNr);
for (int i=orgSize;i<lineNr;i++) // output lines can be skipped due to hidden comments so fill in the gap
{
//printf("%p: startCodeLine(%d) offset=%zu\n",(void*)this,i,m_calls.size());
m_lineOffset[i]=m_calls.size();
}
}
}
void OutputCodeRecorder::codify(const QCString &s)
{
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol) { ol->codify(s); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::startSpecialComment()
{
m_insideSpecialComment=true;
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol) { ol->startSpecialComment(); },
true
);
}
void OutputCodeRecorder::endSpecialComment()
{
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol) { ol->endSpecialComment(); },
true
);
m_insideSpecialComment=false;
}
void OutputCodeRecorder::writeCodeLink(CodeSymbolType type,
const QCString &ref,const QCString &file,
const QCString &anchor,const QCString &name,
const QCString &tooltip)
{
m_calls.emplace_back([](){ return true; },
[=](OutputCodeList *ol) { ol->writeCodeLink(type,ref,file,anchor,name,tooltip); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::writeLineNumber(const QCString &ref,const QCString &file,const QCString &anchor,
int lineNumber, bool writeLineAnchor)
{
startNewLine(lineNumber);
m_calls.emplace_back([&]() { return m_showLineNumbers; },
[=](OutputCodeList *ol) { ol->writeLineNumber(ref,file,anchor,lineNumber,writeLineAnchor); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::writeTooltip(const QCString &id, const DocLinkInfo &docInfo, const QCString &decl,
const QCString &desc, const SourceLinkInfo &defInfo, const SourceLinkInfo &declInfo)
{
m_calls.emplace_back([](){ return true; },
[=](OutputCodeList *ol) { ol->writeTooltip(id,docInfo,decl,desc,defInfo,declInfo); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::startCodeLine(int lineNr)
{
startNewLine(lineNr);
m_calls.emplace_back([](){ return true; },
[=](OutputCodeList *ol) { ol->startCodeLine(lineNr); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::endCodeLine()
{
m_calls.emplace_back([](){ return true; },
[=](OutputCodeList *ol) { ol->endCodeLine(); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::startFontClass(const QCString &c)
{
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol) { ol->startFontClass(c); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::endFontClass()
{
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol){ ol->endFontClass(); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::writeCodeAnchor(const QCString &name)
{
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol){ ol->writeCodeAnchor(name); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::startCodeFragment(const QCString &style)
{
}
void OutputCodeRecorder::endCodeFragment(const QCString &style)
{
}
void OutputCodeRecorder::startFold(int lineNr,const QCString &startMarker,const QCString &endMarker)
{
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol) { ol->startFold(lineNr,startMarker,endMarker); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::endFold()
{
m_calls.emplace_back([]() { return true; },
[=](OutputCodeList *ol) { ol->endFold(); },
m_insideSpecialComment
);
}
void OutputCodeRecorder::replay(OutputCodeList &ol,int startLine,int endLine,bool showLineNumbers,bool
stripCodeComments,size_t stripIndentAmount)
{
size_t startIndex = startLine>0 && startLine<=(int)m_lineOffset.size() ? m_lineOffset[startLine-1] : 0;
size_t endIndex = endLine>0 && endLine <=(int)m_lineOffset.size() ? m_lineOffset[ endLine-1] : m_calls.size();
//printf("startIndex=%zu endIndex=%zu\n",startIndex,endIndex);
// configure run time properties of the rendering
ol.stripCodeComments(stripCodeComments);
ol.setStripIndentAmount(stripIndentAmount);
m_showLineNumbers = showLineNumbers;
bool insideSpecialComment = false;
// in case the start of the special comment marker is outside of the fragment, start it here
if (startIndex<endIndex && m_calls[startIndex].insideSpecialComment)
{
ol.startSpecialComment();
insideSpecialComment = true;
}
// render the requested fragment of the pre-recorded output
for (size_t i=startIndex; i<endIndex; i++)
{
if (m_calls[i].condition())
{
insideSpecialComment = m_calls[i].insideSpecialComment;
m_calls[i].function(&ol);
}
}
// if we end the fragment inside a special comment, make sure we end it,
// and also the code line
if (insideSpecialComment)
{
ol.endSpecialComment();
ol.endCodeLine();
}
}
| 11,280
|
C++
|
.cpp
| 341
| 27.152493
| 118
| 0.635329
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,399
|
resourcemgr.cpp
|
doxygen_doxygen/src/resourcemgr.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2015 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.
*
*/
#include <map>
#include <string.h>
#include <cstdint>
#include "resourcemgr.h"
#include "util.h"
#include "version.h"
#include "message.h"
#include "config.h"
#include "portable.h"
class ResourceMgr::Private
{
public:
std::map<std::string,Resource> resources;
};
ResourceMgr &ResourceMgr::instance()
{
static ResourceMgr theInstance;
return theInstance;
}
ResourceMgr::ResourceMgr() : p(std::make_unique<Private>())
{
}
ResourceMgr::~ResourceMgr()
{
}
void ResourceMgr::registerResources(std::initializer_list<Resource> resources)
{
for (auto &res : resources)
{
p->resources.emplace(res.name,res);
}
}
bool ResourceMgr::writeCategory(const QCString &categoryName,const QCString &targetDir) const
{
for (auto &[name,res] : p->resources)
{
if (res.category==categoryName)
{
QCString pathName = targetDir+"/"+res.name;
std::ofstream f = Portable::openOutputStream(pathName);
bool ok=false;
if (f.is_open())
{
f.write(reinterpret_cast<const char *>(res.data),res.size);
ok = !f.fail();
}
if (!ok)
{
err("Failed to write resource '%s' to directory '%s'\n",res.name,qPrint(targetDir));
return FALSE;
}
}
}
return TRUE;
}
bool ResourceMgr::copyResourceAs(const QCString &name,const QCString &targetDir,const QCString &targetName,bool append) const
{
QCString pathName = targetDir+"/"+targetName;
const Resource *res = get(name);
if (res)
{
switch (res->type)
{
case Resource::Verbatim:
{
std::ofstream f = Portable::openOutputStream(pathName,append);
bool ok=false;
if (f.is_open())
{
f.write(reinterpret_cast<const char *>(res->data),res->size);
ok = !f.fail();
}
if (ok)
{
return TRUE;
}
}
break;
case Resource::Luminance:
{
QCString n = name;
n = n.left(n.length()-4)+".png"; // replace .lum by .png
const uint8_t *data = res->data;
uint16_t width = (data[0]<<8)+data[1];
uint16_t height = (data[2]<<8)+data[3];
ColoredImgDataItem images[2];
images[0].name = n.data();
images[0].width = width;
images[0].height = height;
images[0].content = &data[4];
images[0].alpha = nullptr;
images[1].name = nullptr; // terminator
writeColoredImgData(targetDir,images);
return TRUE;
}
break;
case Resource::LumAlpha:
{
QCString n = name;
n = n.left(n.length()-5)+".png"; // replace .luma by .png
const uint8_t *data = res->data;
uint16_t width = (data[0]<<8)+data[1];
uint16_t height = (data[2]<<8)+data[3];
ColoredImgDataItem images[2];
images[0].name = n.data();
images[0].width = width;
images[0].height = height;
images[0].content = &data[4];
images[0].alpha = &data[4+width*height];
images[1].name = nullptr; // terminator
writeColoredImgData(targetDir,images);
return TRUE;
}
break;
case Resource::CSS:
{
std::ofstream t = Portable::openOutputStream(pathName,append);
if (t.is_open())
{
QCString buf(res->size, QCString::ExplicitSize);
memcpy(buf.rawData(),res->data,res->size);
buf = replaceColorMarkers(buf);
if (name=="navtree.css")
{
t << substitute(buf,"$width",QCString().setNum(Config_getInt(TREEVIEW_WIDTH))+"px");
}
else
{
t << substitute(buf,"$doxygenversion",getDoxygenVersion());
}
return TRUE;
}
}
break;
case Resource::SVG:
{
std::ofstream t = Portable::openOutputStream(pathName,append);
if (t.is_open())
{
QCString buf(res->size, QCString::ExplicitSize);
memcpy(buf.rawData(),res->data,res->size);
t << replaceColorMarkers(buf);
return TRUE;
}
}
}
}
else
{
err("requested resource '%s' not compiled in!\n",qPrint(name));
}
return FALSE;
}
bool ResourceMgr::copyResource(const QCString &name,const QCString &targetDir) const
{
return copyResourceAs(name,targetDir,name);
}
const Resource *ResourceMgr::get(const QCString &name) const
{
auto it = p->resources.find(name.str());
if (it!=p->resources.end()) return &it->second;
return nullptr;
}
QCString ResourceMgr::getAsString(const QCString &name) const
{
const Resource *res = get(name);
if (res)
{
QCString result(res->size, QCString::ExplicitSize);
memcpy(result.rawData(),res->data,res->size);
return result;
}
else
{
return QCString();
}
}
| 5,610
|
C++
|
.cpp
| 191
| 22.937173
| 125
| 0.59175
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,400
|
portable.cpp
|
doxygen_doxygen/src/portable.cpp
|
#include "portable.h"
#include "qcstring.h"
#include <stdlib.h>
#include <stdio.h>
#include <chrono>
#include <thread>
#include <mutex>
#include <map>
#if defined(_WIN32) && !defined(__CYGWIN__)
#undef UNICODE
#define _WIN32_DCOM
#include <windows.h>
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
extern char **environ;
#endif
#include <assert.h>
#include <ctype.h>
#include <map>
#include <string>
#include "fileinfo.h"
#include "message.h"
#include "util.h"
#include "dir.h"
#ifndef NODEBUG
#include "debug.h"
#endif
#if !defined(_WIN32) || defined(__CYGWIN__)
static bool environmentLoaded = false;
static std::map<std::string,std::string> proc_env = std::map<std::string,std::string>();
#endif
//---------------------------------------------------------------------------------------------------------
/*! Helper class to keep time interval per thread */
class SysTimeKeeper
{
public:
static SysTimeKeeper &instance();
//! start a timer for this thread
void start()
{
std::lock_guard<std::mutex> lock(m_mutex);
m_startTimes[std::this_thread::get_id()] = std::chrono::steady_clock::now();
}
//! ends a timer for this thread, accumulate time difference since start
void stop()
{
std::lock_guard<std::mutex> lock(m_mutex);
std::chrono::steady_clock::time_point endTime = std::chrono::steady_clock::now();
auto it = m_startTimes.find(std::this_thread::get_id());
if (it == m_startTimes.end())
{
err("SysTimeKeeper stop() called without matching start()\n");
return;
}
double timeSpent = static_cast<double>(std::chrono::duration_cast<
std::chrono::microseconds>(endTime - it->second).count())/1000000.0;
//printf("timeSpent on thread %zu: %.4f seconds\n",std::hash<std::thread::id>{}(std::this_thread::get_id()),timeSpent);
m_elapsedTime += timeSpent;
}
double elapsedTime() const { return m_elapsedTime; }
private:
struct TimeData
{
std::chrono::steady_clock::time_point startTime;
};
std::map<std::thread::id,std::chrono::steady_clock::time_point> m_startTimes;
double m_elapsedTime = 0;
std::mutex m_mutex;
};
SysTimeKeeper &SysTimeKeeper::instance()
{
static SysTimeKeeper theInstance;
return theInstance;
}
class AutoTimeKeeper
{
public:
AutoTimeKeeper() { SysTimeKeeper::instance().start(); }
~AutoTimeKeeper() { SysTimeKeeper::instance().stop(); }
};
double Portable::getSysElapsedTime()
{
return SysTimeKeeper::instance().elapsedTime();
}
//---------------------------------------------------------------------------------------------------------
int Portable::system(const QCString &command,const QCString &args,bool commandHasConsole)
{
if (command.isEmpty()) return 1;
AutoTimeKeeper timeKeeper;
#if defined(_WIN32) && !defined(__CYGWIN__)
QCString commandCorrectedPath = substitute(command,'/','\\');
QCString fullCmd=commandCorrectedPath;
#else
QCString fullCmd=command;
#endif
fullCmd=fullCmd.stripWhiteSpace();
if (fullCmd.at(0)!='"' && fullCmd.find(' ')!=-1)
{
// add quotes around command as it contains spaces and is not quoted already
fullCmd="\""+fullCmd+"\"";
}
fullCmd += " ";
fullCmd += args;
#ifndef NODEBUG
Debug::print(Debug::ExtCmd,0,"Executing external command `%s`\n",qPrint(fullCmd));
#endif
#if !defined(_WIN32) || defined(__CYGWIN__)
(void)commandHasConsole;
/*! taken from the system() manpage on my Linux box */
int pid,status=0;
#ifdef _OS_SOLARIS // for Solaris we use vfork since it is more memory efficient
// on Solaris fork() duplicates the memory usage
// so we use vfork instead
// spawn shell
if ((pid=vfork())<0)
{
status=-1;
}
else if (pid==0)
{
execl("/bin/sh","sh","-c",fullCmd.data(),(char*)0);
_exit(127);
}
else
{
while (waitpid(pid,&status,0 )<0)
{
if (errno!=EINTR)
{
status=-1;
break;
}
}
}
return status;
#else // Other Unices just use fork
pid = fork();
if (pid==-1)
{
perror("fork error");
return -1;
}
if (pid==0)
{
const char * const argv[4] = { "sh", "-c", fullCmd.data(), 0 };
execve("/bin/sh",const_cast<char * const*>(argv),environ);
exit(127);
}
for (;;)
{
if (waitpid(pid,&status,0)==-1)
{
if (errno!=EINTR) return -1;
}
else
{
if (WIFEXITED(status))
{
return WEXITSTATUS(status);
}
else
{
return status;
}
}
}
#endif // !_OS_SOLARIS
#else // Win32 specific
if (commandHasConsole)
{
return ::system(fullCmd.data());
}
else
{
// Because ShellExecuteEx can delegate execution to Shell extensions
// (data sources, context menu handlers, verb implementations) that
// are activated using Component Object Model (COM), COM should be
// initialized before ShellExecuteEx is called. Some Shell extensions
// require the COM single-threaded apartment (STA) type.
// For that case COM is initialized as follows
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
uint16_t *commandw = nullptr;
recodeUtf8StringToW( commandCorrectedPath, &commandw );
uint16_t *argsw = nullptr;
recodeUtf8StringToW( args, &argsw );
// gswin32 is a GUI api which will pop up a window and run
// asynchronously. To prevent both, we use ShellExecuteEx and
// WaitForSingleObject (thanks to Robert Golias for the code)
SHELLEXECUTEINFOW sInfo = {
sizeof(SHELLEXECUTEINFOW), /* structure size */
SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI, /* tell us the process
* handle so we can wait till it's done |
* do not display msg box if error
*/
nullptr, /* window handle */
nullptr, /* action to perform: open */
(LPCWSTR)commandw, /* file to execute */
(LPCWSTR)argsw, /* argument list */
nullptr, /* use current working dir */
SW_HIDE, /* minimize on start-up */
nullptr, /* application instance handle */
nullptr, /* ignored: id list */
nullptr, /* ignored: class name */
nullptr, /* ignored: key class */
0, /* ignored: hot key */
nullptr, /* ignored: icon */
nullptr /* resulting application handle */
};
if (!ShellExecuteExW(&sInfo))
{
delete[] commandw;
delete[] argsw;
return -1;
}
else if (sInfo.hProcess) /* executable was launched, wait for it to finish */
{
WaitForSingleObject(sInfo.hProcess,INFINITE);
/* get process exit code */
DWORD exitCode;
bool retval = GetExitCodeProcess(sInfo.hProcess,&exitCode);
CloseHandle(sInfo.hProcess);
delete[] commandw;
delete[] argsw;
if (!retval) return -1;
return exitCode;
}
}
#endif
return 1; // we should never get here
}
uint32_t Portable::pid()
{
uint32_t pid;
#if !defined(_WIN32) || defined(__CYGWIN__)
pid = static_cast<uint32_t>(getpid());
#else
pid = static_cast<uint32_t>(GetCurrentProcessId());
#endif
return pid;
}
#if !defined(_WIN32) || defined(__CYGWIN__)
void loadEnvironment()
{
if(environ != nullptr)
{
unsigned int i = 0;
char* current = environ[i];
while(current != nullptr) // parse all strings contained by environ til the last element (nullptr)
{
std::string env_var(current); // load current environment variable string
size_t pos = env_var.find("=");
if(pos != std::string::npos) // only parse the variable, if it is a valid environment variable...
{ // ...which has to contain an equal sign as delimiter by definition
std::string name = env_var.substr(0,pos); // the string til the equal sign contains the name
std::string value = env_var.substr(pos + 1); // the string from the equal sign contains the value
proc_env[name] = std::move(value); // save the value by the name as its key in the classes map
}
i++;
current = environ[i];
}
}
environmentLoaded = true;
}
#endif
void Portable::setenv(const QCString &name,const QCString &value)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
SetEnvironmentVariable(name.data(),!value.isEmpty() ? value.data() : "");
#else
if(!environmentLoaded) // if the environment variables are not loaded already...
{ // ...call loadEnvironment to store them in class
loadEnvironment();
}
proc_env[name.str()] = value.str(); // create or replace existing value
::setenv(name.data(),value.data(),1);
#endif
}
void Portable::unsetenv(const QCString &variable)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
SetEnvironmentVariable(variable.data(),nullptr);
#else
/* Some systems don't have unsetenv(), so we do it ourselves */
if (variable.isEmpty() || variable.find('=')!=-1)
{
return; // not properly formatted
}
auto it = proc_env.find(variable.str());
if (it != proc_env.end())
{
proc_env.erase(it);
::unsetenv(variable.data());
}
#endif
}
QCString Portable::getenv(const QCString &variable)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
#define ENV_BUFSIZE 32768
LPTSTR pszVal = (LPTSTR) malloc(ENV_BUFSIZE*sizeof(TCHAR));
if (GetEnvironmentVariable(variable.data(),pszVal,ENV_BUFSIZE) == 0) return "";
QCString out;
out = pszVal;
free(pszVal);
return out;
#undef ENV_BUFSIZE
#else
if(!environmentLoaded) // if the environment variables are not loaded already...
{ // ...call loadEnvironment to store them in class
loadEnvironment();
}
if (proc_env.find(variable.str()) != proc_env.end())
{
return QCString(proc_env[variable.str()]);
}
else
{
return QCString();
}
#endif
}
FILE *Portable::fopen(const QCString &fileName,const QCString &mode)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
uint16_t *fn = nullptr;
size_t fn_len = recodeUtf8StringToW(fileName,&fn);
uint16_t *m = nullptr;
size_t m_len = recodeUtf8StringToW(mode,&m);
FILE *result = nullptr;
if (fn_len!=(size_t)-1 && m_len!=(size_t)-1)
{
result = _wfopen((wchar_t*)fn,(wchar_t*)m);
}
delete[] fn;
delete[] m;
return result;
#else
return ::fopen(fileName.data(),mode.data());
#endif
}
int Portable::fclose(FILE *f)
{
return ::fclose(f);
}
QCString Portable::pathSeparator()
{
#if defined(_WIN32) && !defined(__CYGWIN__)
return "\\";
#else
return "/";
#endif
}
QCString Portable::pathListSeparator()
{
#if defined(_WIN32) && !defined(__CYGWIN__)
return ";";
#else
return ":";
#endif
}
static bool ExistsOnPath(const QCString &fileName)
{
FileInfo fi1(fileName.str());
if (fi1.exists()) return true;
QCString paths = Portable::getenv("PATH");
char listSep = Portable::pathListSeparator()[0];
char pathSep = Portable::pathSeparator()[0];
int strt = 0;
int idx;
while ((idx = paths.find(listSep,strt)) != -1)
{
QCString locFile(paths.mid(strt,idx-strt));
locFile += pathSep;
locFile += fileName;
FileInfo fi(locFile.str());
if (fi.exists()) return true;
strt = idx + 1;
}
// to be sure the last path component is checked as well
QCString locFile(paths.mid(strt));
if (!locFile.isEmpty())
{
locFile += pathSep;
locFile += fileName;
FileInfo fi(locFile.str());
if (fi.exists()) return true;
}
return false;
}
bool Portable::checkForExecutable(const QCString &fileName)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
const char *extensions[] = {".bat",".com",".exe"};
for (int i = 0; i < sizeof(extensions) / sizeof(*extensions); i++)
{
if (ExistsOnPath(fileName + extensions[i])) return true;
}
return false;
#else
return ExistsOnPath(fileName);
#endif
}
const char *Portable::ghostScriptCommand()
{
#if defined(_WIN32) && !defined(__CYGWIN__)
static const char *gsexe = nullptr;
if (!gsexe)
{
const char *gsExec[] = {"gswin32c.exe","gswin64c.exe"};
for (int i = 0; i < sizeof(gsExec) / sizeof(*gsExec); i++)
{
if (ExistsOnPath(gsExec[i]))
{
gsexe = gsExec[i];
return gsexe;
}
}
gsexe = gsExec[0];
return gsexe;
}
return gsexe;
#else
return "gs";
#endif
}
const char *Portable::commandExtension()
{
#if defined(_WIN32) && !defined(__CYGWIN__)
return ".exe";
#else
return "";
#endif
}
bool Portable::fileSystemIsCaseSensitive()
{
#if defined(_WIN32) || defined(macintosh) || defined(__MACOSX__) || defined(__APPLE__) || defined(__CYGWIN__)
return FALSE;
#else
return TRUE;
#endif
}
FILE * Portable::popen(const QCString &name,const QCString &type)
{
#if defined(_MSC_VER) || defined(__BORLANDC__)
return ::_popen(name.data(),type.data());
#else
return ::popen(name.data(),type.data());
#endif
}
int Portable::pclose(FILE *stream)
{
#if defined(_MSC_VER) || defined(__BORLANDC__)
return ::_pclose(stream);
#else
return ::pclose(stream);
#endif
}
bool Portable::isAbsolutePath(const QCString &fileName)
{
const char *fn = fileName.data();
# ifdef _WIN32
if (fileName.length()>1 && isalpha(fileName[0]) && fileName[1]==':') fn+=2;
# endif
char const fst = fn[0];
if (fst == '/') return true;
# ifdef _WIN32
if (fst == '\\') return true;
# endif
return false;
}
/**
* Correct a possible wrong PATH variable
*
* This routine was inspired by the cause for bug 766059 was that in the Windows path there were forward slashes.
*/
void Portable::correctPath(const StringVector &extraPaths)
{
QCString p = Portable::getenv("PATH");
bool first=true;
QCString result;
#if defined(_WIN32) && !defined(__CYGWIN__)
for (const auto &path : extraPaths)
{
if (!first) result+=';';
first=false;
result += substitute(QCString(path),"/","\\");
}
if (!result.isEmpty() && !p.isEmpty()) result+=';';
result += substitute(p,"/","\\");
#else
for (const auto &path : extraPaths)
{
if (!first) result+=':';
first=false;
result += QCString(path);
}
if (!result.isEmpty() && !p.isEmpty()) result+=':';
result += p;
#endif
if (result!=p) Portable::setenv("PATH",result.data());
//printf("settingPath(%s) #extraPaths=%zu\n",Portable::getenv("PATH").data(),extraPaths.size());
}
void Portable::unlink(const QCString &fileName)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
_unlink(fileName.data());
#else
::unlink(fileName.data());
#endif
}
void Portable::setShortDir()
{
#if defined(_WIN32) && !defined(__CYGWIN__)
long length = 0;
TCHAR* buffer = nullptr;
// First obtain the size needed by passing nullptr and 0.
length = GetShortPathName(Dir::currentDirPath().c_str(), nullptr, 0);
// Dynamically allocate the correct size
// (terminating null char was included in length)
buffer = new TCHAR[length];
// Now simply call again using same (long) path.
length = GetShortPathName(Dir::currentDirPath().c_str(), buffer, length);
// Set the correct directory (short name)
Dir::setCurrent(buffer);
delete [] buffer;
#endif
}
/* Return the first occurrence of NEEDLE in HAYSTACK. */
static const char * portable_memmem (const char *haystack, size_t haystack_len,
const char *needle, size_t needle_len)
{
const char *const last_possible = haystack + haystack_len - needle_len;
if (needle_len == 0)
// The first occurrence of the empty string should to occur at the beginning of the string.
{
return haystack;
}
// Sanity check
if (haystack_len < needle_len)
{
return nullptr;
}
for (const char *begin = haystack; begin <= last_possible; ++begin)
{
if (begin[0] == needle[0] && !memcmp(&begin[1], needle + 1, needle_len - 1))
{
return begin;
}
}
return nullptr;
}
const char *Portable::strnstr(const char *haystack, const char *needle, size_t haystack_len)
{
size_t needle_len = strnlen(needle, haystack_len);
if (needle_len < haystack_len || !needle[needle_len])
{
const char *x = portable_memmem(haystack, haystack_len, needle, needle_len);
if (x && !memchr(haystack, 0, x - haystack))
{
return x;
}
}
return nullptr;
}
const char *Portable::devNull()
{
#if defined(_WIN32) && !defined(__CYGWIN__)
return "NUL";
#else
return "/dev/null";
#endif
}
size_t Portable::recodeUtf8StringToW(const QCString &inputStr,uint16_t **outBuf)
{
if (inputStr.isEmpty() || outBuf==nullptr) return 0; // empty input or invalid output
void *handle = portable_iconv_open("UTF-16LE","UTF-8");
if (handle==reinterpret_cast<void *>(-1)) return 0; // invalid encoding
size_t len = inputStr.length();
uint16_t *buf = new uint16_t[len+1];
*outBuf = buf;
size_t inRemains = len;
size_t outRemains = len*sizeof(uint16_t)+2; // chars + \0
const char *p = inputStr.data();
portable_iconv(handle,&p,&inRemains,reinterpret_cast<char **>(&buf),&outRemains);
*buf=0;
portable_iconv_close(handle);
return len;
}
//----------------------------------------------------------------------------------------
// We need to do this part last as including filesystem.hpp earlier
// causes the code above to fail to compile on Windows.
#include "filesystem.hpp"
namespace fs = ghc::filesystem;
std::ofstream Portable::openOutputStream(const QCString &fileName,bool append)
{
std::ios_base::openmode mode = std::ofstream::out | std::ofstream::binary;
if (append) mode |= std::ofstream::app;
#if defined(__clang__) && defined(__MINGW32__)
return std::ofstream(fs::path(fileName.str()).wstring(), mode);
#else
return std::ofstream(fs::path(fileName.str()), mode);
#endif
}
std::ifstream Portable::openInputStream(const QCString &fileName,bool binary, bool openAtEnd)
{
std::ios_base::openmode mode = std::ifstream::in | std::ifstream::binary;
if (binary) mode |= std::ios::binary;
if (openAtEnd) mode |= std::ios::ate;
#if defined(__clang__) && defined(__MINGW32__)
return std::ifstream(fs::path(fileName.str()).wstring(), mode);
#else
return std::ifstream(fs::path(fileName.str()), mode);
#endif
}
| 18,712
|
C++
|
.cpp
| 617
| 26.470016
| 129
| 0.626963
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,401
|
codefragment.cpp
|
doxygen_doxygen/src/codefragment.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 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.
*
*/
#include <mutex>
#include <unordered_map>
#include <map>
#include "codefragment.h"
#include "util.h"
#include "doxygen.h"
#include "parserintf.h"
#include "outputlist.h"
#include "clangparser.h"
#include "trace.h"
#include "fileinfo.h"
#include "filedef.h"
#include "portable.h"
#include "message.h"
struct CodeFragmentManager::Private
{
struct BlockMarker
{
int indent=0;
std::string key;
std::vector<int> lines;
};
struct FragmentInfo
{
QCString fileContents;
QCString fileContentsTrimLeft;
FragmentInfo() { recorderCodeList.add<OutputCodeRecorder>(); }
void findBlockMarkers();
OutputCodeList recorderCodeList;
std::map<int,BlockMarker> blocks;
std::map<std::string,const BlockMarker*> blocksById;
std::mutex mutex;
};
std::unordered_map<std::string,std::unique_ptr<FragmentInfo> > fragments;
std::mutex mutex;
};
void CodeFragmentManager::Private::FragmentInfo::findBlockMarkers()
{
AUTO_TRACE("findBlockMarkers() size={}",fileContents.size());
// give fileContents and a list of candidate [XYZ] labels with/without trim left flag (from commentscan?)
if (fileContents.length()==0) return;
// find the potential snippet blocks (can also be other array like stuff in the file)
const char *s=fileContents.data();
int lineNr=1;
char c=0;
const char *foundOpen=nullptr;
std::unordered_map<std::string,BlockMarker> candidates;
while ((c=*s))
{
if (c=='[')
{
foundOpen=s;
}
else if (foundOpen && c==']' && foundOpen+1<s) // non-empty [...] section
{
std::string key(foundOpen+1,s-foundOpen-1);
candidates[key].lines.push_back(lineNr);
}
else if (c=='\n')
{
foundOpen=nullptr;
lineNr++;
}
s++;
}
// Sort the valid snippet blocks by line number, Look for blocks that appears twice,
// where candidate has block id as key and the start and end line as value.
// Store the key in marker.key
for (auto &kv : candidates)
{
auto &marker = kv.second;
if (marker.lines.size()==2 && marker.lines[0]+1<=marker.lines[1]-1)
{
marker.key = kv.first;
int startLine = marker.lines[0];
blocks[startLine] = marker;
blocksById["["+kv.first+"]"] = &blocks[startLine];
}
}
// determine the shared indentation for each line in each block, and store it in marker.indent
s=fileContents.data();
static auto gotoLine = [](const char *startBuf, const char *startPos, int startLine, int targetLine) -> const char *
{
char cc=0;
if (targetLine<startLine)
{
//printf("gotoLine(pos=%p,start=%d,target=%d) backward\n",(void*)startPos,startLine,targetLine);
while (startLine>=targetLine && startPos>=startBuf && (cc=*startPos--)) { if (cc=='\n') startLine--; }
if (startPos>startBuf)
{
// given fragment:
// line1\n
// line2\n
// line3
// and targetLine==2 then startPos ends at character '1' of line 1 before we detect that startLine<targetLine,
// so we need to advance startPos with 2 to be at the start of line2, unless we are already at the first line.
startPos+=2;
}
//printf("result=[%s]\n",qPrint(QCString(startPos).left(20)));
}
else
{
//printf("gotoLine(pos=%p,start=%d,target=%d) forward\n",(void*)startPos,startLine,targetLine);
while (startLine<targetLine && (cc=*startPos++)) { if (cc=='\n') startLine++; }
//printf("result=[%s]\n",qPrint(QCString(startPos).left(20)));
}
return startPos;
};
static auto lineIndent = [](const char *&ss) -> int
{
int tabSize=Config_getInt(TAB_SIZE);
int col = 0;
char cc = 0;
while ((cc=*ss++))
{
if (cc==' ') col++;
else if (cc=='\t') col+=tabSize-(col%tabSize);
else
{
// goto end of the line
while ((cc=*ss++) && cc!='\n');
break;
}
}
return col;
};
lineNr=1;
const char *startBuf = s;
for (auto &kv : blocks)
{
auto &marker = kv.second;
s = gotoLine(startBuf,s,lineNr,marker.lines[0]+1);
lineNr=marker.lines[1];
const char *e = gotoLine(startBuf,s,marker.lines[0]+1,lineNr);
const char *ss = s;
int minIndent=100000;
while (ss<e)
{
int indent = lineIndent(ss);
if (indent<minIndent)
{
minIndent=indent;
if (minIndent==0) break;
}
}
marker.indent = minIndent;
AUTO_TRACE_ADD("found snippet key='{}' range=[{}..{}] indent={}",
marker.key,
marker.lines[0]+1,
marker.lines[1]-1,
marker.indent);
s=e;
}
}
CodeFragmentManager::CodeFragmentManager() : p(std::make_unique<Private>())
{
}
CodeFragmentManager::~CodeFragmentManager() = default;
CodeFragmentManager &CodeFragmentManager::instance()
{
static CodeFragmentManager m;
return m;
}
static QCString readTextFileByName(const QCString &file)
{
AUTO_TRACE("file={}",file);
if (Portable::isAbsolutePath(file))
{
FileInfo fi(file.str());
if (fi.exists())
{
return fileToString(file,Config_getBool(FILTER_SOURCE_FILES));
}
}
const StringVector &examplePathList = Config_getList(EXAMPLE_PATH);
for (const auto &s : examplePathList)
{
std::string absFileName = s+(Portable::pathSeparator()+file).str();
FileInfo fi(absFileName);
if (fi.exists())
{
return fileToString(QCString(absFileName),Config_getBool(FILTER_SOURCE_FILES));
}
}
// as a fallback we also look in the exampleNameDict
bool ambig=false;
FileDef *fd = findFileDef(Doxygen::exampleNameLinkedMap,file,ambig);
if (fd)
{
if (ambig)
{
err("included file name '%s' is ambiguous.\nPossible candidates:\n%s\n",qPrint(file),
qPrint(showFileDefMatches(Doxygen::exampleNameLinkedMap,file))
);
}
return fileToString(fd->absFilePath(),Config_getBool(FILTER_SOURCE_FILES));
}
else
{
err("included file %s is not found. Check your EXAMPLE_PATH\n",qPrint(file));
}
return QCString();
}
void CodeFragmentManager::parseCodeFragment(OutputCodeList & codeOutList,
const QCString & fileName,
const QCString & blockId,
const QCString & scopeName,
bool showLineNumbers,
bool trimLeft,
bool stripCodeComments
)
{
AUTO_TRACE("CodeFragmentManager::parseCodeFragment({},blockId={},scopeName={},showLineNumber={},trimLeft={},stripCodeComments={}",
fileName, blockId, scopeName, showLineNumbers, trimLeft, stripCodeComments);
std::string fragmentKey=fileName.str()+":"+scopeName.str();
std::unordered_map< std::string,std::unique_ptr<Private::FragmentInfo> >::iterator it;
bool inserted = false;
{
// create new entry if it is not yet in the map
std::lock_guard lock(p->mutex);
it = p->fragments.find(fragmentKey);
if (it == p->fragments.end())
{
it = p->fragments.emplace(fragmentKey, std::make_unique<Private::FragmentInfo>()).first;
inserted = true;
AUTO_TRACE_ADD("new fragment");
}
}
// only lock the one item we are working with
auto &codeFragment = it->second;
std::lock_guard lock(codeFragment->mutex);
if (inserted) // new entry, need to parse the file and record the output and cache it
{
SrcLangExt langExt = getLanguageFromFileName(fileName);
FileInfo cfi( fileName.str() );
auto fd = createFileDef( cfi.dirPath(), cfi.fileName() );
auto intf = Doxygen::parserManager->getCodeParser(getFileNameExtension(fileName));
intf->resetCodeParserState();
bool filterSourceFiles = Config_getBool(FILTER_SOURCE_FILES);
bool needs2PassParsing =
Doxygen::parseSourcesNeeded && // we need to parse (filtered) sources for cross-references
!filterSourceFiles && // but user wants to show sources as-is
!getFileFilter(fileName,TRUE).isEmpty(); // and there is a filter used while parsing
codeFragment->fileContents = readTextFileByName(fileName);
//printf("fileContents=[%s]\n",qPrint(codeFragment->fileContents));
if (needs2PassParsing)
{
OutputCodeList devNullList;
devNullList.add<DevNullCodeGenerator>();
intf->parseCode(devNullList,
scopeName,
codeFragment->fileContents,
langExt,
stripCodeComments, // actually not important here
false,
QCString()
);
}
codeFragment->findBlockMarkers();
if (codeFragment->fileContents.length()>0) // parse the normal version
{
intf->parseCode(codeFragment->recorderCodeList,
scopeName,
codeFragment->fileContents,
langExt, // lang
false, // strip code comments (overruled before replaying)
false, // isExampleBlock
QCString(), // exampleName
fd.get(), // fileDef
-1, // startLine
-1, // endLine
true, // inlineFragment
nullptr, // memberDef
true, // showLineNumbers
nullptr, // searchCtx
false // collectXRefs
);
}
}
// use the recorded OutputCodeList from the cache to output a pre-recorded fragment
auto blockKv = codeFragment->blocksById.find(blockId.str());
if (blockKv != codeFragment->blocksById.end())
{
const auto &marker = blockKv->second;
int startLine = marker->lines[0];
int endLine = marker->lines[1];
int indent = marker->indent;
AUTO_TRACE_ADD("replay(start={},end={},indent={}) fileContentsTrimLeft.empty()={}",
startLine,endLine,indent,codeFragment->fileContentsTrimLeft.isEmpty());
auto recorder = codeFragment->recorderCodeList.get<OutputCodeRecorder>(OutputType::Recorder);
recorder->replay(codeOutList,
startLine+1,
endLine,
showLineNumbers,
stripCodeComments,
trimLeft ? static_cast<size_t>(indent) : 0
);
}
else
{
AUTO_TRACE_ADD("block not found!");
}
}
| 11,218
|
C++
|
.cpp
| 317
| 28.984227
| 132
| 0.619096
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,402
|
dotfilepatcher.cpp
|
doxygen_doxygen/src/dotfilepatcher.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include "dotfilepatcher.h"
#include "dotrunner.h"
#include "config.h"
#include "message.h"
#include "docparser.h"
#include "docnode.h"
#include "doxygen.h"
#include "util.h"
#include "dot.h"
#include "dir.h"
#include "portable.h"
// top part of the interactive SVG header
static const char svgZoomHeader0[] = R"svg(
<svg id="main" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" onload="init(evt)">
)svg";
static const char svgZoomHeader0_noinit[] = R"svg(
<svg id="main" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve">
)svg";
static const char svgZoomHeader1[] = R"svg(
<style type="text/css"><![CDATA[
.node, .edge {opacity: 0.7;}
.node.selected, .edge.selected {opacity: 1;}
.edge:hover path { stroke: red; }
.edge:hover polygon { stroke: red; fill: red; }
]]></style>
)svg";
// conditional part of the interactive SVG header in case the navigation panel is shown
static const char svgZoomHeader2[] = R"svg(
<defs>
<circle id="rim" cx="0" cy="0" r="7"/>
<circle id="rim2" cx="0" cy="0" r="3.5"/>
<g id="zoomPlus">
<use xlink:href="#rim" fill="#404040"><set attributeName="fill" to="#808080" begin="zoomplus.mouseover" end="zoomplus.mouseout"/></use>
<path d="M-4,0h8M0,-4v8" fill="none" stroke="white" stroke-width="1.5" pointer-events="none"/>
</g>
<g id="zoomMin">
<use xlink:href="#rim" fill="#404040"><set attributeName="fill" to="#808080" begin="zoomminus.mouseover" end="zoomminus.mouseout"/></use>
<path d="M-4,0h8" fill="none" stroke="white" stroke-width="1.5" pointer-events="none"/>
</g>
<g id="arrowUp" transform="translate(30 24)">
<use xlink:href="#rim"/>
<path pointer-events="none" fill="none" stroke="white" stroke-width="1.5" d="M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5"/>
</g>
<g id="arrowRight" transform="rotate(90) translate(36 -43)">
<use xlink:href="#rim"/>
<path pointer-events="none" fill="none" stroke="white" stroke-width="1.5" d="M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5"/>
</g>
<g id="arrowDown" transform="rotate(180) translate(-30 -48)">
<use xlink:href="#rim"/>
<path pointer-events="none" fill="none" stroke="white" stroke-width="1.5" d="M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5"/>
</g>
<g id="arrowLeft" transform="rotate(270) translate(-36 17)">
<use xlink:href="#rim"/>
<path pointer-events="none" fill="none" stroke="white" stroke-width="1.5" d="M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5"/>
</g>
<g id="resetDef">
<use xlink:href="#rim2" fill="#404040"><set attributeName="fill" to="#808080" begin="reset.mouseover" end="reset.mouseout"/></use>
</g>
</defs>
)svg";
// part of the footer that is needed if the navigation panel is shown
static const char svgZoomFooter1[] = R"svg(
<g id="navigator" transform="translate(0 0)" fill="#404254">
<rect fill="#f2f5e9" fill-opacity="0.5" stroke="#606060" stroke-width=".5" x="0" y="0" width="60" height="60"/>
<use id="zoomplus" xlink:href="#zoomPlus" x="17" y="9" onmousedown="handleZoom(evt,'in')"/>
<use id="zoomminus" xlink:href="#zoomMin" x="42" y="9" onmousedown="handleZoom(evt,'out')"/>
<use id="reset" xlink:href="#resetDef" x="30" y="36" onmousedown="handleReset()"/>
<use id="arrowup" xlink:href="#arrowUp" x="0" y="0" onmousedown="handlePan(0,-1)"/>
<use id="arrowright" xlink:href="#arrowRight" x="0" y="0" onmousedown="handlePan(1,0)"/>
<use id="arrowdown" xlink:href="#arrowDown" x="0" y="0" onmousedown="handlePan(0,1)"/>
<use id="arrowleft" xlink:href="#arrowLeft" x="0" y="0" onmousedown="handlePan(-1,0)"/>
</g>
<svg viewBox="0 0 15 15" width="100%" height="30px" preserveAspectRatio="xMaxYMin meet">
<g id="arrow_out" transform="scale(0.3 0.3)">
<a xlink:href="$orgname" target="_base">
<rect id="button" ry="5" rx="5" y="6" x="6" height="38" width="38"
fill="#f2f5e9" fill-opacity="0.5" stroke="#606060" stroke-width="1.0"/>
<path id="arrow"
d="M 11.500037,31.436501 C 11.940474,20.09759 22.043105,11.32322 32.158766,21.979434 L 37.068811,17.246167 C 37.068811,17.246167 37.088388,32 37.088388,32 L 22.160133,31.978069 C 22.160133,31.978069 26.997745,27.140456 26.997745,27.140456 C 18.528582,18.264221 13.291696,25.230495 11.500037,31.436501 z"
style="fill:#404040;"/>
</a>
</g>
</svg>
)svg";
// generic part of the interactive SVG footer
static const char svgZoomFooter2[] = R"svg(
<style type='text/css'>
<![CDATA[
[data-mouse-over-selected='false'] { opacity: 0.7; }
[data-mouse-over-selected='true'] { opacity: 1.0; }
]]>
</style>
<script type="application/ecmascript"><![CDATA[
document.addEventListener('DOMContentLoaded', (event) => {
highlightEdges();
highlightAdjacentNodes();
});
]]></script>
</svg>
)svg";
static QCString replaceRef(const QCString &buf,const QCString &relPath,
bool urlOnly,const QCString &context,const QCString &target=QCString())
{
// search for href="...", store ... part in link
QCString href = "href";
//bool isXLink=FALSE;
int len = 6;
int indexS = buf.find("href=\""), indexE = 0;
bool targetAlreadySet = buf.find("target=")!=-1;
if (indexS>5 && buf.find("xlink:href=\"")!=-1) // XLink href (for SVG)
{
indexS-=6;
len+=6;
href.prepend("xlink:");
//isXLink=TRUE;
}
if (indexS>=0 && (indexE=buf.find('"',indexS+len))!=-1)
{
QCString link = buf.mid(indexS+len,indexE-indexS-len);
QCString result;
if (urlOnly) // for user defined dot graphs
{
if (link.startsWith("\\ref ") || link.startsWith("@ref ")) // \ref url
{
result=href+"=\"";
// fake ref node to resolve the url
auto parser { createDocParser() };
auto dfAst { createRef( *parser.get(), link.mid(5), context ) };
auto dfAstImpl = dynamic_cast<const DocNodeAST*>(dfAst.get());
const DocRef *df = std::get_if<DocRef>(&dfAstImpl->root);
result+=externalRef(relPath,df->ref(),TRUE);
if (!df->file().isEmpty())
{
QCString fn = df->file();
addHtmlExtensionIfMissing(fn);
result += fn;
}
if (!df->anchor().isEmpty())
{
result += "#" + df->anchor();
}
result += "\"";
}
else
{
result = href+"=\"" + link + "\"";
}
}
else // ref$url (external ref via tag file), or $url (local ref)
{
int marker = link.find('$');
if (marker!=-1)
{
QCString ref = link.left(marker);
QCString url = link.mid(marker+1);
if (!ref.isEmpty())
{
result = externalLinkTarget(true);
if (!result.isEmpty())targetAlreadySet=true;
}
result+= href+"=\"";
result+=externalRef(relPath,ref,TRUE);
result+= url + "\"";
}
else // should not happen, but handle properly anyway
{
result = href+"=\"" + link + "\"";
}
}
if (!target.isEmpty() && !targetAlreadySet)
{
result+=" target=\""+target+"\"";
}
QCString leftPart = buf.left(indexS);
QCString rightPart = buf.mid(indexE+1);
//printf("replaceRef(\n'%s'\n)->\n'%s+%s+%s'\n",
// qPrint(buf),qPrint(leftPart),qPrint(result),qPrint(rightPart));
return leftPart + result + rightPart;
}
else
{
return buf;
}
}
/*! converts the rectangles in a client site image map into a stream
* \param t the stream to which the result is written.
* \param mapName the name of the map file.
* \param relPath the relative path to the root of the output directory
* (used in case CREATE_SUBDIRS is enabled).
* \param urlOnly if FALSE the url field in the map contains an external
* references followed by a $ and then the URL.
* \param context the context (file, class, or namespace) in which the
* map file was found
* \returns TRUE if successful.
*/
bool DotFilePatcher::convertMapFile(TextStream &t,const QCString &mapName,
const QCString &relPath, bool urlOnly,
const QCString &context)
{
std::ifstream f = Portable::openInputStream(mapName);
if (!f.is_open())
{
err("problems opening map file %s for inclusion in the docs!\n"
"If you installed Graphviz/dot after a previous failing run, \n"
"try deleting the output directory and rerun doxygen.\n",qPrint(mapName));
return FALSE;
}
std::string line;
while (getline(f,line)) // foreach line
{
QCString buf = line+'\n';
if (buf.startsWith("<area"))
{
QCString replBuf = replaceRef(buf,relPath,urlOnly,context);
// in dot version 7.0.2 the alt attribute is, incorrectly, removed.
// see https://gitlab.com/graphviz/graphviz/-/issues/265
int indexA = replBuf.find("alt=");
if (indexA == -1)
{
replBuf = replBuf.left(5) + " alt=\"\"" + replBuf.right(replBuf.length() - 5);
}
// strip id="..." from replBuf since the id's are not needed and not unique.
int indexS = replBuf.find("id=\""), indexE = 0;
if (indexS>0 && (indexE=replBuf.find('"',indexS+4))!=-1)
{
t << replBuf.left(indexS-1) << replBuf.right(replBuf.length() - indexE - 1);
}
else
{
t << replBuf;
}
}
}
return TRUE;
}
DotFilePatcher::DotFilePatcher(const QCString &patchFile)
: m_patchFile(patchFile)
{
}
bool DotFilePatcher::isSVGFile() const
{
return m_patchFile.endsWith(".svg");
}
int DotFilePatcher::addMap(const QCString &mapFile,const QCString &relPath,
bool urlOnly,const QCString &context,const QCString &label)
{
size_t id = m_maps.size();
m_maps.emplace_back(mapFile,relPath,urlOnly,context,label);
return static_cast<int>(id);
}
int DotFilePatcher::addFigure(const QCString &baseName,
const QCString &figureName,bool heightCheck)
{
size_t id = m_maps.size();
m_maps.emplace_back(figureName,"",heightCheck,"",baseName);
return static_cast<int>(id);
}
int DotFilePatcher::addSVGConversion(const QCString &relPath,bool urlOnly,
const QCString &context,bool zoomable,
int graphId)
{
size_t id = m_maps.size();
m_maps.emplace_back("",relPath,urlOnly,context,"",zoomable,graphId);
return static_cast<int>(id);
}
int DotFilePatcher::addSVGObject(const QCString &baseName,
const QCString &absImgName,
const QCString &relPath)
{
size_t id = m_maps.size();
m_maps.emplace_back(absImgName,relPath,false,"",baseName);
return static_cast<int>(id);
}
bool DotFilePatcher::run() const
{
//printf("DotFilePatcher::run(): %s\n",qPrint(m_patchFile));
bool interactiveSVG = Config_getBool(INTERACTIVE_SVG);
bool isSVGFile = m_patchFile.endsWith(".svg");
int graphId = -1;
QCString relPath;
if (isSVGFile)
{
const Map &map = m_maps.front(); // there is only one 'map' for a SVG file
interactiveSVG = interactiveSVG && map.zoomable;
graphId = map.graphId;
relPath = map.relPath;
//printf("DotFilePatcher::addSVGConversion: file=%s zoomable=%d\n",
// qPrint(m_patchFile),map->zoomable);
}
QCString tmpName = m_patchFile+".tmp";
Dir thisDir;
if (!thisDir.rename(m_patchFile.str(),tmpName.str()))
{
err("Failed to rename file %s to %s!\n",qPrint(m_patchFile),qPrint(tmpName));
return FALSE;
}
std::ifstream fi = Portable::openInputStream(tmpName);
std::ofstream fo = Portable::openOutputStream(m_patchFile);
if (!fi.is_open())
{
err("problem opening file %s for patching!\n",qPrint(tmpName));
thisDir.rename(tmpName.str(),m_patchFile.str());
return FALSE;
}
if (!fo.is_open())
{
err("problem opening file %s for patching!\n",qPrint(m_patchFile));
thisDir.rename(tmpName.str(),m_patchFile.str());
return FALSE;
}
TextStream t(&fo);
int width=0,height=0;
bool insideHeader=FALSE;
bool replacedHeader=FALSE;
bool useNagivation=FALSE;
std::string lineStr;
static const reg::Ex reSVG(R"([\[<]!-- SVG [0-9]+)");
static const reg::Ex reMAP(R"(<!-- MAP [0-9]+)");
static const reg::Ex reFIG(R"(% FIG [0-9]+)");
while (getline(fi,lineStr))
{
QCString line = lineStr+'\n';
//printf("line=[%s]\n",qPrint(line.stripWhiteSpace()));
int i = 0;
if (isSVGFile)
{
if (interactiveSVG)
{
if (line.find("<svg")!=-1 && !replacedHeader)
{
int count = sscanf(line.data(),"<svg width=\"%dpt\" height=\"%dpt\"",&width,&height);
//printf("width=%d height=%d\n",width,height);
useNagivation = count==2 && (width>500 || height>450);
insideHeader = count==2;
}
else if (insideHeader && !replacedHeader && line.find("<g id=\"graph")!=-1)
{
if (useNagivation)
{
// insert special replacement header for interactive SVGs
t << "<!--zoomable " << height << " -->\n";
t << svgZoomHeader0;
}
else
{
t << svgZoomHeader0_noinit;
}
t << svgZoomHeader1;
if (useNagivation)
{
t << svgZoomHeader2;
}
if (useNagivation)
{
t << "<script type=\"application/ecmascript\">\n";
t << "var viewWidth = " << width << ";\n";
t << "var viewHeight = " << height << ";\n";
if (graphId>=0)
{
t << "var sectionId = 'dynsection-" << graphId << "';\n";
}
t << "</script>\n";
}
t << "<script type=\"application/ecmascript\" xlink:href=\"" << relPath << "svg.min.js\"/>\n";
t << "<svg id=\"graph\" class=\"graph\">\n";
if (useNagivation)
{
t << "<g id=\"viewport\">\n";
}
else
{
t << line;
}
line="";
insideHeader=FALSE;
replacedHeader=TRUE;
}
}
if (!insideHeader || !useNagivation) // copy SVG and replace refs,
// unless we are inside the header of the SVG.
// Then we replace it with another header.
{
const Map &map = m_maps.front(); // there is only one 'map' for a SVG file
t << replaceRef(line,map.relPath,map.urlOnly,map.context,"_top");
}
}
else if (line.find("SVG")!=-1 && (i=findIndex(line.str(),reSVG))!=-1)
{
//printf("Found marker at %d\n",i);
int mapId=-1;
t << line.left(i);
int n = sscanf(line.data()+i+1,"!-- SVG %d",&mapId);
if (n==1 && mapId>=0 && mapId<static_cast<int>(m_maps.size()))
{
int e = std::max(line.find("--]"),line.find("-->"));
const Map &map = m_maps.at(mapId);
//printf("DotFilePatcher::writeSVGFigure: file=%s zoomable=%d\n",
// qPrint(m_patchFile),map.zoomable);
if (!writeSVGFigureLink(t,map.relPath,map.label,map.mapFile))
{
err("Problem extracting size from SVG file %s\n",qPrint(map.mapFile));
}
if (e!=-1) t << line.mid(e+3);
}
else // error invalid map id!
{
err("Found invalid SVG id in file %s!\n",qPrint(m_patchFile));
t << line.mid(i);
}
}
else if (line.find("MAP")!=-1 && (i=findIndex(line.str(),reMAP))!=-1)
{
int mapId=-1;
t << line.left(i);
int n = sscanf(line.data()+i,"<!-- MAP %d",&mapId);
if (n==1 && mapId>=0 && mapId<static_cast<int>(m_maps.size()))
{
TextStream tt;
const Map &map = m_maps.at(mapId);
//printf("patching MAP %d in file %s with contents of %s\n",
// mapId,qPrint(m_patchFile),qPrint(map.mapFile));
convertMapFile(tt,map.mapFile,map.relPath,map.urlOnly,map.context);
if (!tt.empty())
{
t << "<map name=\"" << correctId(map.label) << "\" id=\"" << correctId(map.label) << "\">\n";
t << tt.str();
t << "</map>\n";
}
}
else // error invalid map id!
{
err("Found invalid MAP id in file %s!\n",qPrint(m_patchFile));
t << line.mid(i);
}
}
else if (line.find("FIG")!=-1 && (i=findIndex(line.str(),reFIG))!=-1)
{
int mapId=-1;
int n = sscanf(line.data()+i+2,"FIG %d",&mapId);
//printf("line='%s' n=%d\n",qPrint(line)+i,n);
if (n==1 && mapId>=0 && mapId<static_cast<int>(m_maps.size()))
{
const Map &map = m_maps.at(mapId);
//printf("patching FIG %d in file %s with contents of %s\n",
// mapId,qPrint(m_patchFile),qPrint(map.mapFile));
if (!writeVecGfxFigure(t,map.label,map.mapFile))
{
err("problem writing FIG %d figure!\n",mapId);
return FALSE;
}
}
else // error invalid map id!
{
err("Found invalid bounding FIG %d in file %s!\n",mapId,qPrint(m_patchFile));
t << line;
}
}
else
{
t << line;
}
}
if (isSVGFile && interactiveSVG && !useNagivation) t << "</svg>\n";
fi.close();
if (isSVGFile && interactiveSVG && replacedHeader)
{
QCString orgName=m_patchFile.left(m_patchFile.length()-4)+"_org.svg";
if (useNagivation)
{
t << substitute(svgZoomFooter1,"$orgname",stripPath(orgName));
}
t << svgZoomFooter2;
t.flush();
fo.close();
// keep original SVG file so we can refer to it, we do need to replace
// dummy link by real ones
fi = Portable::openInputStream(tmpName);
fo = Portable::openOutputStream(orgName);
if (!fi.is_open())
{
err("problem opening file %s for reading!\n",qPrint(tmpName));
return FALSE;
}
if (!fo.is_open())
{
err("problem opening file %s for writing!\n",qPrint(orgName));
return FALSE;
}
t.setStream(&fo);
while (getline(fi,lineStr)) // foreach line
{
std::string line = lineStr+'\n';
const Map &map = m_maps.front(); // there is only one 'map' for a SVG file
t << replaceRef(line.c_str(),map.relPath,map.urlOnly,map.context,"_top");
}
t.flush();
fi.close();
fo.close();
}
// remove temporary file
thisDir.remove(tmpName.str());
return TRUE;
}
//---------------------------------------------------------------------------------------------
// extract size from a dot generated SVG file
static bool readSVGSize(const QCString &fileName,int *width,int *height)
{
bool found=FALSE;
std::ifstream f = Portable::openInputStream(fileName);
if (!f.is_open())
{
return false;
}
std::string line;
while (getline(f,line) && !found)
{
if (qstrncmp(line.c_str(),"<!--zoomable ",13)==0)
{
*width=-1;
*height=-1;
sscanf(line.c_str(),"<!--zoomable %d",height);
found=true;
}
else if (sscanf(line.c_str(),"<svg width=\"%dpt\" height=\"%dpt\"",width,height)==2)
{
found=true;
}
}
return true;
}
static void writeSVGNotSupported(TextStream &out)
{
out << "<p><b>This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.</b></p>";
}
/// Check if a reference to a SVG figure can be written and do so if possible.
/// Returns FALSE if not possible (for instance because the SVG file is not yet generated).
bool DotFilePatcher::writeSVGFigureLink(TextStream &out,const QCString &relPath,
const QCString &baseName,const QCString &absImgName)
{
int width=600,height=600;
if (!readSVGSize(absImgName,&width,&height))
{
return FALSE;
}
if (width==-1)
{
if (height<=60) height=300; else height+=300; // add some extra space for zooming
if (height>600) height=600; // clip to maximum height of 600 pixels
out << "<div class=\"zoom\">";
//out << "<object type=\"image/svg+xml\" data=\""
//out << "<embed type=\"image/svg+xml\" src=\""
out << "<iframe scrolling=\"no\" frameborder=\"0\" src=\""
<< relPath << baseName << ".svg\" width=\"100%\" height=\"" << height << "\">";
}
else
{
//out << "<object type=\"image/svg+xml\" data=\""
//out << "<embed type=\"image/svg+xml\" src=\""
out << "<iframe scrolling=\"no\" frameborder=\"0\" src=\""
<< relPath << baseName << ".svg\" width=\""
<< ((width*96+48)/72) << "\" height=\""
<< ((height*96+48)/72) << "\">";
}
writeSVGNotSupported(out);
//out << "</object>";
//out << "</embed>";
out << "</iframe>";
if (width==-1)
{
out << "</div>";
}
return TRUE;
}
bool DotFilePatcher::writeVecGfxFigure(TextStream &out,const QCString &baseName,
const QCString &figureName)
{
int width=400,height=550;
if (Config_getBool(USE_PDFLATEX))
{
if (!DotRunner::readBoundingBox(figureName+".pdf",&width,&height,FALSE))
{
//printf("writeVecGfxFigure()=0\n");
return FALSE;
}
}
else
{
if (!DotRunner::readBoundingBox(figureName+".eps",&width,&height,TRUE))
{
//printf("writeVecGfxFigure()=0\n");
return FALSE;
}
}
//printf("Got PDF/EPS size %d,%d\n",width,height);
int maxWidth = 350; /* approx. page width in points, excl. margins */
int maxHeight = 550; /* approx. page height in points, excl. margins */
out << "\\nopagebreak\n"
"\\begin{figure}[H]\n"
"\\begin{center}\n"
"\\leavevmode\n";
if (width>maxWidth || height>maxHeight) // figure too big for page
{
// c*width/maxWidth > c*height/maxHeight, where c=maxWidth*maxHeight>0
if (width*maxHeight>height*maxWidth)
{
out << "\\includegraphics[width=" << maxWidth << "pt]";
}
else
{
out << "\\includegraphics[height=" << maxHeight << "pt]";
}
}
else
{
out << "\\includegraphics[width=" << width << "pt]";
}
out << "{" << baseName << "}\n"
"\\end{center}\n"
"\\end{figure}\n";
//printf("writeVecGfxFigure()=1\n");
return TRUE;
}
| 22,668
|
C++
|
.cpp
| 636
| 30.039308
| 308
| 0.596419
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,403
|
membergroup.cpp
|
doxygen_doxygen/src/membergroup.cpp
|
/******************************************************************************
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include "membergroup.h"
#include "memberlist.h"
#include "outputlist.h"
#include "util.h"
#include "classdef.h"
#include "namespacedef.h"
#include "filedef.h"
#include "language.h"
#include "groupdef.h"
#include "doxygen.h"
#include "docparser.h"
#include "entry.h"
#include "md5.h"
MemberGroup::MemberGroup(const Definition *container,int id,const QCString &hdr,
const QCString &d,const QCString &docFile,int docLine,
MemberListContainer con)
: m_container(container),
memberList(std::make_unique<MemberList>(MemberListType::MemberGroup(),con)),
grpId(id), grpHeader(hdr), doc(d), m_docFile(docFile), m_docLine(docLine)
{
//printf("New member group id=%d header=%s desc=%s\n",id,hdr,d);
memberList->setNeedsSorting(Config_getBool(SORT_BRIEF_DOCS)); // detailed sections are already sorted elsewhere.
//printf("Member group docs='%s'\n",qPrint(doc));
}
void MemberGroup::insertMember(MemberDef *md)
{
//printf("MemberGroup::insertMember(%s) inSameSection=%d md->getSectionList()=%s\n",qPrint(md->name()),
// inSameSection,qPrint(md->getSectionList(m_container)->listType().to_string()));
MemberDef *firstMd = memberList->empty() ? nullptr : memberList->front();
if (inSameSection && firstMd &&
firstMd->getSectionList(m_container)!=md->getSectionList(m_container))
{
//printf("inSameSection=FALSE\n");
inSameSection=FALSE;
}
else if (inDeclSection==nullptr)
{
inDeclSection = const_cast<MemberList*>(md->getSectionList(m_container));
//printf("inDeclSection=%p type=%d\n",inDeclSection,inDeclSection->listType());
}
memberList->push_back(md);
// copy the group of the first member in the memberGroup
GroupDef *gd = nullptr;
if (firstMd && !firstMd->isAlias() && (gd=firstMd->getGroupDef()))
{
MemberDefMutable *mdm = toMemberDefMutable(md);
if (mdm)
{
mdm->setGroupDef(gd, firstMd->getGroupPri(),
firstMd->getGroupFileName(),
firstMd->getGroupStartLine(),
firstMd->getGroupHasDocs());
}
gd->insertMember(md);
}
}
void MemberGroup::setAnchors()
{
memberList->setAnchors();
}
void MemberGroup::writeDeclarations(OutputList &ol,
const ClassDef *cd,const NamespaceDef *nd,const FileDef *fd,const GroupDef *gd,const ModuleDef *mod,
bool showInline) const
{
//printf("MemberGroup::writeDeclarations() %s\n",qPrint(grpHeader));
QCString ldoc = doc;
memberList->writeDeclarations(ol,cd,nd,fd,gd,mod,grpHeader,ldoc,FALSE,showInline);
}
void MemberGroup::writePlainDeclarations(OutputList &ol,bool inGroup,
const ClassDef *cd,const NamespaceDef *nd,const FileDef *fd,const GroupDef *gd,const ModuleDef *mod,
int indentLevel,const ClassDef *inheritedFrom,const QCString &inheritId
) const
{
//printf("MemberGroup::writePlainDeclarations() memberList->count()=%d\n",memberList->count());
memberList->writePlainDeclarations(ol,inGroup,cd,nd,fd,gd,mod,indentLevel,inheritedFrom,inheritId);
}
void MemberGroup::writeDocumentation(OutputList &ol,const QCString &scopeName,
const Definition *container,bool showEnumValues,bool showInline) const
{
//printf("MemberGroup::writeDocumentation() %s\n",qPrint(grpHeader));
memberList->writeDocumentation(ol,scopeName,container,QCString(),showEnumValues,showInline);
}
void MemberGroup::writeDocumentationPage(OutputList &ol,const QCString &scopeName,
const DefinitionMutable *container) const
{
memberList->writeDocumentationPage(ol,scopeName,container);
}
void MemberGroup::setAnonymousEnumType()
{
memberList->setAnonymousEnumType();
}
void MemberGroup::addGroupedInheritedMembers(OutputList &ol,const ClassDef *cd,
MemberListType lt,
const ClassDef *inheritedFrom,const QCString &inheritId) const
{
//printf("** addGroupedInheritedMembers()\n");
for (const auto &md : *memberList)
{
//printf("matching %d == %d\n",lt,md->getSectionList()->listType());
const MemberList *ml = md->getSectionList(m_container);
if (ml && lt==ml->listType())
{
MemberList mml(lt,MemberListContainer::Class);
mml.push_back(md);
mml.countDecMembers();
mml.writePlainDeclarations(ol,false,cd,nullptr,nullptr,nullptr,nullptr,0,inheritedFrom,inheritId);
}
}
}
int MemberGroup::countGroupedInheritedMembers(MemberListType lt)
{
//printf("** countGroupedInheritedMembers()\n");
int count=0;
for (const auto &md : *memberList)
{
//printf("matching %d == %d\n",lt,md->getSectionList()->listType());
const MemberList *ml = md->getSectionList(m_container);
if (ml && lt==ml->listType())
{
count++;
}
}
return count;
}
/*! Add this group as a subsection of the declaration section, instead
* of rendering it in its own section
*/
void MemberGroup::addToDeclarationSection()
{
if (inDeclSection)
{
//printf("Adding group %p to list %p (type=%d) memberList=%p\n",this,
// inDeclSection,inDeclSection->listType(),memberList);
inDeclSection->addMemberGroup(this);
}
}
void MemberGroup::countDecMembers()
{
memberList->countDecMembers();
}
void MemberGroup::countDocMembers()
{
memberList->countDocMembers();
}
const Definition *MemberGroup::container() const
{
return m_container;
}
const Definition *MemberGroup::memberContainer() const
{
// return the container for the first member.
// Note this can be different from container() in case
// the member is rendered as part of a file but the members
// are actually of a namespace.
const Definition *ctx = nullptr;
if (memberList && !memberList->empty())
{
const MemberDef *md = memberList->front();
ctx = md->getClassDef();
if (ctx==nullptr) ctx = md->getNamespaceDef();
if (ctx==nullptr) ctx = md->getFileDef();
}
return ctx==nullptr ? m_container : ctx;
}
int MemberGroup::countInheritableMembers(const ClassDef *inheritedFrom) const
{
return memberList->countInheritableMembers(inheritedFrom);
}
void MemberGroup::distributeMemberGroupDocumentation()
{
//printf("MemberGroup::distributeMemberGroupDocumentation() %s\n",qPrint(grpHeader));
const MemberDef *md = nullptr;
for (const auto &smd : *memberList)
{
//printf("checking md=%s\n",qPrint(md->name()));
// find the first member of the group with documentation
if (!smd->documentation().isEmpty() ||
!smd->briefDescription().isEmpty() ||
!smd->inbodyDocumentation().isEmpty()
)
{
//printf("found it!\n");
md = smd;
break;
}
}
if (md) // distribute docs of md to other members of the list
{
//printf("Member %s has documentation!\n",qPrint(md->name()));
for (const auto &iomd : *memberList)
{
MemberDefMutable *omd = toMemberDefMutable(iomd);
if (omd && md!=omd && omd->documentation().isEmpty() &&
omd->briefDescription().isEmpty() &&
omd->inbodyDocumentation().isEmpty()
)
{
//printf("Copying documentation to member %s\n",qPrint(omd->name()));
omd->setBriefDescription(md->briefDescription(),md->briefFile(),md->briefLine());
omd->setDocumentation(md->documentation(),md->docFile(),md->docLine());
omd->setInbodyDocumentation(md->inbodyDocumentation(),md->inbodyFile(),md->inbodyLine());
}
}
}
}
int MemberGroup::numDecMembers() const
{
return memberList->numDecMembers();
}
int MemberGroup::numDecEnumValues() const
{
return memberList->numDecEnumValues();
}
int MemberGroup::numDocMembers() const
{
return memberList->numDocMembers();
}
int MemberGroup::numDocEnumValues() const
{
return memberList->numDocEnumValues();
}
void MemberGroup::addListReferences(Definition *def)
{
memberList->addListReferences(def);
}
void MemberGroup::findSectionsInDocumentation(const Definition *d)
{
docFindSections(doc,d,m_docFile);
memberList->findSectionsInDocumentation(d);
}
void MemberGroup::setRefItems(const RefItemVector &sli)
{
m_xrefListItems.insert(m_xrefListItems.end(), sli.cbegin(), sli.cend());
}
void MemberGroup::writeTagFile(TextStream &tagFile,bool qualifiedName)
{
memberList->writeTagFile(tagFile,qualifiedName);
}
//--------------------------------------------------------------------------
void MemberGroupInfo::setRefItems(const RefItemVector &sli)
{
m_sli.insert(m_sli.end(), sli.cbegin(), sli.cend());
}
| 9,211
|
C++
|
.cpp
| 259
| 31.467181
| 115
| 0.694887
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,404
|
docgroup.cpp
|
doxygen_doxygen/src/docgroup.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include <atomic>
#include "doxygen.h"
#include "util.h"
#include "entry.h"
#include "message.h"
#include "docgroup.h"
static std::atomic_int g_groupId;
static std::mutex g_memberGroupInfoMapMutex;
void DocGroup::enterFile(const QCString &fileName,int)
{
m_openCount = 0;
m_autoGroupStack.clear();
m_memberGroupId = DOX_NOGROUP;
m_memberGroupDocs.clear();
m_memberGroupRelates.clear();
m_compoundName=fileName;
}
void DocGroup::leaveFile(const QCString &fileName,int line)
{
//if (m_memberGroupId!=DOX_NOGROUP)
//{
// warn(fileName,line,"end of file while inside a member group");
//}
m_memberGroupId=DOX_NOGROUP;
m_memberGroupRelates.clear();
m_memberGroupDocs.clear();
if (!m_autoGroupStack.empty())
{
warn(fileName,line,"end of file while inside a group");
}
else if (m_openCount > 0) // < 0 is already handled on close call
{
warn(fileName,line,"end of file with unbalanced grouping commands");
}
}
void DocGroup::enterCompound(const QCString &fileName,int line,const QCString &name)
{
if (m_memberGroupId!=DOX_NOGROUP)
{
warn(fileName,line,"try to put compound %s inside a member group",qPrint(name));
}
m_memberGroupId=DOX_NOGROUP;
m_memberGroupRelates.clear();
m_memberGroupDocs.clear();
m_compoundName = name;
int i = m_compoundName.find('(');
if (i!=-1)
{
m_compoundName=m_compoundName.left(i); // strip category (Obj-C)
}
if (m_compoundName.isEmpty())
{
m_compoundName=fileName;
}
//printf("groupEnterCompound(%s)\n",qPrint(name));
}
void DocGroup::leaveCompound(const QCString &,int,const QCString &/* name */)
{
//printf("groupLeaveCompound(%s)\n",qPrint(name));
//if (m_memberGroupId!=DOX_NOGROUP)
//{
// warn(fileName,line,"end of compound %s while inside a member group\n",qPrint(name));
//}
m_memberGroupId=DOX_NOGROUP;
m_memberGroupRelates.clear();
m_memberGroupDocs.clear();
m_compoundName.clear();
}
int DocGroup::findExistingGroup(const MemberGroupInfo *info)
{
std::lock_guard<std::mutex> lock(g_memberGroupInfoMapMutex);
//printf("findExistingGroup %s:%s\n",qPrint(info->header),qPrint(info->compoundName));
for (const auto &[groupId,groupInfo] : Doxygen::memberGroupInfoMap)
{
if (m_compoundName==groupInfo->compoundName && // same file or scope
!groupInfo->header.isEmpty() && // not a nameless group
qstricmp(groupInfo->header,info->header)==0 // same header name
)
{
//printf("Found it!\n");
return groupId; // put the item in this group
}
}
return ++g_groupId; // start new group
}
void DocGroup::open(Entry *e,const QCString &,int, bool implicit)
{
if (!implicit) m_openCount++;
//printf("==> openGroup(name=%s,sec=%x) m_autoGroupStack=%zu\n",
// qPrint(e->name),e->section,m_autoGroupStack.size());
if (e->section.isGroupDoc()) // auto group
{
m_autoGroupStack.emplace_back(e->name,e->groupingPri());
}
else // start of a member group
{
//printf(" membergroup id=%d %s\n",m_memberGroupId,qPrint(m_memberGroupHeader));
if (m_memberGroupId==DOX_NOGROUP) // no group started yet
{
auto info = std::make_unique<MemberGroupInfo>();
info->header = m_memberGroupHeader.stripWhiteSpace();
info->compoundName = m_compoundName;
m_memberGroupId = findExistingGroup(info.get());
{
std::lock_guard<std::mutex> lock(g_memberGroupInfoMapMutex);
auto it = Doxygen::memberGroupInfoMap.find(m_memberGroupId);
if (it==Doxygen::memberGroupInfoMap.end())
{
//printf(" use membergroup %d\n",m_memberGroupId);
Doxygen::memberGroupInfoMap.emplace(m_memberGroupId,std::move(info));
}
}
m_memberGroupRelates = e->relates;
e->mGrpId = m_memberGroupId;
}
}
}
void DocGroup::close(Entry *e,const QCString &fileName,int line,bool foundInline,bool implicit)
{
if (!implicit)
{
if (m_openCount < 1)
{
warn(fileName,line,"unbalanced grouping commands");
}
else
{
m_openCount--;
}
}
//printf("==> closeGroup(name=%s,sec=%x,file=%s,line=%d) m_autoGroupStack=%zu\n",
// qPrint(e->name),e->section,qPrint(fileName),line,m_autoGroupStack.size());
if (m_memberGroupId!=DOX_NOGROUP) // end of member group
{
{
std::lock_guard<std::mutex> lock(g_memberGroupInfoMapMutex);
auto it = Doxygen::memberGroupInfoMap.find(m_memberGroupId);
if (it!=Doxygen::memberGroupInfoMap.end()) // known group
{
auto &info = it->second;
info->doc = m_memberGroupDocs;
//info->docFile = fileName;
//info->docLine = line;
}
}
m_memberGroupId=DOX_NOGROUP;
m_memberGroupRelates.clear();
m_memberGroupDocs.clear();
if (!foundInline)
{
e->mGrpId=DOX_NOGROUP;
e->relates="";
}
//printf("new group id=%d\n",m_memberGroupId);
}
else if (!m_autoGroupStack.empty()) // end of auto group
{
Grouping grp = m_autoGroupStack.back();
m_autoGroupStack.pop_back();
// see bug577005: we should not remove the last group for e
if (!foundInline && !e->groups.empty()) e->groups.pop_back();
//printf("Removing %s e=%p\n",qPrint(grp->groupname),e);
if (!foundInline) initGroupInfo(e);
}
}
void DocGroup::initGroupInfo(Entry *e)
{
//printf("==> initGroup(id=%d,related=%s,e=%p,#stack=%zu)\n",m_memberGroupId,
// qPrint(m_memberGroupRelates),(void*)e,m_autoGroupStack.size());
e->mGrpId = m_memberGroupId;
e->relates = m_memberGroupRelates;
if (!m_autoGroupStack.empty())
{
//printf("Appending group %s to %s: count=%zu entry=%p\n",
// qPrint(m_autoGroupStack.back().groupname),
// qPrint(e->name),e->groups.size(),(void*)e);
e->groups.emplace_back(m_autoGroupStack.back());
}
}
void DocGroup::addDocs(Entry *e)
{
if (e->section.isMemberGrp())
{
m_memberGroupDocs=e->brief.stripWhiteSpace();
e->doc = stripLeadingAndTrailingEmptyLines(e->doc,e->docLine);
if (!m_memberGroupDocs.isEmpty() && !e->doc.isEmpty())
{
m_memberGroupDocs+="\n\n";
}
m_memberGroupDocs+=e->doc;
{
std::lock_guard<std::mutex> lock(g_memberGroupInfoMapMutex);
auto it =Doxygen::memberGroupInfoMap.find(m_memberGroupId);
if (it!=Doxygen::memberGroupInfoMap.end())
{
auto &info = it->second;
info->doc = m_memberGroupDocs;
info->docFile = e->docFile;
info->docLine = e->docLine;
info->setRefItems(e->sli);
}
}
e->doc.clear();
e->brief.clear();
}
}
bool DocGroup::isEmpty() const
{
return (m_memberGroupId==DOX_NOGROUP);
}
void DocGroup::clearHeader()
{
m_memberGroupHeader.clear();
}
void DocGroup::appendHeader(const char text)
{
m_memberGroupHeader += text;
}
| 7,435
|
C++
|
.cpp
| 232
| 28.142241
| 95
| 0.669217
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,405
|
docparser.cpp
|
doxygen_doxygen/src/docparser.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2022 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.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <cassert>
#include <ctype.h>
#include "classlist.h"
#include "cmdmapper.h"
#include "config.h"
#include "debug.h"
#include "dir.h"
#include "docparser.h"
#include "docparser_p.h"
#include "doxygen.h"
#include "filedef.h"
#include "fileinfo.h"
#include "groupdef.h"
#include "namespacedef.h"
#include "message.h"
#include "pagedef.h"
#include "portable.h"
#include "printdocvisitor.h"
#include "util.h"
#include "indexlist.h"
#include "trace.h"
#if !ENABLE_DOCPARSER_TRACING
#undef AUTO_TRACE
#undef AUTO_TRACE_ADD
#undef AUTO_TRACE_EXIT
#define AUTO_TRACE(...) (void)0
#define AUTO_TRACE_ADD(...) (void)0
#define AUTO_TRACE_EXIT(...) (void)0
#endif
//---------------------------------------------------------------------------
IDocParserPtr createDocParser()
{
return std::make_unique<DocParser>();
}
void DocParser::pushContext()
{
//QCString indent;
//indent.fill(' ',contextStack.size()*2+2);
//printf("%sdocParserPushContext() count=%zu\n",qPrint(indent),context.nodeStack.size());
tokenizer.pushContext();
contextStack.emplace();
auto &ctx = contextStack.top();
ctx = context;
ctx.lineNo = tokenizer.getLineNr();
context.token = tokenizer.token();
}
void DocParser::popContext()
{
auto &ctx = contextStack.top();
context = ctx;
tokenizer.setLineNr(ctx.lineNo);
contextStack.pop();
tokenizer.popContext();
context.token = tokenizer.token();
//QCString indent;
//indent.fill(' ',contextStack.size()*2+2);
//printf("%sdocParserPopContext() count=%zu\n",qPrint(indent),context.nodeStack.size());
}
//---------------------------------------------------------------------------
/*! search for an image in the imageNameDict and if found
* copies the image to the output directory (which depends on the \a type
* parameter).
*/
QCString DocParser::findAndCopyImage(const QCString &fileName, DocImage::Type type, bool doWarn)
{
QCString result;
bool ambig = false;
FileDef *fd = findFileDef(Doxygen::imageNameLinkedMap,fileName,ambig);
//printf("Search for %s\n",fileName);
if (fd)
{
if (ambig & doWarn)
{
QCString text;
text.sprintf("image file name '%s' is ambiguous.\n",qPrint(fileName));
text+="Possible candidates:\n";
text+=showFileDefMatches(Doxygen::imageNameLinkedMap,fileName);
warn_doc_error(context.fileName,tokenizer.getLineNr(),"%s", qPrint(text));
}
QCString inputFile = fd->absFilePath();
FileInfo infi(inputFile.str());
if (infi.exists())
{
result = fileName;
int i = result.findRev('/');
if (i!=-1 || (i=result.findRev('\\'))!=-1)
{
result = result.right(static_cast<int>(result.length())-i-1);
}
//printf("fileName=%s result=%s\n",fileName,qPrint(result));
QCString outputDir;
switch(type)
{
case DocImage::Html:
if (!Config_getBool(GENERATE_HTML)) return result;
outputDir = Config_getString(HTML_OUTPUT);
break;
case DocImage::Latex:
if (!Config_getBool(GENERATE_LATEX)) return result;
outputDir = Config_getString(LATEX_OUTPUT);
break;
case DocImage::DocBook:
if (!Config_getBool(GENERATE_DOCBOOK)) return result;
outputDir = Config_getString(DOCBOOK_OUTPUT);
break;
case DocImage::Rtf:
if (!Config_getBool(GENERATE_RTF)) return result;
outputDir = Config_getString(RTF_OUTPUT);
break;
case DocImage::Xml:
if (!Config_getBool(GENERATE_XML)) return result;
outputDir = Config_getString(XML_OUTPUT);
break;
}
QCString outputFile = outputDir+"/"+result;
FileInfo outfi(outputFile.str());
if (outfi.isSymLink())
{
Dir().remove(outputFile.str());
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"destination of image %s is a symlink, replacing with image",
qPrint(outputFile));
}
if (outputFile!=inputFile) // prevent copying to ourself
{
if (copyFile(inputFile,outputFile) && type==DocImage::Html)
{
Doxygen::indexList->addImageFile(result);
}
}
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"could not open image %s",qPrint(fileName));
}
if (type==DocImage::Latex && Config_getBool(USE_PDFLATEX) &&
fd->name().endsWith(".eps")
)
{ // we have an .eps image in pdflatex mode => convert it to a pdf.
QCString outputDir = Config_getString(LATEX_OUTPUT);
QCString baseName = fd->name().left(fd->name().length()-4);
QCString epstopdfArgs(4096, QCString::ExplicitSize);
epstopdfArgs.sprintf("\"%s/%s.eps\" --outfile=\"%s/%s.pdf\"",
qPrint(outputDir), qPrint(baseName),
qPrint(outputDir), qPrint(baseName));
if (Portable::system("epstopdf",epstopdfArgs)!=0)
{
err("Problems running epstopdf. Check your TeX installation!\n");
}
else
{
Dir().remove(outputDir.str()+"/"+baseName.str()+".eps");
}
return baseName;
}
}
else
{
result=fileName;
if (!result.startsWith("http:") && !result.startsWith("https:") && doWarn)
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"image file %s is not found in IMAGE_PATH: "
"assuming external image.",qPrint(fileName)
);
}
}
return result;
}
/*! Collects the parameters found with \@param command
* in a list context.paramsFound. If
* the parameter is not an actual parameter of the current
* member context.memberDef, then a warning is raised (unless warnings
* are disabled altogether).
*/
void DocParser::checkArgumentName()
{
if (!(Config_getBool(WARN_IF_DOC_ERROR) || Config_getBool(WARN_IF_INCOMPLETE_DOC))) return;
if (context.memberDef==nullptr) return; // not a member
std::string name = context.token->name.str();
const ArgumentList &al=context.memberDef->isDocsForDefinition() ?
context.memberDef->argumentList() :
context.memberDef->declArgumentList();
SrcLangExt lang = context.memberDef->getLanguage();
//printf("isDocsForDefinition()=%d\n",context.memberDef->isDocsForDefinition());
if (al.empty()) return; // no argument list
static const reg::Ex re(R"(\$?\w+\.*)");
reg::Iterator it(name,re);
reg::Iterator end;
for (; it!=end ; ++it)
{
const auto &match = *it;
QCString aName=match.str();
if (lang==SrcLangExt::Fortran) aName=aName.lower();
//printf("aName='%s'\n",qPrint(aName));
bool found=FALSE;
for (const Argument &a : al)
{
QCString argName = context.memberDef->isDefine() ? a.type : a.name;
if (lang==SrcLangExt::Fortran) argName=argName.lower();
argName=argName.stripWhiteSpace();
//printf("argName='%s' aName=%s\n",qPrint(argName),qPrint(aName));
if (argName.endsWith("...")) argName=argName.left(argName.length()-3);
if (aName==argName)
{
context.paramsFound.insert(aName.str());
found=TRUE;
break;
}
}
if (!found)
{
//printf("member type=%d\n",context.memberDef->memberType());
QCString scope=context.memberDef->getScopeString();
if (!scope.isEmpty()) scope+="::"; else scope="";
QCString inheritedFrom = "";
QCString docFile = context.memberDef->docFile();
int docLine = context.memberDef->docLine();
const MemberDef *inheritedMd = context.memberDef->inheritsDocsFrom();
if (inheritedMd) // documentation was inherited
{
inheritedFrom.sprintf(" inherited from member %s at line "
"%d in file %s",qPrint(inheritedMd->name()),
inheritedMd->docLine(),qPrint(inheritedMd->docFile()));
docFile = context.memberDef->getDefFileName();
docLine = context.memberDef->getDefLine();
}
QCString alStr = argListToString(al);
warn_doc_error(docFile,docLine,
"argument '%s' of command @param "
"is not found in the argument list of %s%s%s%s",
qPrint(aName), qPrint(scope), qPrint(context.memberDef->name()),
qPrint(alStr), qPrint(inheritedFrom));
}
}
}
/*! Collects the return values found with \@retval command
* in a global list g_parserContext.retvalsFound.
*/
void DocParser::checkRetvalName()
{
QCString name = context.token->name;
if (!Config_getBool(WARN_IF_DOC_ERROR)) return;
if (context.memberDef==nullptr || name.isEmpty()) return; // not a member or no valid name
if (context.retvalsFound.count(name.str())==1) // only report the first double entry
{
warn_doc_error(context.memberDef->getDefFileName(),
context.memberDef->getDefLine(),
"%s",
qPrint("return value '" + name + "' of " +
QCString(context.memberDef->qualifiedName()) +
" has multiple documentation sections"));
}
context.retvalsFound.insert(name.str());
}
/*! Checks if the parameters that have been specified using \@param are
* indeed all parameters and that a parameter does not have multiple
* \@param blocks.
* Must be called after checkArgumentName() has been called for each
* argument.
*/
void DocParser::checkUnOrMultipleDocumentedParams()
{
if (context.memberDef && context.hasParamCommand)
{
const ArgumentList &al=context.memberDef->isDocsForDefinition() ?
context.memberDef->argumentList() :
context.memberDef->declArgumentList();
SrcLangExt lang = context.memberDef->getLanguage();
if (!al.empty())
{
ArgumentList undocParams;
for (const Argument &a: al)
{
QCString argName = context.memberDef->isDefine() ? a.type : a.name;
if (lang==SrcLangExt::Fortran) argName = argName.lower();
argName=argName.stripWhiteSpace();
QCString aName = argName;
if (argName.endsWith("...")) argName=argName.left(argName.length()-3);
if (lang==SrcLangExt::Python && (argName=="self" || argName=="cls"))
{
// allow undocumented self / cls parameter for Python
}
else if (lang==SrcLangExt::Cpp && (a.type=="this" || a.type.startsWith("this ")))
{
// allow undocumented this (for C++23 deducing this), see issue #11123
}
else if (!argName.isEmpty())
{
size_t count = context.paramsFound.count(argName.str());
if (count==0 && a.docs.isEmpty())
{
undocParams.push_back(a);
}
else if (count>1 && Config_getBool(WARN_IF_DOC_ERROR))
{
warn_doc_error(context.memberDef->docFile(),
context.memberDef->docLine(),
"%s",
qPrint("argument '" + aName +
"' from the argument list of " +
QCString(context.memberDef->qualifiedName()) +
" has multiple @param documentation sections"));
}
}
}
if (!undocParams.empty() && Config_getBool(WARN_IF_INCOMPLETE_DOC))
{
bool first=TRUE;
QCString errMsg = "The following parameter";
if (undocParams.size()>1) errMsg+="s";
errMsg+=" of "+
QCString(context.memberDef->qualifiedName()) +
QCString(argListToString(al)) +
(undocParams.size()>1 ? " are" : " is") + " not documented:\n";
for (const Argument &a : undocParams)
{
QCString argName = context.memberDef->isDefine() ? a.type : a.name;
if (lang==SrcLangExt::Fortran) argName = argName.lower();
argName=argName.stripWhiteSpace();
if (!first) errMsg+="\n";
first=FALSE;
errMsg+=" parameter '"+argName+"'";
}
warn_incomplete_doc(context.memberDef->docFile(),
context.memberDef->docLine(),
"%s",
qPrint(substitute(errMsg,"%","%%")));
}
}
else
{
if (context.paramsFound.empty() && Config_getBool(WARN_IF_DOC_ERROR))
{
warn_doc_error(context.memberDef->docFile(),
context.memberDef->docLine(),
"%s",
qPrint(context.memberDef->qualifiedName() +
" has @param documentation sections but no arguments"));
}
}
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
/*! Looks for a documentation block with name commandName in the current
* context (g_parserContext.context). The resulting documentation string is
* put in pDoc, the definition in which the documentation was found is
* put in pDef.
* @retval TRUE if name was found.
* @retval FALSE if name was not found.
*/
bool DocParser::findDocsForMemberOrCompound(const QCString &commandName,
QCString *pDoc,
QCString *pBrief,
const Definition **pDef)
{
AUTO_TRACE("commandName={}",commandName);
*pDoc="";
*pBrief="";
*pDef=nullptr;
QCString cmdArg=commandName;
if (cmdArg.isEmpty())
{
AUTO_TRACE_EXIT("empty");
return false;
}
const FileDef *fd=nullptr;
const GroupDef *gd=nullptr;
const PageDef *pd=nullptr;
gd = Doxygen::groupLinkedMap->find(cmdArg);
if (gd) // group
{
*pDoc=gd->documentation();
*pBrief=gd->briefDescription();
*pDef=gd;
AUTO_TRACE_EXIT("group");
return true;
}
pd = Doxygen::pageLinkedMap->find(cmdArg);
if (pd) // page
{
*pDoc=pd->documentation();
*pBrief=pd->briefDescription();
*pDef=pd;
AUTO_TRACE_EXIT("page");
return true;
}
bool ambig = false;
fd = findFileDef(Doxygen::inputNameLinkedMap,cmdArg,ambig);
if (fd && !ambig) // file
{
*pDoc=fd->documentation();
*pBrief=fd->briefDescription();
*pDef=fd;
AUTO_TRACE_EXIT("file");
return true;
}
// for symbols we need to normalize the separator, so A#B, or A\B, or A.B becomes A::B
cmdArg = substitute(cmdArg,"#","::");
cmdArg = substitute(cmdArg,"\\","::");
bool extractAnonNs = Config_getBool(EXTRACT_ANON_NSPACES);
if (extractAnonNs &&
cmdArg.startsWith("anonymous_namespace{")
)
{
size_t rightBracePos = cmdArg.find("}", static_cast<int>(qstrlen("anonymous_namespace{")));
QCString leftPart = cmdArg.left(rightBracePos + 1);
QCString rightPart = cmdArg.right(cmdArg.size() - rightBracePos - 1);
rightPart = substitute(rightPart, ".", "::");
cmdArg = leftPart + rightPart;
}
else
{
cmdArg = substitute(cmdArg,".","::");
}
int l=static_cast<int>(cmdArg.length());
int funcStart=cmdArg.find('(');
if (funcStart==-1)
{
funcStart=l;
}
else
{
// Check for the case of operator() and the like.
// beware of scenarios like operator()((foo)bar)
int secondParen = cmdArg.find('(', funcStart+1);
int leftParen = cmdArg.find(')', funcStart+1);
if (leftParen!=-1 && secondParen!=-1)
{
if (leftParen<secondParen)
{
funcStart=secondParen;
}
}
}
QCString name=removeRedundantWhiteSpace(cmdArg.left(funcStart));
QCString args=cmdArg.right(l-funcStart);
// try if the link is to a member
GetDefInput input(
context.context.find('.')==-1 ? context.context : QCString(), // find('.') is a hack to detect files
name,
args);
input.checkCV=true;
GetDefResult result = getDefs(input);
//printf("found=%d context=%s name=%s\n",result.found,qPrint(context.context),qPrint(name));
if (result.found && result.md)
{
*pDoc=result.md->documentation();
*pBrief=result.md->briefDescription();
*pDef=result.md;
AUTO_TRACE_EXIT("member");
return true;
}
int scopeOffset=static_cast<int>(context.context.length());
do // for each scope
{
QCString fullName=cmdArg;
if (scopeOffset>0)
{
fullName.prepend(context.context.left(scopeOffset)+"::");
}
//printf("Trying fullName='%s'\n",qPrint(fullName));
// try class, namespace, group, page, file reference
const ClassDef *cd = Doxygen::classLinkedMap->find(fullName);
if (cd) // class
{
*pDoc=cd->documentation();
*pBrief=cd->briefDescription();
*pDef=cd;
AUTO_TRACE_EXIT("class");
return true;
}
const NamespaceDef *nd = Doxygen::namespaceLinkedMap->find(fullName);
if (nd) // namespace
{
*pDoc=nd->documentation();
*pBrief=nd->briefDescription();
*pDef=nd;
AUTO_TRACE_EXIT("namespace");
return true;
}
if (scopeOffset==0)
{
scopeOffset=-1;
}
else
{
scopeOffset = context.context.findRev("::",scopeOffset-1);
if (scopeOffset==-1) scopeOffset=0;
}
} while (scopeOffset>=0);
AUTO_TRACE_EXIT("not found");
return FALSE;
}
//---------------------------------------------------------------------------
void DocParser::errorHandleDefaultToken(DocNodeVariant *parent,Token tok,
DocNodeList &children,const QCString &txt)
{
switch (tok.value())
{
case TokenRetval::TK_COMMAND_AT:
// fall through
case TokenRetval::TK_COMMAND_BS:
{
char cs[2] = { tok.command_to_char(), 0 };
children.append<DocWord>(this,parent,cs + context.token->name);
warn_doc_error(context.fileName,tokenizer.getLineNr(),"Illegal command '%c%s' found as part of a %s",
tok.command_to_char(),qPrint(context.token->name),qPrint(txt));
}
break;
case TokenRetval::TK_SYMBOL:
warn_doc_error(context.fileName,tokenizer.getLineNr(),"Unsupported symbol '%s' found as part of a %s",
qPrint(context.token->name), qPrint(txt));
break;
case TokenRetval::TK_HTMLTAG:
warn_doc_error(context.fileName,tokenizer.getLineNr(),"Unsupported HTML tag <%s%s> found as part of a %s",
context.token->endTag ? "/" : "",qPrint(context.token->name), qPrint(txt));
break;
default:
children.append<DocWord>(this,parent,context.token->name);
warn_doc_error(context.fileName,tokenizer.getLineNr(),"Unexpected token %s found as part of a %s",
tok.to_string(), qPrint(txt));
break;
}
}
//---------------------------------------------------------------------------
Token DocParser::handleStyleArgument(DocNodeVariant *parent,DocNodeList &children,const QCString &cmdName)
{
AUTO_TRACE("cmdName={}",cmdName);
QCString saveCmdName = cmdName;
Token tok=tokenizer.lex();
if (!tok.is(TokenRetval::TK_WHITESPACE))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"expected whitespace after \\%s command",
qPrint(saveCmdName));
return tok;
}
tok = tokenizer.lex();
while (!tok.is_any_of(TokenRetval::TK_NONE, TokenRetval::TK_EOF, TokenRetval::TK_WHITESPACE,
TokenRetval::TK_NEWPARA, TokenRetval::TK_LISTITEM, TokenRetval::TK_ENDLIST)
)
{
static const reg::Ex specialChar(R"([.,|()\[\]:;?])");
if (tok.is(TokenRetval::TK_WORD) && context.token->name.length()==1 &&
reg::match(context.token->name.str(),specialChar))
{
// special character that ends the markup command
return tok;
}
if (!defaultHandleToken(parent,tok,children))
{
switch (tok.value())
{
case TokenRetval::TK_HTMLTAG:
if (insideLI(parent) && Mappers::htmlTagMapper->map(context.token->name)!=HtmlTagType::UNKNOWN && context.token->endTag)
{ // ignore </li> as the end of a style command
continue;
}
AUTO_TRACE_EXIT("end tok={}",tok.to_string());
return tok;
break;
default:
errorHandleDefaultToken(parent,tok,children,"\\" + saveCmdName + " command");
break;
}
break;
}
tok = tokenizer.lex();
}
AUTO_TRACE_EXIT("end tok={}",tok.to_string());
return (tok.is_any_of(TokenRetval::TK_NEWPARA,TokenRetval::TK_LISTITEM,TokenRetval::TK_ENDLIST)) ? tok : Token::make_RetVal_OK();
}
/*! Called when a style change starts. For instance a \<b\> command is
* encountered.
*/
void DocParser::handleStyleEnter(DocNodeVariant *parent,DocNodeList &children,
DocStyleChange::Style s,const QCString &tagName,const HtmlAttribList *attribs)
{
AUTO_TRACE("tagName={}",tagName);
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),s,tagName,TRUE,attribs);
context.styleStack.push(&children.back());
}
/*! Called when a style change ends. For instance a \</b\> command is
* encountered.
*/
void DocParser::handleStyleLeave(DocNodeVariant *parent,DocNodeList &children,
DocStyleChange::Style s,const QCString &tagName)
{
AUTO_TRACE("tagName={}",tagName);
QCString tagNameLower = QCString(tagName).lower();
auto topStyleChange = [](const DocStyleChangeStack &stack) -> const DocStyleChange &
{
return std::get<DocStyleChange>(*stack.top());
};
if (context.styleStack.empty() || // no style change
topStyleChange(context.styleStack).style()!=s || // wrong style change
topStyleChange(context.styleStack).tagName()!=tagNameLower || // wrong style change
topStyleChange(context.styleStack).position()!=context.nodeStack.size() // wrong position
)
{
if (context.styleStack.empty())
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"found </%s> tag without matching <%s>",
qPrint(tagName),qPrint(tagName));
}
else if (topStyleChange(context.styleStack).tagName()!=tagNameLower)
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"found </%s> tag while expecting </%s>",
qPrint(tagName),qPrint(topStyleChange(context.styleStack).tagName()));
}
else if (topStyleChange(context.styleStack).style()!=s)
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"found </%s> tag while expecting </%s>",
qPrint(tagName),qPrint(topStyleChange(context.styleStack).tagName()));
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"found </%s> at different nesting level (%zu) than expected (%zu)",
qPrint(tagName),context.nodeStack.size(),topStyleChange(context.styleStack).position());
}
}
else // end the section
{
children.append<DocStyleChange>(
this,parent,context.nodeStack.size(),s,
topStyleChange(context.styleStack).tagName(),FALSE);
context.styleStack.pop();
}
}
/*! Called at the end of a paragraph to close all open style changes
* (e.g. a <b> without a </b>). The closed styles are pushed onto a stack
* and entered again at the start of a new paragraph.
*/
void DocParser::handlePendingStyleCommands(DocNodeVariant *parent,DocNodeList &children)
{
AUTO_TRACE();
if (!context.styleStack.empty())
{
const DocStyleChange *sc = &std::get<DocStyleChange>(*context.styleStack.top());
while (sc && sc->position()>=context.nodeStack.size())
{ // there are unclosed style modifiers in the paragraph
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),
sc->style(),sc->tagName(),FALSE);
context.initialStyleStack.push(context.styleStack.top());
context.styleStack.pop();
sc = !context.styleStack.empty() ? &std::get<DocStyleChange>(*context.styleStack.top()) : nullptr;
}
}
}
void DocParser::handleInitialStyleCommands(DocNodeVariant *parent,DocNodeList &children)
{
AUTO_TRACE();
while (!context.initialStyleStack.empty())
{
const DocStyleChange &sc = std::get<DocStyleChange>(*context.initialStyleStack.top());
handleStyleEnter(parent,children,sc.style(),sc.tagName(),&sc.attribs());
context.initialStyleStack.pop();
}
}
Token DocParser::handleAHref(DocNodeVariant *parent,DocNodeList &children,
const HtmlAttribList &tagHtmlAttribs)
{
AUTO_TRACE();
size_t index=0;
Token retval = Token::make_RetVal_OK();
for (const auto &opt : tagHtmlAttribs)
{
if (opt.name=="name" || opt.name=="id") // <a name=label> or <a id=label> tag
{
if (!opt.value.isEmpty())
{
children.append<DocAnchor>(this,parent,opt.value,TRUE);
break; // stop looking for other tag attribs
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"found <a> tag with name option but without value!");
}
}
else if (opt.name=="href") // <a href=url>..</a> tag
{
// copy attributes
HtmlAttribList attrList = tagHtmlAttribs;
// and remove the href attribute
attrList.erase(attrList.begin()+index);
QCString relPath;
if (opt.value.at(0) != '#') relPath = context.relPath;
children.append<DocHRef>(this, parent, attrList,
opt.value, relPath,
convertNameToFile(context.fileName, FALSE, TRUE));
context.insideHtmlLink=TRUE;
retval = children.get_last<DocHRef>()->parse();
context.insideHtmlLink=FALSE;
tokenizer.setStatePara();
break;
}
else // unsupported option for tag a
{
}
++index;
}
return retval;
}
void DocParser::handleUnclosedStyleCommands()
{
AUTO_TRACE();
if (!context.initialStyleStack.empty())
{
QCString tagName = std::get<DocStyleChange>(*context.initialStyleStack.top()).tagName();
context.initialStyleStack.pop();
handleUnclosedStyleCommands();
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"end of comment block while expecting "
"command </%s>",qPrint(tagName));
}
}
void DocParser::handleLinkedWord(DocNodeVariant *parent,DocNodeList &children,bool ignoreAutoLinkFlag)
{
// helper to check if word w starts with any of the words in AUTOLINK_IGNORE_WORDS
auto ignoreWord = [](const QCString &w) -> bool {
const auto &list = Config_getList(AUTOLINK_IGNORE_WORDS);
return std::find_if(list.begin(), list.end(),
[&w](const auto &ignore) { return w.startsWith(ignore); }
)!=list.end();
};
QCString name = linkToText(context.lang,context.token->name,TRUE);
AUTO_TRACE("word={}",name);
bool autolinkSupport = Config_getBool(AUTOLINK_SUPPORT);
if ((!autolinkSupport && !ignoreAutoLinkFlag) || ignoreWord(context.token->name)) // no autolinking -> add as normal word
{
children.append<DocWord>(this,parent,name);
return;
}
// ------- try to turn the word 'name' into a link
const Definition *compound=nullptr;
const MemberDef *member=nullptr;
size_t len = context.token->name.length();
ClassDef *cd=nullptr;
bool ambig = false;
FileDef *fd = findFileDef(Doxygen::inputNameLinkedMap,context.fileName,ambig);
//printf("handleLinkedWord(%s) context.context=%s\n",qPrint(context.token->name),qPrint(context.context));
if (!context.insideHtmlLink &&
(resolveRef(context.context,context.token->name,context.inSeeBlock,&compound,&member,TRUE,fd,TRUE)
|| (!context.context.isEmpty() && // also try with global scope
resolveRef(QCString(),context.token->name,context.inSeeBlock,&compound,&member,FALSE,nullptr,TRUE))
)
)
{
//printf("ADD %s = %p (linkable?=%d)\n",qPrint(context.token->name),(void*)member,member ? member->isLinkable() : FALSE);
if (member && member->isLinkable()) // member link
{
AUTO_TRACE_ADD("resolved reference as member link");
if (member->isObjCMethod())
{
bool localLink = context.memberDef ? member->getClassDef()==context.memberDef->getClassDef() : FALSE;
name = member->objCMethodName(localLink,context.inSeeBlock);
}
children.append<DocLinkedWord>(
this,parent,name,
member->getReference(),
member->getOutputFileBase(),
member->anchor(),
member->briefDescriptionAsTooltip());
}
else if (compound->isLinkable()) // compound link
{
AUTO_TRACE_ADD("resolved reference as compound link");
QCString anchor = compound->anchor();
if (compound->definitionType()==Definition::TypeFile)
{
name=context.token->name;
}
else if (compound->definitionType()==Definition::TypeGroup)
{
name=toGroupDef(compound)->groupTitle();
}
children.append<DocLinkedWord>(
this,parent,name,
compound->getReference(),
compound->getOutputFileBase(),
anchor,
compound->briefDescriptionAsTooltip());
}
else if (compound->definitionType()==Definition::TypeFile &&
(toFileDef(compound))->generateSourceFile()
) // undocumented file that has source code we can link to
{
AUTO_TRACE_ADD("resolved reference as source link");
children.append<DocLinkedWord>(
this,parent,context.token->name,
compound->getReference(),
compound->getSourceFileBase(),
"",
compound->briefDescriptionAsTooltip());
}
else // not linkable
{
AUTO_TRACE_ADD("resolved reference as unlinkable compound={} (linkable={}) member={} (linkable={})",
compound ? compound->name() : "<none>", compound ? (int)compound->isLinkable() : -1,
member ? member->name() : "<none>", member ? (int)member->isLinkable() : -1);
children.append<DocWord>(this,parent,name);
}
}
else if (!context.insideHtmlLink && len>1 && context.token->name.at(len-1)==':')
{
// special case, where matching Foo: fails to be an Obj-C reference,
// but Foo itself might be linkable.
context.token->name=context.token->name.left(len-1);
handleLinkedWord(parent,children,ignoreAutoLinkFlag);
children.append<DocWord>(this,parent,":");
}
else if (!context.insideHtmlLink && (cd=getClass(context.token->name+"-p")))
{
// special case 2, where the token name is not a class, but could
// be a Obj-C protocol
children.append<DocLinkedWord>(
this,parent,name,
cd->getReference(),
cd->getOutputFileBase(),
cd->anchor(),
cd->briefDescriptionAsTooltip());
}
else // normal non-linkable word
{
AUTO_TRACE_ADD("non-linkable");
if (context.token->name.startsWith("#"))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"explicit link request to '%s' could not be resolved",qPrint(name));
}
children.append<DocWord>(this,parent,context.token->name);
}
}
void DocParser::handleParameterType(DocNodeVariant *parent,DocNodeList &children,const QCString ¶mTypes)
{
QCString name = context.token->name; // save token name
AUTO_TRACE("name={}",name);
QCString name1;
int p=0, i=0, ii=0;
while ((i=paramTypes.find('|',p))!=-1)
{
name1 = paramTypes.mid(p,i-p);
ii=name1.find('[');
context.token->name=ii!=-1 ? name1.mid(0,ii) : name1; // take part without []
handleLinkedWord(parent,children);
if (ii!=-1) children.append<DocWord>(this,parent,name1.mid(ii)); // add [] part
p=i+1;
children.append<DocSeparator>(this,parent,"|");
}
name1 = paramTypes.mid(p);
ii=name1.find('[');
context.token->name=ii!=-1 ? name1.mid(0,ii) : name1;
handleLinkedWord(parent,children);
if (ii!=-1) children.append<DocWord>(this,parent,name1.mid(ii));
context.token->name = name; // restore original token name
}
void DocParser::handleInternalRef(DocNodeVariant *parent,DocNodeList &children)
{
Token tok=tokenizer.lex();
QCString tokenName = context.token->name;
AUTO_TRACE("name={}",tokenName);
if (!tok.is(TokenRetval::TK_WHITESPACE))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"expected whitespace after \\%s command",
qPrint(tokenName));
return;
}
tokenizer.setStateInternalRef();
tok=tokenizer.lex(); // get the reference id
if (!tok.is_any_of(TokenRetval::TK_WORD,TokenRetval::TK_LNKWORD))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"unexpected token %s as the argument of %s",
tok.to_string(),qPrint(tokenName));
return;
}
children.append<DocInternalRef>(this,parent,context.token->name);
children.get_last<DocInternalRef>()->parse();
}
void DocParser::handleAnchor(DocNodeVariant *parent,DocNodeList &children)
{
AUTO_TRACE();
Token tok=tokenizer.lex();
if (!tok.is(TokenRetval::TK_WHITESPACE))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"expected whitespace after \\%s command",
qPrint(context.token->name));
return;
}
tokenizer.setStateAnchor();
tok=tokenizer.lex();
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"unexpected end of comment block while parsing the "
"argument of command %s",qPrint(context.token->name));
return;
}
else if (!tok.is_any_of(TokenRetval::TK_WORD,TokenRetval::TK_LNKWORD))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"unexpected token %s as the argument of %s",
tok.to_string(),qPrint(context.token->name));
return;
}
tokenizer.setStatePara();
children.append<DocAnchor>(this,parent,context.token->name,FALSE);
}
void DocParser::handlePrefix(DocNodeVariant *parent,DocNodeList &children)
{
AUTO_TRACE();
Token tok=tokenizer.lex();
if (!tok.is(TokenRetval::TK_WHITESPACE))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"expected whitespace after \\%s command",
qPrint(context.token->name));
return;
}
tokenizer.setStatePrefix();
tok=tokenizer.lex();
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"unexpected end of comment block while parsing the "
"argument of command %s",qPrint(context.token->name));
return;
}
else if (!tok.is(TokenRetval::TK_WORD))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"unexpected token %s as the argument of %s",
tok.to_string(),qPrint(context.token->name));
return;
}
context.prefix = context.token->name;
tokenizer.setStatePara();
}
/* Helper function that deals with the title, width, and height arguments of various commands.
* @param[in] cmd Command id for which to extract caption and size info.
* @param[in] parent Parent node, owner of the children list passed as
* the third argument.
* @param[in] children The list of child nodes to which the node representing
* the token can be added.
* @param[out] width the extracted width specifier
* @param[out] height the extracted height specifier
*/
void DocParser::defaultHandleTitleAndSize(const CommandType cmd, DocNodeVariant *parent, DocNodeList &children, QCString &width,QCString &height)
{
AUTO_TRACE();
auto ns = AutoNodeStack(this,parent);
// parse title
tokenizer.setStateTitle();
Token tok = tokenizer.lex();
while (!tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
if (tok.is(TokenRetval::TK_WORD) && (context.token->name=="width=" || context.token->name=="height="))
{
// special case: no title, but we do have a size indicator
break;
}
else if (tok.is(TokenRetval::TK_HTMLTAG))
{
tokenizer.unputString(context.token->text);
break;
}
if (!defaultHandleToken(parent,tok,children))
{
errorHandleDefaultToken(parent,tok,children,Mappers::cmdMapper->find(cmd));
}
tok = tokenizer.lex();
}
// parse size attributes
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
tok=tokenizer.lex();
}
while (tok.is_any_of(TokenRetval::TK_WHITESPACE,TokenRetval::TK_WORD,TokenRetval::TK_HTMLTAG)) // there are values following the title
{
if (tok.is(TokenRetval::TK_WORD))
{
if (context.token->name=="width=" || context.token->name=="height=")
{
tokenizer.setStateTitleAttrValue();
context.token->name = context.token->name.left(context.token->name.length()-1);
}
if (context.token->name=="width")
{
width = context.token->chars;
}
else if (context.token->name=="height")
{
height = context.token->chars;
}
else // other text after the title -> treat as normal text
{
tokenizer.unputString(context.token->name);
//warn_doc_error(context.fileName,tokenizer.getLineNr(),"Unknown option '%s' after \\%s command, expected 'width' or 'height'",
// qPrint(context.token->name), qPrint(Mappers::cmdMapper->find(cmd)));
break;
}
}
tok=tokenizer.lex();
// if we found something we did not expect, push it back to the stream
// so it can still be processed
if (tok.is_any_of(TokenRetval::TK_COMMAND_AT,TokenRetval::TK_COMMAND_BS))
{
tokenizer.unputString(context.token->name);
tokenizer.unputString(tok.is(TokenRetval::TK_COMMAND_AT) ? "@" : "\\");
break;
}
else if (tok.is(TokenRetval::TK_SYMBOL))
{
tokenizer.unputString(context.token->name);
break;
}
else if (tok.is(TokenRetval::TK_HTMLTAG))
{
tokenizer.unputString(context.token->text);
break;
}
}
tokenizer.setStatePara();
handlePendingStyleCommands(parent,children);
AUTO_TRACE_EXIT("width={} height={}",width,height);
}
void DocParser::handleImage(DocNodeVariant *parent, DocNodeList &children)
{
AUTO_TRACE();
bool inlineImage = false;
QCString anchorStr;
Token tok=tokenizer.lex();
if (!tok.is(TokenRetval::TK_WHITESPACE))
{
if (tok.is(TokenRetval::TK_WORD))
{
if (context.token->name == "{")
{
tokenizer.setStateOptions();
tokenizer.lex();
tokenizer.setStatePara();
StringVector optList=split(context.token->name.str(),",");
for (const auto &opt : optList)
{
if (opt.empty()) continue;
QCString locOpt(opt);
QCString locOptLow;
locOpt = locOpt.stripWhiteSpace();
locOptLow = locOpt.lower();
if (locOptLow == "inline")
{
inlineImage = true;
}
else if (locOptLow.startsWith("anchor:"))
{
if (!anchorStr.isEmpty())
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"multiple use of option 'anchor' for 'image' command, ignoring: '%s'",
qPrint(locOpt.mid(7)));
}
else
{
anchorStr = locOpt.mid(7);
}
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"unknown option '%s' for 'image' command specified",
qPrint(locOpt));
}
}
tok=tokenizer.lex();
if (!tok.is(TokenRetval::TK_WHITESPACE))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"expected whitespace after \\image command");
return;
}
}
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"expected whitespace after \\image command");
return;
}
}
tok=tokenizer.lex();
if (!tok.is_any_of(TokenRetval::TK_WORD,TokenRetval::TK_LNKWORD))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"unexpected token %s as the argument of \\image",
tok.to_string());
return;
}
tok=tokenizer.lex();
if (!tok.is(TokenRetval::TK_WHITESPACE))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"expected whitespace after \\image command");
return;
}
DocImage::Type t = DocImage::Html;
QCString imgType = context.token->name.lower();
if (imgType=="html") t=DocImage::Html;
else if (imgType=="latex") t=DocImage::Latex;
else if (imgType=="docbook") t=DocImage::DocBook;
else if (imgType=="rtf") t=DocImage::Rtf;
else if (imgType=="xml") t=DocImage::Xml;
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"output format `%s` specified as the first argument of "
"\\image command is not valid",
qPrint(imgType));
return;
}
tokenizer.setStateFile();
tok=tokenizer.lex();
tokenizer.setStatePara();
if (!tok.is(TokenRetval::TK_WORD))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"unexpected token %s as the argument of \\image",
tok.to_string());
return;
}
if (!anchorStr.isEmpty())
{
children.append<DocAnchor>(this,parent,anchorStr,true);
}
HtmlAttribList attrList;
children.append<DocImage>(this,parent,attrList,
findAndCopyImage(context.token->name,t),t,"",inlineImage);
children.get_last<DocImage>()->parse();
}
/* Helper function that deals with the most common tokens allowed in
* title like sections.
* @param parent Parent node, owner of the children list passed as
* the third argument.
* @param tok The token to process.
* @param children The list of child nodes to which the node representing
* the token can be added.
* @param handleWord Indicates if word token should be processed
* @retval TRUE The token was handled.
* @retval FALSE The token was not handled.
*/
bool DocParser::defaultHandleToken(DocNodeVariant *parent,Token tok, DocNodeList &children,bool handleWord)
{
AUTO_TRACE("token={} handleWord={}",tok.to_string(),handleWord);
if (tok.is_any_of(TokenRetval::TK_WORD,TokenRetval::TK_LNKWORD,TokenRetval::TK_SYMBOL,TokenRetval::TK_URL,
TokenRetval::TK_COMMAND_AT,TokenRetval::TK_COMMAND_BS,TokenRetval::TK_HTMLTAG)
)
{
}
reparsetoken:
QCString tokenName = context.token->name;
AUTO_TRACE_ADD("tokenName={}",tokenName);
switch (tok.value())
{
case TokenRetval::TK_COMMAND_AT:
// fall through
case TokenRetval::TK_COMMAND_BS:
switch (Mappers::cmdMapper->map(tokenName))
{
case CommandType::CMD_BSLASH:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_BSlash);
break;
case CommandType::CMD_AT:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_At);
break;
case CommandType::CMD_LESS:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Less);
break;
case CommandType::CMD_GREATER:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Greater);
break;
case CommandType::CMD_AMP:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Amp);
break;
case CommandType::CMD_DOLLAR:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Dollar);
break;
case CommandType::CMD_HASH:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Hash);
break;
case CommandType::CMD_DCOLON:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_DoubleColon);
break;
case CommandType::CMD_PERCENT:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Percent);
break;
case CommandType::CMD_NDASH:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Minus);
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Minus);
break;
case CommandType::CMD_MDASH:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Minus);
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Minus);
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Minus);
break;
case CommandType::CMD_QUOTE:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Quot);
break;
case CommandType::CMD_PUNT:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Dot);
break;
case CommandType::CMD_PLUS:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Plus);
break;
case CommandType::CMD_MINUS:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Minus);
break;
case CommandType::CMD_EQUAL:
children.append<DocSymbol>(this,parent,HtmlEntityMapper::Sym_Equal);
break;
case CommandType::CMD_EMPHASIS:
{
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),DocStyleChange::Italic,tokenName,TRUE);
tok=handleStyleArgument(parent,children,tokenName);
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),DocStyleChange::Italic,tokenName,FALSE);
if (!tok.is(TokenRetval::TK_WORD)) children.append<DocWhiteSpace>(this,parent," ");
if (tok.is(TokenRetval::TK_NEWPARA)) goto handlepara;
else if (tok.is_any_of(TokenRetval::TK_WORD,TokenRetval::TK_HTMLTAG))
{
AUTO_TRACE_ADD("CommandType::CMD_EMPHASIS: reparsing");
goto reparsetoken;
}
}
break;
case CommandType::CMD_BOLD:
{
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),DocStyleChange::Bold,tokenName,TRUE);
tok=handleStyleArgument(parent,children,tokenName);
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),DocStyleChange::Bold,tokenName,FALSE);
if (!tok.is(TokenRetval::TK_WORD)) children.append<DocWhiteSpace>(this,parent," ");
if (tok.is(TokenRetval::TK_NEWPARA)) goto handlepara;
else if (tok.is_any_of(TokenRetval::TK_WORD,TokenRetval::TK_HTMLTAG))
{
AUTO_TRACE_ADD("CommandType::CMD_BOLD: reparsing");
goto reparsetoken;
}
}
break;
case CommandType::CMD_CODE:
{
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),DocStyleChange::Code,tokenName,TRUE);
tok=handleStyleArgument(parent,children,tokenName);
children.append<DocStyleChange>(this,parent,context.nodeStack.size(),DocStyleChange::Code,tokenName,FALSE);
if (!tok.is(TokenRetval::TK_WORD)) children.append<DocWhiteSpace>(this,parent," ");
if (tok.is(TokenRetval::TK_NEWPARA)) goto handlepara;
else if (tok.is_any_of(TokenRetval::TK_WORD,TokenRetval::TK_HTMLTAG))
{
AUTO_TRACE_ADD("CommandType::CMD_CODE: reparsing");
goto reparsetoken;
}
}
break;
case CommandType::CMD_HTMLONLY:
{
tokenizer.setStateHtmlOnly();
tok = tokenizer.lex();
children.append<DocVerbatim>(this,parent,context.context,context.token->verb,DocVerbatim::HtmlOnly,context.isExample,context.exampleName,context.token->name=="block");
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"htmlonly section ended without end marker");
}
tokenizer.setStatePara();
}
break;
case CommandType::CMD_MANONLY:
{
tokenizer.setStateManOnly();
tok = tokenizer.lex();
children.append<DocVerbatim>(this,parent,context.context,context.token->verb,DocVerbatim::ManOnly,context.isExample,context.exampleName);
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"manonly section ended without end marker");
}
tokenizer.setStatePara();
}
break;
case CommandType::CMD_RTFONLY:
{
tokenizer.setStateRtfOnly();
tok = tokenizer.lex();
children.append<DocVerbatim>(this,parent,context.context,context.token->verb,DocVerbatim::RtfOnly,context.isExample,context.exampleName);
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"rtfonly section ended without end marker");
}
tokenizer.setStatePara();
}
break;
case CommandType::CMD_LATEXONLY:
{
tokenizer.setStateLatexOnly();
tok = tokenizer.lex();
children.append<DocVerbatim>(this,parent,context.context,context.token->verb,DocVerbatim::LatexOnly,context.isExample,context.exampleName);
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"latexonly section ended without end marker");
}
tokenizer.setStatePara();
}
break;
case CommandType::CMD_XMLONLY:
{
tokenizer.setStateXmlOnly();
tok = tokenizer.lex();
children.append<DocVerbatim>(this,parent,context.context,context.token->verb,DocVerbatim::XmlOnly,context.isExample,context.exampleName);
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"xmlonly section ended without end marker");
}
tokenizer.setStatePara();
}
break;
case CommandType::CMD_DBONLY:
{
tokenizer.setStateDbOnly();
tok = tokenizer.lex();
children.append<DocVerbatim>(this,parent,context.context,context.token->verb,DocVerbatim::DocbookOnly,context.isExample,context.exampleName);
if (tok.is_any_of(TokenRetval::TK_NONE,TokenRetval::TK_EOF))
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"docbookonly section ended without end marker");
}
tokenizer.setStatePara();
}
break;
case CommandType::CMD_FORMULA:
{
children.append<DocFormula>(this,parent,context.token->id);
}
break;
case CommandType::CMD_ANCHOR:
case CommandType::CMD_IANCHOR:
{
handleAnchor(parent,children);
}
break;
case CommandType::CMD_IPREFIX:
{
handlePrefix(parent,children);
}
break;
case CommandType::CMD_INTERNALREF:
{
handleInternalRef(parent,children);
tokenizer.setStatePara();
}
break;
case CommandType::CMD_SETSCOPE:
{
tokenizer.setStateSetScope();
(void)tokenizer.lex();
context.context = context.token->name;
//printf("Found scope='%s'\n",qPrint(context.context));
tokenizer.setStatePara();
}
break;
case CommandType::CMD_IMAGE:
handleImage(parent,children);
break;
case CommandType::CMD_ILINE:
tokenizer.pushState();
tokenizer.setStateILine();
(void)tokenizer.lex();
tokenizer.popState();
break;
case CommandType::CMD_IFILE:
tokenizer.pushState();
tokenizer.setStateIFile();
(void)tokenizer.lex();
tokenizer.popState();
break;
default:
return FALSE;
}
break;
case TokenRetval::TK_HTMLTAG:
{
switch (Mappers::htmlTagMapper->map(tokenName))
{
case HtmlTagType::HTML_DIV:
warn_doc_error(context.fileName,tokenizer.getLineNr(),"found <div> tag in heading");
break;
case HtmlTagType::HTML_PRE:
warn_doc_error(context.fileName,tokenizer.getLineNr(),"found <pre> tag in heading");
break;
case HtmlTagType::HTML_BOLD:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Bold,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Bold,tokenName);
}
break;
case HtmlTagType::HTML_S:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::S,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::S,tokenName);
}
break;
case HtmlTagType::HTML_STRIKE:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Strike,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Strike,tokenName);
}
break;
case HtmlTagType::HTML_DEL:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Del,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Del,tokenName);
}
break;
case HtmlTagType::HTML_UNDERLINE:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Underline,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Underline,tokenName);
}
break;
case HtmlTagType::HTML_INS:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Ins,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Ins,tokenName);
}
break;
case HtmlTagType::HTML_CODE:
case HtmlTagType::XML_C:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Code,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Code,tokenName);
}
break;
case HtmlTagType::HTML_KBD:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Kbd,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Kbd,tokenName);
}
break;
case HtmlTagType::HTML_EMPHASIS:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Italic,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Italic,tokenName);
}
break;
case HtmlTagType::HTML_SUB:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Subscript,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Subscript,tokenName);
}
break;
case HtmlTagType::HTML_SUP:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Superscript,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Superscript,tokenName);
}
break;
case HtmlTagType::HTML_CENTER:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Center,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Center,tokenName);
}
break;
case HtmlTagType::HTML_SMALL:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Small,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Small,tokenName);
}
break;
case HtmlTagType::HTML_CITE:
if (!context.token->endTag)
{
handleStyleEnter(parent,children,DocStyleChange::Cite,tokenName,&context.token->attribs);
}
else
{
handleStyleLeave(parent,children,DocStyleChange::Cite,tokenName);
}
break;
case HtmlTagType::HTML_IMG:
if (!context.token->endTag)
handleImg(parent,children,context.token->attribs);
break;
default:
return FALSE;
break;
}
}
break;
case TokenRetval::TK_SYMBOL:
{
HtmlEntityMapper::SymType s = DocSymbol::decodeSymbol(tokenName);
if (s!=HtmlEntityMapper::Sym_Unknown)
{
children.append<DocSymbol>(this,parent,s);
}
else
{
return FALSE;
}
}
break;
case TokenRetval::TK_WHITESPACE:
case TokenRetval::TK_NEWPARA:
handlepara:
if (insidePRE(parent) || !children.empty())
{
children.append<DocWhiteSpace>(this,parent,context.token->chars);
}
break;
case TokenRetval::TK_LNKWORD:
if (handleWord)
{
handleLinkedWord(parent,children);
}
else
return FALSE;
break;
case TokenRetval::TK_WORD:
if (handleWord)
{
children.append<DocWord>(this,parent,context.token->name);
}
else
return FALSE;
break;
case TokenRetval::TK_URL:
if (context.insideHtmlLink)
{
children.append<DocWord>(this,parent,context.token->name);
}
else
{
children.append<DocURL>(this,parent,context.token->name,context.token->isEMailAddr);
}
break;
default:
return FALSE;
}
return TRUE;
}
//---------------------------------------------------------------------------
void DocParser::handleImg(DocNodeVariant *parent, DocNodeList &children,const HtmlAttribList &tagHtmlAttribs)
{
AUTO_TRACE();
bool found=FALSE;
size_t index=0;
for (const auto &opt : tagHtmlAttribs)
{
AUTO_TRACE_ADD("option name={} value='{}'",opt.name,opt.value);
if (opt.name=="src" && !opt.value.isEmpty())
{
// copy attributes
HtmlAttribList attrList = tagHtmlAttribs;
// and remove the src attribute
attrList.erase(attrList.begin()+index);
DocImage::Type t = DocImage::Html;
children.append<DocImage>(
this,parent,attrList,
findAndCopyImage(opt.value,t,false),
t,opt.value);
found = TRUE;
}
++index;
}
if (!found)
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"IMG tag does not have a SRC attribute!");
}
}
//---------------------------------------------------------------------------
Token DocParser::internalValidatingParseDoc(DocNodeVariant *parent,DocNodeList &children,
const QCString &doc)
{
AUTO_TRACE();
Token retval = Token::make_RetVal_OK();
if (doc.isEmpty()) return retval;
tokenizer.init(doc.data(),context.fileName,context.markdownSupport,context.insideHtmlLink);
// first parse any number of paragraphs
bool isFirst=TRUE;
DocPara *lastPar=!children.empty() ? std::get_if<DocPara>(&children.back()): nullptr;
if (lastPar)
{ // last child item was a paragraph
isFirst=FALSE;
}
do
{
children.append<DocPara>(this,parent);
DocPara *par = children.get_last<DocPara>();
if (isFirst) { par->markFirst(); isFirst=FALSE; }
retval=par->parse();
if (!par->isEmpty())
{
if (lastPar) lastPar->markLast(FALSE);
lastPar=par;
}
else
{
children.pop_back();
}
} while (retval.is(TokenRetval::TK_NEWPARA));
if (lastPar) lastPar->markLast();
AUTO_TRACE_EXIT("isFirst={} isLast={}",lastPar?lastPar->isFirst():-1,lastPar?lastPar->isLast():-1);
return retval;
}
//---------------------------------------------------------------------------
void DocParser::readTextFileByName(const QCString &file,QCString &text)
{
AUTO_TRACE("file={} text={}",file,text);
bool ambig = false;
QCString filePath = findFilePath(file,ambig);
if (!filePath.isEmpty())
{
text = fileToString(filePath,Config_getBool(FILTER_SOURCE_FILES));
if (ambig)
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"included file name '%s' is ambiguous"
"Possible candidates:\n%s",qPrint(file),
qPrint(showFileDefMatches(Doxygen::exampleNameLinkedMap,file))
);
}
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),"included file '%s' is not found. "
"Check your EXAMPLE_PATH",qPrint(file));
}
}
//---------------------------------------------------------------------------
static QCString extractCopyDocId(const char *data, size_t &j, size_t len)
{
size_t s=j;
int round=0;
bool insideDQuote=FALSE;
bool insideSQuote=FALSE;
bool found=FALSE;
while (j<len && !found)
{
if (!insideSQuote && !insideDQuote)
{
switch (data[j])
{
case '(': round++; break;
case ')': round--; break;
case '"': insideDQuote=TRUE; break;
case '\'': insideSQuote=TRUE; break;
case '\\': // fall through, begin of command
case '@': // fall through, begin of command
case '\t': // fall through
case '\n':
found=(round==0);
break;
case ' ': // allow spaces in cast operator (see issue #11169)
found=(round==0) && (j<8 || qstrncmp(data+j-8,"operator",8)!=0);
break;
}
}
else if (insideSQuote) // look for single quote end
{
if (data[j]=='\'' && (j==0 || data[j]!='\\'))
{
insideSQuote=FALSE;
}
}
else if (insideDQuote) // look for double quote end
{
if (data[j]=='"' && (j==0 || data[j]!='\\'))
{
insideDQuote=FALSE;
}
}
if (!found) j++;
}
// include const and volatile
if (qstrncmp(data+j," const",6)==0)
{
j+=6;
}
else if (qstrncmp(data+j," volatile",9)==0)
{
j+=9;
}
// allow '&' or '&&' or ' &' or ' &&' at the end
size_t k=j;
while (k<len && data[k]==' ') k++;
if (k<len-1 && data[k]=='&' && data[k+1]=='&') j=k+2;
else if (k<len && data[k]=='&' ) j=k+1;
// do not include punctuation added by Definition::_setBriefDescription()
size_t e=j;
if (j>0 && data[j-1]=='.') { e--; }
QCString id(data+s,e-s);
//printf("extractCopyDocId='%s' input='%s'\n",qPrint(id),&data[s]);
return id;
}
// macro to check if the input starts with a specific command.
// note that data[i] should point to the start of the command (\ or @ character)
// and the sizeof(str) returns the size of str including the '\0' terminator;
// a fact we abuse to skip over the start of the command character.
#define CHECK_FOR_COMMAND(str,action) \
do if ((i+sizeof(str)<len) && qstrncmp(data+i+1,str,sizeof(str)-1)==0) \
{ j=i+sizeof(str); action; } while(0)
static size_t isCopyBriefOrDetailsCmd(const char *data, size_t i,size_t len,bool &brief)
{
size_t j=0;
if (i==0 || (data[i-1]!='@' && data[i-1]!='\\')) // not an escaped command
{
CHECK_FOR_COMMAND("copybrief",brief=TRUE); // @copybrief or \copybrief
CHECK_FOR_COMMAND("copydetails",brief=FALSE); // @copydetails or \copydetails
}
return j;
}
static size_t isVerbatimSection(const char *data,size_t i,size_t len,QCString &endMarker)
{
size_t j=0;
if (i==0 || (data[i-1]!='@' && data[i-1]!='\\')) // not an escaped command
{
CHECK_FOR_COMMAND("dot",endMarker="enddot");
CHECK_FOR_COMMAND("icode",endMarker="endicode");
CHECK_FOR_COMMAND("code",endMarker="endcode");
CHECK_FOR_COMMAND("msc",endMarker="endmsc");
CHECK_FOR_COMMAND("iverbatim",endMarker="endiverbatim");
CHECK_FOR_COMMAND("verbatim",endMarker="endverbatim");
CHECK_FOR_COMMAND("iliteral",endMarker="endiliteral");
CHECK_FOR_COMMAND("latexonly",endMarker="endlatexonly");
CHECK_FOR_COMMAND("htmlonly",endMarker="endhtmlonly");
CHECK_FOR_COMMAND("xmlonly",endMarker="endxmlonly");
CHECK_FOR_COMMAND("rtfonly",endMarker="endrtfonly");
CHECK_FOR_COMMAND("manonly",endMarker="endmanonly");
CHECK_FOR_COMMAND("docbookonly",endMarker="enddocbookonly");
CHECK_FOR_COMMAND("startuml",endMarker="enduml");
}
//printf("isVerbatimSection(%s)=%d)\n",qPrint(QCString(&data[i]).left(10)),j);
return j;
}
static size_t skipToEndMarker(const char *data,size_t i,size_t len,const QCString &endMarker)
{
while (i<len)
{
if ((data[i]=='@' || data[i]=='\\') && // start of command character
(i==0 || (data[i-1]!='@' && data[i-1]!='\\'))) // that is not escaped
{
if (i+endMarker.length()+1<=len && qstrncmp(data+i+1,endMarker.data(),endMarker.length())==0)
{
return i+endMarker.length()+1;
}
}
i++;
}
// oops no endmarker found...
return i<len ? i+1 : len;
}
QCString DocParser::processCopyDoc(const char *data,size_t &len)
{
AUTO_TRACE("data={} len={}",Trace::trunc(data),len);
GrowBuf buf;
size_t i=0;
int lineNr = tokenizer.getLineNr();
while (i<len)
{
char c = data[i];
if (c=='@' || c=='\\') // look for a command
{
bool isBrief=TRUE;
size_t j=isCopyBriefOrDetailsCmd(data,i,len,isBrief);
if (j>0)
{
// skip whitespace
while (j<len && (data[j]==' ' || data[j]=='\t')) j++;
// extract the argument
QCString id = extractCopyDocId(data,j,len);
const Definition *def = nullptr;
QCString doc,brief;
//printf("resolving docs='%s'\n",qPrint(id));
bool found = findDocsForMemberOrCompound(id,&doc,&brief,&def);
if (found && def->isReference())
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"@copy%s or @copydoc target '%s' found but is from a tag file, skipped", isBrief?"brief":"details",
qPrint(id));
}
else if (found)
{
//printf("found it def=%p brief='%s' doc='%s' isBrief=%d\n",def,qPrint(brief),qPrint(doc),isBrief);
auto it = std::find(context.copyStack.begin(),context.copyStack.end(),def);
if (it==context.copyStack.end()) // definition not parsed earlier
{
QCString orgFileName = context.fileName;
context.copyStack.push_back(def);
auto addDocs = [&](const QCString &file_,int line_,const QCString &doc_)
{
buf.addStr(" \\ifile \""+file_+"\" ");
buf.addStr("\\iline "+QCString().setNum(line_)+" \\ilinebr ");
size_t len_ = doc_.length();
buf.addStr(processCopyDoc(doc_.data(),len_));
};
if (isBrief)
{
addDocs(def->briefFile(),def->briefLine(),brief);
}
else
{
addDocs(def->docFile(),def->docLine(),doc);
if (def->definitionType()==Definition::TypeMember)
{
const MemberDef *md = toMemberDef(def);
const ArgumentList &docArgList = md->templateMaster() ?
md->templateMaster()->argumentList() :
md->argumentList();
buf.addStr(inlineArgListToDoc(docArgList));
}
}
context.copyStack.pop_back();
buf.addStr(" \\ilinebr \\ifile \""+context.fileName+"\" ");
buf.addStr("\\iline "+QCString().setNum(lineNr)+" ");
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"Found recursive @copy%s or @copydoc relation for argument '%s'.",
isBrief?"brief":"details",qPrint(id));
}
}
else
{
warn_doc_error(context.fileName,tokenizer.getLineNr(),
"@copy%s or @copydoc target '%s' not found", isBrief?"brief":"details",
qPrint(id));
}
// skip over command
i=j;
}
else
{
QCString endMarker;
size_t k = isVerbatimSection(data,i,len,endMarker);
if (k>0)
{
size_t orgPos = i;
i=skipToEndMarker(data,k,len,endMarker);
buf.addStr(data+orgPos,i-orgPos);
// TODO: adjust lineNr
}
else
{
buf.addChar(c);
i++;
}
}
}
else // not a command, just copy
{
buf.addChar(c);
i++;
lineNr += (c=='\n') ? 1 : 0;
}
}
len = buf.getPos();
buf.addChar(0);
AUTO_TRACE_EXIT("result={}",Trace::trunc(buf.get()));
return buf.get();
}
//---------------------------------------------------------------------------
IDocNodeASTPtr validatingParseDoc(IDocParser &parserIntf,
const QCString &fileName,int startLine,
const Definition *ctx,const MemberDef *md,
const QCString &input,bool indexWords,
bool isExample, const QCString &exampleName,
bool singleLine, bool linkFromIndex,
bool markdownSupport)
{
DocParser *parser = dynamic_cast<DocParser*>(&parserIntf);
assert(parser!=nullptr);
if (parser==nullptr) return nullptr;
//printf("validatingParseDoc(%s,%s)=[%s]\n",ctx?qPrint(ctx->name()):"<none>",
// md?qPrint(md->name()):"<none>",
// input);
//printf("========== validating %s at line %d\n",qPrint(fileName),startLine);
//printf("---------------- input --------------------\n%s\n----------- end input -------------------\n",qPrint(input));
// set initial token
parser->context.token = parser->tokenizer.resetToken();
if (ctx && ctx!=Doxygen::globalScope &&
(ctx->definitionType()==Definition::TypeClass ||
ctx->definitionType()==Definition::TypeNamespace
)
)
{
parser->context.context = substitute(ctx->qualifiedName(),getLanguageSpecificSeparator(ctx->getLanguage(),true),"::");
}
else if (ctx && ctx->definitionType()==Definition::TypePage)
{
const Definition *scope = (toPageDef(ctx))->getPageScope();
if (scope && scope!=Doxygen::globalScope)
{
parser->context.context = substitute(scope->name(),getLanguageSpecificSeparator(scope->getLanguage(),true),"::");
}
}
else if (ctx && ctx->definitionType()==Definition::TypeGroup)
{
const Definition *scope = (toGroupDef(ctx))->getGroupScope();
if (scope && scope!=Doxygen::globalScope)
{
parser->context.context = substitute(scope->name(),getLanguageSpecificSeparator(scope->getLanguage(),true),"::");
}
}
else
{
parser->context.context = "";
}
parser->context.scope = ctx;
parser->context.lang = getLanguageFromFileName(fileName);
if (indexWords && Doxygen::searchIndex.enabled())
{
if (md)
{
parser->context.searchUrl=md->getOutputFileBase();
Doxygen::searchIndex.setCurrentDoc(md,md->anchor(),false);
}
else if (ctx)
{
parser->context.searchUrl=ctx->getOutputFileBase();
Doxygen::searchIndex.setCurrentDoc(ctx,ctx->anchor(),false);
}
}
else
{
parser->context.searchUrl="";
}
parser->context.fileName = fileName;
parser->context.relPath = (!linkFromIndex && ctx) ?
QCString(relativePathToRoot(ctx->getOutputFileBase())) :
QCString("");
//printf("ctx->name=%s relPath=%s\n",qPrint(ctx->name()),qPrint(parser->context.relPath));
parser->context.memberDef = md;
while (!parser->context.nodeStack.empty()) parser->context.nodeStack.pop();
while (!parser->context.styleStack.empty()) parser->context.styleStack.pop();
while (!parser->context.initialStyleStack.empty()) parser->context.initialStyleStack.pop();
parser->context.inSeeBlock = FALSE;
parser->context.xmlComment = FALSE;
parser->context.insideHtmlLink = FALSE;
parser->context.includeFileText = "";
parser->context.includeFileOffset = 0;
parser->context.includeFileLength = 0;
parser->context.isExample = isExample;
parser->context.exampleName = exampleName;
parser->context.hasParamCommand = FALSE;
parser->context.hasReturnCommand = FALSE;
parser->context.retvalsFound.clear();
parser->context.paramsFound.clear();
parser->context.markdownSupport = markdownSupport;
//printf("Starting comment block at %s:%d\n",qPrint(parser->context.fileName),startLine);
parser->tokenizer.setLineNr(startLine);
size_t ioLen = input.length();
QCString inpStr = parser->processCopyDoc(input.data(),ioLen);
if (inpStr.isEmpty() || inpStr.at(inpStr.length()-1)!='\n')
{
inpStr+='\n';
}
//printf("processCopyDoc(in='%s' out='%s')\n",input,qPrint(inpStr));
parser->tokenizer.init(inpStr.data(),parser->context.fileName,
parser->context.markdownSupport,parser->context.insideHtmlLink);
// build abstract syntax tree
auto ast = std::make_unique<DocNodeAST>(DocRoot(parser,md!=nullptr,singleLine));
std::get<DocRoot>(ast->root).parse();
if (Debug::isFlagSet(Debug::PrintTree))
{
// pretty print the result
std::visit(PrintDocVisitor{},ast->root);
}
if (md && md->isFunction())
{
parser->checkUnOrMultipleDocumentedParams();
}
if (parser->context.memberDef) parser->context.memberDef->detectUndocumentedParams(parser->context.hasParamCommand,parser->context.hasReturnCommand);
// reset token
parser->tokenizer.resetToken();
//printf(">>>>>> end validatingParseDoc(%s,%s)\n",ctx?qPrint(ctx->name()):"<none>",
// md?qPrint(md->name()):"<none>");
return ast;
}
IDocNodeASTPtr validatingParseText(IDocParser &parserIntf,const QCString &input)
{
DocParser *parser = dynamic_cast<DocParser*>(&parserIntf);
assert(parser!=nullptr);
if (parser==nullptr) return nullptr;
// set initial token
parser->context.token = parser->tokenizer.resetToken();
//printf("------------ input ---------\n%s\n"
// "------------ end input -----\n",input);
//parser->context.token = new TokenInfo;
parser->context.context = "";
parser->context.fileName = "<parseText>";
parser->context.relPath = "";
parser->context.memberDef = nullptr;
while (!parser->context.nodeStack.empty()) parser->context.nodeStack.pop();
while (!parser->context.styleStack.empty()) parser->context.styleStack.pop();
while (!parser->context.initialStyleStack.empty()) parser->context.initialStyleStack.pop();
parser->context.inSeeBlock = FALSE;
parser->context.xmlComment = FALSE;
parser->context.insideHtmlLink = FALSE;
parser->context.includeFileText = "";
parser->context.includeFileOffset = 0;
parser->context.includeFileLength = 0;
parser->context.isExample = FALSE;
parser->context.exampleName = "";
parser->context.hasParamCommand = FALSE;
parser->context.hasReturnCommand = FALSE;
parser->context.retvalsFound.clear();
parser->context.paramsFound.clear();
parser->context.searchUrl="";
parser->context.lang = SrcLangExt::Unknown;
parser->context.markdownSupport = Config_getBool(MARKDOWN_SUPPORT);
auto ast = std::make_unique<DocNodeAST>(DocText(parser));
if (!input.isEmpty())
{
parser->tokenizer.setLineNr(1);
parser->tokenizer.init(input.data(),parser->context.fileName,
parser->context.markdownSupport,parser->context.insideHtmlLink);
// build abstract syntax tree
std::get<DocText>(ast->root).parse();
if (Debug::isFlagSet(Debug::PrintTree))
{
// pretty print the result
std::visit(PrintDocVisitor{},ast->root);
}
}
return ast;
}
IDocNodeASTPtr createRef(IDocParser &parserIntf,const QCString &target,const QCString &context, const QCString &srcFile, int srcLine )
{
DocParser *parser = dynamic_cast<DocParser*>(&parserIntf);
assert(parser!=nullptr);
if (parser==nullptr) return nullptr;
if (!srcFile.isEmpty())
{
parser->context.fileName = srcFile;
parser->tokenizer.setLineNr(srcLine);
}
return std::make_unique<DocNodeAST>(DocRef(parser,nullptr,target,context));
}
void docFindSections(const QCString &input,
const Definition *d,
const QCString &fileName)
{
DocParser parser;
parser.tokenizer.findSections(input,d,fileName);
}
| 77,897
|
C++
|
.cpp
| 2,106
| 29.959639
| 179
| 0.621375
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,406
|
htmlgen.cpp
|
doxygen_doxygen/src/htmlgen.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 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.
*
*/
#include <stdlib.h>
#include <assert.h>
#include <mutex>
#include "message.h"
#include "htmlgen.h"
#include "config.h"
#include "util.h"
#include "doxygen.h"
#include "diagram.h"
#include "version.h"
#include "dot.h"
#include "dotcallgraph.h"
#include "dotclassgraph.h"
#include "dotdirdeps.h"
#include "dotgfxhierarchytable.h"
#include "dotgroupcollaboration.h"
#include "dotincldepgraph.h"
#include "language.h"
#include "htmlhelp.h"
#include "docparser.h"
#include "docnode.h"
#include "htmldocvisitor.h"
#include "searchindex.h"
#include "pagedef.h"
#include "debug.h"
#include "dirdef.h"
#include "vhdldocgen.h"
#include "layout.h"
#include "image.h"
#include "ftvhelp.h"
#include "resourcemgr.h"
#include "tooltip.h"
#include "growbuf.h"
#include "fileinfo.h"
#include "dir.h"
#include "utf8.h"
#include "textstream.h"
#include "indexlist.h"
#include "datetime.h"
#include "portable.h"
#include "outputlist.h"
//#define DBG_HTML(x) x;
#define DBG_HTML(x)
static QCString g_header;
static QCString g_footer;
static QCString g_mathjax_code;
static QCString g_latex_macro;
static constexpr auto hex="0123456789ABCDEF";
static const SelectionMarkerInfo htmlMarkerInfo = { '<', "<!--BEGIN ",10,"<!--END ",8,"-->",3 };
// note: this is only active if DISABLE_INDEX=YES, if DISABLE_INDEX is disabled, this
// part will be rendered inside menu.js
static void writeClientSearchBox(TextStream &t,const QCString &relPath)
{
t << " <div id=\"MSearchBox\" class=\"MSearchBoxInactive\">\n";
t << " <span class=\"left\">\n";
t << " <span id=\"MSearchSelect\" ";
t << " onmouseover=\"return searchBox.OnSearchSelectShow()\" ";
t << " onmouseout=\"return searchBox.OnSearchSelectHide()\"> </span>\n";
t << " <input type=\"text\" id=\"MSearchField\" value=\"\" placeholder=\""
<< theTranslator->trSearch() << "\" accesskey=\"S\"\n";
t << " onfocus=\"searchBox.OnSearchFieldFocus(true)\" \n";
t << " onblur=\"searchBox.OnSearchFieldFocus(false)\" \n";
t << " onkeyup=\"searchBox.OnSearchFieldChange(event)\"/>\n";
t << " </span><span class=\"right\">\n";
t << " <a id=\"MSearchClose\" href=\"javascript:searchBox.CloseResultsWindow()\">"
<< "<img id=\"MSearchCloseImg\" border=\"0\" src=\"" << relPath << "search/close.svg\" alt=\"\"/></a>\n";
t << " </span>\n";
t << " </div>\n";
}
// note: this is only active if DISABLE_INDEX=YES. if DISABLE_INDEX is disabled, this
// part will be rendered inside menu.js
static void writeServerSearchBox(TextStream &t,const QCString &relPath,bool highlightSearch)
{
bool externalSearch = Config_getBool(EXTERNAL_SEARCH);
t << " <div id=\"MSearchBox\" class=\"MSearchBoxInactive\">\n";
t << " <div class=\"left\">\n";
t << " <form id=\"FSearchBox\" action=\"" << relPath;
if (externalSearch)
{
t << "search" << Doxygen::htmlFileExtension;
}
else
{
t << "search.php";
}
t << "\" method=\"get\">\n";
t << " <span id=\"MSearchSelectExt\"> </span>\n";
if (!highlightSearch)
{
t << " <input type=\"text\" id=\"MSearchField\" name=\"query\" value=\"\" placeholder=\""
<< theTranslator->trSearch() << "\" size=\"20\" accesskey=\"S\" \n";
t << " onfocus=\"searchBox.OnSearchFieldFocus(true)\" \n";
t << " onblur=\"searchBox.OnSearchFieldFocus(false)\"/>\n";
t << " </form>\n";
t << " </div><div class=\"right\"></div>\n";
t << " </div>\n";
}
}
//------------------------------------------------------------------------
/// Convert a set of LaTeX commands `\(re)newcommand` to a form readable by MathJax
/// LaTeX syntax:
/// ```
/// \newcommand{\cmd}{replacement}
/// or
/// \renewcommand{\cmd}{replacement}
/// ```
/// MathJax syntax:
/// ```
/// cmd: "{replacement}"
/// ```
///
/// LaTeX syntax:
/// ```
/// \newcommand{\cmd}[nr]{replacement}
/// or
/// \renewcommand{\cmd}[nr]{replacement}
/// ```
/// MathJax syntax:
/// ```
/// cmd: ["{replacement}",nr]
/// ```
static QCString getConvertLatexMacro()
{
QCString macrofile = Config_getString(FORMULA_MACROFILE);
if (macrofile.isEmpty()) return "";
QCString s = fileToString(macrofile);
macrofile = FileInfo(macrofile.str()).absFilePath();
size_t size = s.length();
GrowBuf out(size);
const char *data = s.data();
int line = 1;
int cnt = 0;
size_t i = 0;
QCString nr;
while (i < size)
{
nr = "";
// skip initial white space, but count lines
while (i < size && (data[i] == ' ' || data[i] == '\t' || data[i] == '\n'))
{
if (data[i] == '\n') line++;
i++;
}
if (i >= size) break;
// check for \newcommand or \renewcommand
if (data[i] != '\\')
{
warn(macrofile,line, "file contains non valid code, expected '\\' got '%c'",data[i]);
return "";
}
i++;
if (!qstrncmp(data + i, "newcommand", strlen("newcommand")))
{
i += strlen("newcommand");
}
else if (!qstrncmp(data + i, "renewcommand", strlen("renewcommand")))
{
i += strlen("renewcommand");
}
else
{
warn(macrofile,line, "file contains non valid code, expected 'newcommand' or 'renewcommand'");
return "";
}
// handle {cmd}
if (data[i] != '{')
{
warn(macrofile,line, "file contains non valid code, expected '{' got '%c'",data[i]);
return "";
}
i++;
if (data[i] != '\\')
{
warn(macrofile,line, "file contains non valid code, expected '\\' got '%c'",data[i]);
return "";
}
i++;
// run till }, i.e. cmd
out.addStr(" ");
while (i < size && (data[i] != '}')) out.addChar(data[i++]);
if (i >= size)
{
warn(macrofile,line, "file contains non valid code, no closing '}' for command");
return "";
}
out.addChar(':');
out.addChar(' ');
i++;
if (data[i] == '[')
{
// handle [nr]
// run till ]
out.addChar('[');
i++;
while (i < size && (data[i] != ']')) nr += data[i++];
if (i >= size)
{
warn(macrofile,line, "file contains non valid code, no closing ']'");
return "";
}
i++;
}
else if (data[i] != '{')
{
warn(macrofile,line, "file contains non valid code, expected '[' or '{' got '%c'",data[i]);
return "";
}
// handle {replacement}
// retest as the '[' part might have advanced so we can have a new '{'
if (data[i] != '{')
{
warn(macrofile,line, "file contains non valid code, expected '{' got '%c'",data[i]);
return "";
}
out.addChar('"');
out.addChar('{');
i++;
// run till }
cnt = 1;
while (i < size && cnt)
{
switch(data[i])
{
case '\\':
out.addChar('\\'); // need to escape it for MathJax js code
out.addChar('\\');
i++;
if (data[i] == '\\') // we have an escaped backslash
{
out.addChar('\\');
out.addChar('\\');
i++;
}
else if (data[i] != '"') out.addChar(data[i++]); // double quote handled separately
break;
case '{':
cnt++;
out.addChar(data[i++]);
break;
case '}':
cnt--;
if (cnt) out.addChar(data[i]);
i++;
break;
case '"':
out.addChar('\\'); // need to escape it for MathJax js code
out.addChar(data[i++]);
break;
case '\n':
line++;
out.addChar(data[i++]);
break;
default:
out.addChar(data[i++]);
break;
}
}
if (i > size)
{
warn(macrofile,line, "file contains non valid code, no closing '}' for replacement");
return "";
}
out.addChar('}');
out.addChar('"');
if (!nr.isEmpty())
{
out.addChar(',');
out.addStr(nr);
}
if (!nr.isEmpty())
{
out.addChar(']');
}
out.addChar(',');
out.addChar('\n');
}
out.addChar(0);
return out.get();
}
static QCString getSearchBox(bool serverSide, QCString relPath, bool highlightSearch)
{
TextStream t;
if (serverSide)
{
writeServerSearchBox(t, relPath, highlightSearch);
}
else
{
writeClientSearchBox(t, relPath);
}
return t.str();
}
static QCString substituteHtmlKeywords(const QCString &str,
const QCString &title,
const QCString &relPath,
const QCString &navPath=QCString())
{
// Build CSS/JavaScript tags depending on treeview, search engine settings
QCString cssFile;
QCString generatedBy;
QCString treeViewCssJs;
QCString searchCssJs;
QCString searchBox;
QCString mathJaxJs;
QCString extraCssText;
QCString projectName = Config_getString(PROJECT_NAME);
bool treeView = Config_getBool(GENERATE_TREEVIEW);
bool searchEngine = Config_getBool(SEARCHENGINE);
bool serverBasedSearch = Config_getBool(SERVER_BASED_SEARCH);
bool mathJax = Config_getBool(USE_MATHJAX);
QCString mathJaxFormat = Config_getEnumAsString(MATHJAX_FORMAT);
bool disableIndex = Config_getBool(DISABLE_INDEX);
bool hasProjectName = !projectName.isEmpty();
bool hasProjectNumber = !Config_getString(PROJECT_NUMBER).isEmpty();
bool hasProjectBrief = !Config_getString(PROJECT_BRIEF).isEmpty();
bool hasProjectLogo = !Config_getString(PROJECT_LOGO).isEmpty();
bool hasProjectIcon = !Config_getString(PROJECT_ICON).isEmpty();
bool hasFullSideBar = Config_getBool(FULL_SIDEBAR) && disableIndex && treeView;
bool hasCopyClipboard = Config_getBool(HTML_COPY_CLIPBOARD);
bool hasCookie = treeView || searchEngine || Config_getEnum(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::TOGGLE;
static bool titleArea = (hasProjectName || hasProjectBrief || hasProjectLogo || (disableIndex && searchEngine));
cssFile = Config_getString(HTML_STYLESHEET);
if (cssFile.isEmpty())
{
cssFile = "doxygen.css";
}
else
{
if (!cssFile.startsWith("http:") && !cssFile.startsWith("https:"))
{
FileInfo cssfi(cssFile.str());
if (cssfi.exists())
{
cssFile = cssfi.fileName();
}
else
{
cssFile = "doxygen.css";
}
}
}
extraCssText = "";
const StringVector &extraCssFile = Config_getList(HTML_EXTRA_STYLESHEET);
for (const auto &fileName : extraCssFile)
{
if (!fileName.empty())
{
QCString htmlStyleSheet = fileName.c_str();
if (htmlStyleSheet.startsWith("http:") || htmlStyleSheet.startsWith("https:"))
{
extraCssText += "<link href=\""+htmlStyleSheet+"\" rel=\"stylesheet\" type=\"text/css\"/>\n";
}
else
{
FileInfo fi(fileName);
if (fi.exists())
{
extraCssText += "<link href=\"$relpath^"+stripPath(fileName.c_str())+"\" rel=\"stylesheet\" type=\"text/css\"/>\n";
}
}
}
}
switch (Config_getEnum(TIMESTAMP))
{
case TIMESTAMP_t::YES:
case TIMESTAMP_t::DATETIME:
generatedBy = theTranslator->trGeneratedAt(dateToString(DateTimeType::DateTime),
convertToHtml(Config_getString(PROJECT_NAME)));
break;
case TIMESTAMP_t::DATE:
generatedBy = theTranslator->trGeneratedAt(dateToString(DateTimeType::Date),
convertToHtml(Config_getString(PROJECT_NAME)));
break;
case TIMESTAMP_t::NO:
generatedBy = theTranslator->trGeneratedBy();
break;
}
treeViewCssJs = "<link href=\"$relpath^navtree.css\" rel=\"stylesheet\" type=\"text/css\"/>\n";
if (treeView)
{
treeViewCssJs += "<script type=\"text/javascript\" src=\"$relpath^navtreedata.js\"></script>\n"
"<script type=\"text/javascript\" src=\"$relpath^navtree.js\"></script>\n";
}
treeViewCssJs += "<script type=\"text/javascript\" src=\"$relpath^resize.js\"></script>\n";
if (searchEngine)
{
searchCssJs = "<link href=\"$relpath^search/search.css\" rel=\"stylesheet\" type=\"text/css\"/>\n";
if (!serverBasedSearch)
{
searchCssJs += "<script type=\"text/javascript\" src=\"$relpath^search/searchdata.js\"></script>\n";
}
searchCssJs += "<script type=\"text/javascript\" src=\"$relpath^search/search.js\"></script>\n";
if (!serverBasedSearch)
{
if (disableIndex || !Config_getBool(HTML_DYNAMIC_MENUS))
{
searchCssJs += "<script type=\"text/javascript\">\n"
"/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n"
" $(function() { init_search(); });\n"
"/* @license-end */\n"
"</script>";
}
}
else
{
if (disableIndex || !Config_getBool(HTML_DYNAMIC_MENUS))
{
searchCssJs += "<script type=\"text/javascript\">\n"
"/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n"
" $(function() {\n"
" if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); }\n"
" });\n"
" /* @license-end */\n"
"</script>\n";
}
// OPENSEARCH_PROVIDER {
searchCssJs += "<link rel=\"search\" href=\"" + relPath +
"search_opensearch.php?v=opensearch.xml\" "
"type=\"application/opensearchdescription+xml\" title=\"" +
(hasProjectName ? projectName : QCString("Doxygen")) +
"\"/>";
// OPENSEARCH_PROVIDER }
}
searchBox = getSearchBox(serverBasedSearch, relPath, FALSE);
}
if (mathJax)
{
auto mathJaxVersion = Config_getEnum(MATHJAX_VERSION);
QCString path = Config_getString(MATHJAX_RELPATH);
if (path.isEmpty() || path.startsWith("..")) // relative path
{
path.prepend(relPath);
}
switch (mathJaxVersion)
{
case MATHJAX_VERSION_t::MathJax_3:
{
mathJaxJs += // "<script src=\"https://polyfill.io/v3/polyfill.min.js?features=es6\"></script>\n" // needed for IE11 only, see #10354
"<script type=\"text/javascript\">\n"
"window.MathJax = {\n"
" options: {\n"
" ignoreHtmlClass: 'tex2jax_ignore',\n"
" processHtmlClass: 'tex2jax_process'\n"
" }";
const StringVector &mathJaxExtensions = Config_getList(MATHJAX_EXTENSIONS);
if (!mathJaxExtensions.empty() || !g_latex_macro.isEmpty())
{
mathJaxJs+= ",\n";
if (!mathJaxExtensions.empty())
{
bool first = true;
mathJaxJs+= " loader: {\n"
" load: [";
for (const auto &s : mathJaxExtensions)
{
if (!first) mathJaxJs+= ",";
mathJaxJs+= "'[tex]/"+QCString(s.c_str())+"'";
first = false;
}
mathJaxJs+= "]\n"
" },\n";
}
mathJaxJs+= " tex: {\n"
" macros: {";
if (!g_latex_macro.isEmpty())
{
mathJaxJs += g_latex_macro+" ";
}
mathJaxJs+="},\n"
" packages: ['base','configmacros'";
if (!g_latex_macro.isEmpty())
{
mathJaxJs+= ",'newcommand'";
}
for (const auto &s : mathJaxExtensions)
{
mathJaxJs+= ",'"+QCString(s.c_str())+"'";
}
mathJaxJs += "]\n"
" }\n";
}
else
{
mathJaxJs += "\n";
}
mathJaxJs += "};\n";
// MATHJAX_CODEFILE
if (!g_mathjax_code.isEmpty())
{
mathJaxJs += g_mathjax_code;
mathJaxJs += "\n";
}
mathJaxJs += "</script>\n";
mathJaxJs += "<script type=\"text/javascript\" id=\"MathJax-script\" async=\"async\" src=\"" +
path + "es5/tex-" + mathJaxFormat.lower() + ".js\">";
mathJaxJs+="</script>\n";
}
break;
case MATHJAX_VERSION_t::MathJax_2:
{
mathJaxJs = "<script type=\"text/x-mathjax-config\">\n"
"MathJax.Hub.Config({\n"
" extensions: [\"tex2jax.js\"";
const StringVector &mathJaxExtensions = Config_getList(MATHJAX_EXTENSIONS);
for (const auto &s : mathJaxExtensions)
{
mathJaxJs+= ", \""+QCString(s.c_str())+".js\"";
}
if (mathJaxFormat.isEmpty())
{
mathJaxFormat = "HTML-CSS";
}
mathJaxJs += "],\n"
" jax: [\"input/TeX\",\"output/"+mathJaxFormat+"\"],\n";
if (!g_latex_macro.isEmpty())
{
mathJaxJs += " TeX: { Macros: {\n";
mathJaxJs += g_latex_macro;
mathJaxJs += "\n"
" } }\n";
}
mathJaxJs += "});\n";
if (!g_mathjax_code.isEmpty())
{
mathJaxJs += g_mathjax_code;
mathJaxJs += "\n";
}
mathJaxJs += "</script>\n";
mathJaxJs += "<script type=\"text/javascript\" async=\"async\" src=\"" + path + "MathJax.js\"></script>\n";
}
break;
}
}
QCString darkModeJs;
if (Config_getEnum(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::TOGGLE)
{
darkModeJs="<script type=\"text/javascript\" src=\"$relpath^darkmode_toggle.js\"></script>\n";
}
if (hasCookie) // extend the $treeview tag to avoid breaking old files used with HTML_HEADER
{
treeViewCssJs+="<script type=\"text/javascript\" src=\"$relpath^cookie.js\"></script>\n";
}
// first substitute generic keywords
QCString result = substituteKeywords(str,title,
convertToHtml(Config_getString(PROJECT_NAME)),
convertToHtml(Config_getString(PROJECT_NUMBER)),
convertToHtml(Config_getString(PROJECT_BRIEF)));
// then do the HTML specific keywords
result = substituteKeywords(result,
{
// keyword value getter
{ "$navpath", [&]() { return navPath; } },
{ "$stylesheet", [&]() { return cssFile; } },
{ "$treeview", [&]() { return treeViewCssJs; } },
{ "$searchbox", [&]() { return searchBox; } },
{ "$search", [&]() { return searchCssJs; } },
{ "$mathjax", [&]() { return mathJaxJs; } },
{ "$darkmode", [&]() { return darkModeJs; } },
{ "$generatedby", [&]() { return generatedBy; } },
{ "$extrastylesheet",[&]() { return extraCssText; } },
{ "$relpath$", [&]() { return relPath; } } //<-- obsolete: for backwards compatibility only
});
result = substitute(result,"$relpath^",relPath); //<-- must be done after the previous substitutions
// remove conditional blocks
result = selectBlocks(result,
{
// keyword, is enabled
{ "FULL_SIDEBAR", hasFullSideBar },
{ "DISABLE_INDEX", disableIndex },
{ "GENERATE_TREEVIEW", treeView },
{ "SEARCHENGINE", searchEngine },
{ "TITLEAREA", titleArea },
{ "PROJECT_NAME", hasProjectName },
{ "PROJECT_NUMBER", hasProjectNumber },
{ "PROJECT_BRIEF", hasProjectBrief },
{ "PROJECT_LOGO", hasProjectLogo },
{ "PROJECT_ICON", hasProjectIcon },
{ "COPY_CLIPBOARD", hasCopyClipboard },
},htmlMarkerInfo);
result = removeEmptyLines(result);
return result;
}
//---------------------------------------------------------------------------------------------
static StringUnorderedMap g_lightMap;
static StringUnorderedMap g_darkMap;
static void fillColorStyleMap(const QCString &definitions,StringUnorderedMap &map)
{
int p=0,i=0;
while ((i=definitions.find('\n',p))!=-1)
{
QCString line = definitions.mid(p,i-p);
if (line.startsWith("--"))
{
int separator = line.find(':');
assert(separator!=-1);
std::string key = line.left(separator).str();
int semi = line.findRev(';');
assert(semi!=-1);
std::string value = line.mid(separator+1,semi-separator-1).stripWhiteSpace().str();
map.emplace(key,value);
//printf("var(%s)=%s\n",qPrint(key),qPrint(value));
}
p=i+1;
}
}
static void fillColorStyleMaps()
{
ResourceMgr &mgr = ResourceMgr::instance();
auto colorStyle = Config_getEnum(HTML_COLORSTYLE);
if (colorStyle==HTML_COLORSTYLE_t::LIGHT)
{
fillColorStyleMap(replaceColorMarkers(mgr.getAsString("lightmode_settings.css")),g_lightMap);
}
else if (colorStyle==HTML_COLORSTYLE_t::DARK)
{
fillColorStyleMap(replaceColorMarkers(mgr.getAsString("darkmode_settings.css")),g_darkMap);
}
}
static QCString replaceVariables(const QCString &input)
{
auto doReplacements = [&input](const StringUnorderedMap &mapping) -> QCString
{
GrowBuf output;
int p=0,i=0;
while ((i=input.find("var(",p))!=-1)
{
output.addStr(input.data()+p,i-p);
int j=input.find(")",i+4);
assert(j!=-1);
auto it = mapping.find(input.mid(i+4,j-i-4).str()); // find variable
assert(it!=mapping.end()); // should be found
output.addStr(it->second); // add it value
//printf("replace '%s' by '%s'\n",qPrint(input.mid(i+4,j-i-4)),qPrint(it->second));
p=j+1;
}
output.addStr(input.data()+p,input.length()-p);
output.addChar(0);
return output.get();
};
auto colorStyle = Config_getEnum(HTML_COLORSTYLE);
if (colorStyle==HTML_COLORSTYLE_t::LIGHT)
{
return doReplacements(g_lightMap);
}
else if (colorStyle==HTML_COLORSTYLE_t::DARK)
{
return doReplacements(g_darkMap);
}
else
{
return input;
}
}
//----------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------
HtmlCodeGenerator::HtmlCodeGenerator(TextStream *t) : m_t(t)
{
//printf("%p:HtmlCodeGenerator()\n",(void*)this);
}
HtmlCodeGenerator::HtmlCodeGenerator(TextStream *t,const QCString &relPath)
: m_t(t), m_relPath(relPath)
{
//printf("%p:HtmlCodeGenerator()\n",(void*)this);
}
void HtmlCodeGenerator::setRelativePath(const QCString &path)
{
m_relPath = path;
}
void HtmlCodeGenerator::codify(const QCString &str)
{
if (!str.isEmpty())
{
int tabSize = Config_getInt(TAB_SIZE);
const char *p=str.data();
if (m_hide) // only update column count
{
m_col = updateColumnCount(p,m_col);
}
else // actually output content and keep track of m_col
{
while (*p)
{
char c=*p++;
switch(c)
{
case '\t': {
int spacesToNextTabStop = tabSize - (m_col%tabSize);
while (spacesToNextTabStop--)
{
if (m_col>=m_stripIndentAmount) *m_t << " ";
m_col++;
}
}
break;
case ' ': if (m_col>=m_stripIndentAmount) *m_t << " ";
m_col++;
break;
case '\n': *m_t << "\n"; m_col=0;
break;
case '\r': break;
case '<': *m_t << "<"; m_col++;
break;
case '>': *m_t << ">"; m_col++;
break;
case '&': *m_t << "&"; m_col++;
break;
case '\'': *m_t << "'"; m_col++; // ' is not valid XHTML
break;
case '"': *m_t << """; m_col++;
break;
case '\\':
if (*p=='<')
{ *m_t << "<"; p++; }
else if (*p=='>')
{ *m_t << ">"; p++; }
else if (*p=='(')
{ *m_t << "\\‍("; m_col++;p++; }
else if (*p==')')
{ *m_t << "\\‍)"; m_col++;p++; }
else
*m_t << "\\";
m_col++;
break;
default:
{
uint8_t uc = static_cast<uint8_t>(c);
if (uc<32)
{
*m_t << "$" << hex[uc>>4] << hex[uc&0xF] << ";";
m_col++;
}
else if (uc<0x80) // printable ASCII char
{
*m_t << c;
m_col++;
}
else // multibyte UTF-8 char
{
p=writeUTF8Char(*m_t,p-1);
m_col++;
}
}
break;
}
}
}
}
}
void HtmlCodeGenerator::stripCodeComments(bool b)
{
m_stripCodeComments = b;
}
void HtmlCodeGenerator::startSpecialComment()
{
m_hide = m_stripCodeComments;
//*m_t << "[START]";
}
void HtmlCodeGenerator::endSpecialComment()
{
//*m_t << "[END]";
m_hide = false;
}
void HtmlCodeGenerator::setStripIndentAmount(size_t amount)
{
m_stripIndentAmount = amount;
}
void HtmlCodeGenerator::writeLineNumber(const QCString &ref,const QCString &filename,
const QCString &anchor,int l,bool writeLineAnchor)
{
m_lastLineInfo = LineInfo(ref,filename,anchor,l,writeLineAnchor);
if (m_hide) return;
const int maxLineNrStr = 10;
char lineNumber[maxLineNrStr];
char lineAnchor[maxLineNrStr];
qsnprintf(lineNumber,maxLineNrStr,"%5d",l);
qsnprintf(lineAnchor,maxLineNrStr,"l%05d",l);
if (!m_lineOpen)
{
*m_t << "<div class=\"line\">";
m_lineOpen = TRUE;
}
if (writeLineAnchor) *m_t << "<a id=\"" << lineAnchor << "\" name=\"" << lineAnchor << "\"></a>";
*m_t << "<span class=\"lineno\">";
if (!filename.isEmpty())
{
_writeCodeLink("line",ref,filename,anchor,lineNumber,QCString());
}
else
{
codify(lineNumber);
}
*m_t << "</span>";
m_col=0;
}
void HtmlCodeGenerator::writeCodeLink(CodeSymbolType type,
const QCString &ref,const QCString &f,
const QCString &anchor, const QCString &name,
const QCString &tooltip)
{
if (m_hide) return;
const char *hl = codeSymbolType2Str(type);
QCString hlClass = "code";
if (hl)
{
hlClass+=" hl_";
hlClass+=hl;
}
_writeCodeLink(hlClass,ref,f,anchor,name,tooltip);
}
void HtmlCodeGenerator::_writeCodeLink(const QCString &className,
const QCString &ref,const QCString &f,
const QCString &anchor, const QCString &name,
const QCString &tooltip)
{
m_col+=name.length();
if (m_hide) return;
if (!ref.isEmpty())
{
*m_t << "<a class=\"" << className << "Ref\" ";
*m_t << externalLinkTarget();
}
else
{
*m_t << "<a class=\"" << className << "\" ";
}
*m_t << "href=\"";
QCString fn = f;
addHtmlExtensionIfMissing(fn);
*m_t << createHtmlUrl(m_relPath,ref,true,
fileName()==fn,fn,anchor);
*m_t << "\"";
if (!tooltip.isEmpty()) *m_t << " title=\"" << convertToHtml(tooltip) << "\"";
*m_t << ">";
codify(name);
*m_t << "</a>";
}
void HtmlCodeGenerator::writeTooltip(const QCString &id, const DocLinkInfo &docInfo,
const QCString &decl, const QCString &desc,
const SourceLinkInfo &defInfo,
const SourceLinkInfo &declInfo)
{
if (m_hide) return;
*m_t << "<div class=\"ttc\" id=\"" << id << "\">";
*m_t << "<div class=\"ttname\">";
if (!docInfo.url.isEmpty())
{
*m_t << "<a href=\"";
QCString fn = docInfo.url;
addHtmlExtensionIfMissing(fn);
*m_t << createHtmlUrl(m_relPath,docInfo.ref,true,
fileName()==fn,fn,docInfo.anchor);
*m_t << "\">";
}
codify(docInfo.name);
if (!docInfo.url.isEmpty())
{
*m_t << "</a>";
}
*m_t << "</div>";
if (!decl.isEmpty())
{
*m_t << "<div class=\"ttdeci\">";
codify(decl);
*m_t << "</div>";
}
if (!desc.isEmpty())
{
*m_t << "<div class=\"ttdoc\">";
codify(desc);
*m_t << "</div>";
}
if (!defInfo.file.isEmpty())
{
*m_t << "<div class=\"ttdef\"><b>" << theTranslator->trDefinition() << "</b> ";
if (!defInfo.url.isEmpty())
{
*m_t << "<a href=\"";
QCString fn = defInfo.url;
addHtmlExtensionIfMissing(fn);
*m_t << createHtmlUrl(m_relPath,defInfo.ref,true,
fileName()==fn,fn,defInfo.anchor);
*m_t << "\">";
}
*m_t << defInfo.file << ":" << defInfo.line;
if (!defInfo.url.isEmpty())
{
*m_t << "</a>";
}
*m_t << "</div>";
}
if (!declInfo.file.isEmpty())
{
*m_t << "<div class=\"ttdecl\"><b>" << theTranslator->trDeclaration() << "</b> ";
if (!declInfo.url.isEmpty())
{
*m_t << "<a href=\"";
QCString fn = declInfo.url;
addHtmlExtensionIfMissing(fn);
*m_t << createHtmlUrl(m_relPath,declInfo.ref,true,
fileName()==fn,fn,declInfo.anchor);
*m_t << "\">";
}
*m_t << declInfo.file << ":" << declInfo.line;
if (!declInfo.url.isEmpty())
{
*m_t << "</a>";
}
*m_t << "</div>";
}
*m_t << "</div>\n";
}
void HtmlCodeGenerator::startCodeLine(int)
{
m_col=0;
if (m_hide) return;
if (!m_lineOpen)
{
*m_t << "<div class=\"line\">";
m_lineOpen = TRUE;
}
}
void HtmlCodeGenerator::endCodeLine()
{
if (m_hide) return;
if (m_col == 0)
{
*m_t << " ";
m_col++;
}
if (m_lineOpen)
{
*m_t << "</div>\n";
m_lineOpen = FALSE;
}
}
void HtmlCodeGenerator::startFontClass(const QCString &s)
{
if (m_hide) return;
*m_t << "<span class=\"" << s << "\">";
}
void HtmlCodeGenerator::endFontClass()
{
if (m_hide) return;
*m_t << "</span>";
}
void HtmlCodeGenerator::writeCodeAnchor(const QCString &anchor)
{
if (m_hide) return;
*m_t << "<a id=\"" << anchor << "\" name=\"" << anchor << "\"></a>";
}
void HtmlCodeGenerator::startCodeFragment(const QCString &)
{
*m_t << "<div class=\"fragment\">";
}
void HtmlCodeGenerator::endCodeFragment(const QCString &)
{
//endCodeLine checks is there is still an open code line, if so closes it.
endCodeLine();
*m_t << "</div><!-- fragment -->";
}
void HtmlCodeGenerator::startFold(int lineNr,const QCString &startMarker,const QCString &endMarker)
{
if (m_lineOpen) // if we have a hidden comment in a code fold, we need to end the line
{
*m_t << "</div>\n";
}
const int maxLineNrStr = 10;
char lineNumber[maxLineNrStr];
qsnprintf(lineNumber,maxLineNrStr,"%05d",lineNr);
*m_t << "<div class=\"foldopen\" id=\"foldopen" << lineNumber <<
"\" data-start=\"" << startMarker <<
"\" data-end=\"" << endMarker <<
"\">\n";
if (m_lineOpen) // if we have a hidden comment in a code fold, we need to restart the line
{
*m_t << "<div class=\"line\">";
}
m_hide=false;
}
void HtmlCodeGenerator::_startOpenLine()
{
*m_t << "<div class=\"line\">";
bool wasHidden=m_hide;
m_hide = false;
m_lineOpen = true;
writeLineNumber(m_lastLineInfo.ref,
m_lastLineInfo.fileName,
m_lastLineInfo.anchor,
m_lastLineInfo.line+1,
m_lastLineInfo.writeAnchor);
m_hide = wasHidden;
}
void HtmlCodeGenerator::endFold()
{
if (m_lineOpen) // if we have a hidden comment in a code fold, we need to end the line
{
*m_t << "</div>\n";
}
*m_t << "</div>\n";
if (m_lineOpen)
{
_startOpenLine();
}
}
//--------------------------------------------------------------------------
HtmlGenerator::HtmlGenerator()
: OutputGenerator(Config_getString(HTML_OUTPUT))
, m_codeList(std::make_unique<OutputCodeList>())
{
//printf("%p:HtmlGenerator()\n",(void*)this);
m_codeGen = m_codeList->add<HtmlCodeGenerator>(&m_t);
}
HtmlGenerator::HtmlGenerator(const HtmlGenerator &og) : OutputGenerator(og.m_dir), OutputGenIntf()
{
//printf("%p:HtmlGenerator(copy %p)\n",(void*)this,(void*)&og);
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<HtmlCodeGenerator>(OutputType::Html);
m_codeGen->setTextStream(&m_t);
m_lastTitle = og.m_lastTitle;
m_lastFile = og.m_lastFile;
m_relPath = og.m_relPath;
m_sectionCount = og.m_sectionCount;
m_emptySection = og.m_emptySection;
}
HtmlGenerator &HtmlGenerator::operator=(const HtmlGenerator &og)
{
//printf("%p:HtmlGenerator(copy assign %p)\n",(void*)this,(void*)&og);
if (this!=&og)
{
m_dir = og.m_dir;
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<HtmlCodeGenerator>(OutputType::Html);
m_codeGen->setTextStream(&m_t);
m_lastTitle = og.m_lastTitle;
m_lastFile = og.m_lastFile;
m_relPath = og.m_relPath;
m_sectionCount = og.m_sectionCount;
m_emptySection = og.m_emptySection;
}
return *this;
}
HtmlGenerator::~HtmlGenerator() = default;
void HtmlGenerator::addCodeGen(OutputCodeList &list)
{
list.add<HtmlCodeGeneratorDefer>(m_codeGen);
}
void HtmlGenerator::init()
{
QCString dname = Config_getString(HTML_OUTPUT);
Dir d(dname.str());
if (!d.exists() && !d.mkdir(dname.str()))
{
term("Could not create output directory %s\n",qPrint(dname));
}
//writeLogo(dname);
if (!Config_getString(HTML_HEADER).isEmpty())
{
g_header=fileToString(Config_getString(HTML_HEADER));
//printf("g_header='%s'\n",qPrint(g_header));
QCString result = substituteHtmlKeywords(g_header,QCString(),QCString());
checkBlocks(result,Config_getString(HTML_HEADER),htmlMarkerInfo);
}
else
{
g_header = ResourceMgr::instance().getAsString("header.html");
QCString result = substituteHtmlKeywords(g_header,QCString(),QCString());
checkBlocks(result,"<default header.html>",htmlMarkerInfo);
}
if (!Config_getString(HTML_FOOTER).isEmpty())
{
g_footer=fileToString(Config_getString(HTML_FOOTER));
//printf("g_footer='%s'\n",qPrint(g_footer));
QCString result = substituteHtmlKeywords(g_footer,QCString(),QCString());
checkBlocks(result,Config_getString(HTML_FOOTER),htmlMarkerInfo);
}
else
{
g_footer = ResourceMgr::instance().getAsString("footer.html");
QCString result = substituteHtmlKeywords(g_footer,QCString(),QCString());
checkBlocks(result,"<default footer.html>",htmlMarkerInfo);
}
if (Config_getBool(USE_MATHJAX))
{
if (!Config_getString(MATHJAX_CODEFILE).isEmpty())
{
g_mathjax_code=fileToString(Config_getString(MATHJAX_CODEFILE));
//printf("g_mathjax_code='%s'\n",qPrint(g_mathjax_code));
}
g_latex_macro=getConvertLatexMacro();
//printf("converted g_latex_macro='%s'\n",qPrint(g_latex_macro));
}
createSubDirs(d);
fillColorStyleMaps();
ResourceMgr &mgr = ResourceMgr::instance();
{
QCString tabsCss;
if (Config_getBool(HTML_DYNAMIC_MENUS))
{
tabsCss = mgr.getAsString("tabs.css");
}
else // stylesheet for the 'old' static tabs
{
tabsCss = mgr.getAsString("fixed_tabs.css");
}
std::ofstream f = Portable::openOutputStream(dname+"/tabs.css");
if (f.is_open())
{
TextStream t(&f);
t << replaceVariables(tabsCss);
}
}
mgr.copyResource("jquery.js",dname);
if (Config_getBool(INTERACTIVE_SVG))
{
mgr.copyResource("svg.min.js",dname);
}
if (!Config_getBool(DISABLE_INDEX) && Config_getBool(HTML_DYNAMIC_MENUS))
{
mgr.copyResource("menu.js",dname);
}
// copy navtree.css
{
std::ofstream f = Portable::openOutputStream(dname+"/navtree.css");
if (f.is_open())
{
TextStream t(&f);
t << getNavTreeCss();
}
}
// copy resize.js
{
std::ofstream f = Portable::openOutputStream(dname+"/resize.js");
if (f.is_open())
{
TextStream t(&f);
t << substitute(
substitute(mgr.getAsString("resize.js"),
"$TREEVIEW_WIDTH", QCString().setNum(Config_getInt(TREEVIEW_WIDTH))),
"$PROJECTID", getProjectId());
}
}
if (Config_getBool(HTML_COPY_CLIPBOARD))
{
std::ofstream f = Portable::openOutputStream(dname+"/clipboard.js");
if (f.is_open())
{
TextStream t(&f);
t << substitute(mgr.getAsString("clipboard.js"),"$copy_to_clipboard_text",theTranslator->trCopyToClipboard());
}
}
bool hasCookie = Config_getBool(GENERATE_TREEVIEW) || Config_getBool(SEARCHENGINE) || Config_getEnum(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::TOGGLE;
if (hasCookie)
{
mgr.copyResource("cookie.js",dname);
}
if (Config_getBool(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::TOGGLE)
{
std::ofstream f = Portable::openOutputStream(dname+"/darkmode_toggle.js");
if (f.is_open())
{
TextStream t(&f);
t << substitute(replaceColorMarkers(mgr.getAsString("darkmode_toggle.js")),
"$PROJECTID",getProjectId());
}
}
{
std::ofstream f = Portable::openOutputStream(dname+"/dynsections.js");
if (f.is_open())
{
TextStream t(&f);
t << replaceVariables(mgr.getAsString("dynsections.js"));
if (Config_getBool(SOURCE_BROWSER) && Config_getBool(SOURCE_TOOLTIPS))
{
t << replaceVariables(mgr.getAsString("dynsections_tooltips.js"));
}
}
}
}
void HtmlGenerator::cleanup()
{
QCString dname = Config_getString(HTML_OUTPUT);
Dir d(dname.str());
clearSubDirs(d);
}
/// Additional initialization after indices have been created
void HtmlGenerator::writeTabData()
{
Doxygen::indexList->addStyleSheetFile("tabs.css");
QCString dname=Config_getString(HTML_OUTPUT);
ResourceMgr &mgr = ResourceMgr::instance();
//writeColoredImgData(dname,colored_tab_data);
mgr.copyResource("tab_a.lum",dname); // active, light mode
mgr.copyResource("tab_b.lum",dname); // normal, light mode
mgr.copyResource("tab_h.lum",dname); // highlight, light mode
mgr.copyResource("tab_s.lum",dname); // separator, light mode
mgr.copyResource("tab_ad.lum",dname); // active, dark mode
mgr.copyResource("tab_bd.lum",dname); // normal, dark mode
mgr.copyResource("tab_hd.lum",dname); // highlight, dark mode
mgr.copyResource("tab_sd.lum",dname); // separator, light mode
mgr.copyResource("nav_h.lum",dname); // header gradient, light mode
mgr.copyResource("nav_hd.lum",dname); // header gradient, dark mode
mgr.copyResource("nav_f.lum",dname); // member definition header, light mode
mgr.copyResource("nav_fd.lum",dname); // member definition header, dark mode
mgr.copyResource("bc_s.luma",dname); // breadcrumb separator, light mode
mgr.copyResource("bc_sd.luma",dname); // breadcrumb separator, dark mode
mgr.copyResource("doxygen.svg",dname);
Doxygen::indexList->addImageFile("doxygen.svg");
mgr.copyResource("closed.luma",dname);
mgr.copyResource("open.luma",dname);
mgr.copyResource("sync_on.luma",dname);
mgr.copyResource("sync_off.luma",dname);
mgr.copyResource("nav_g.png",dname);
Doxygen::indexList->addImageFile("nav_g.png");
mgr.copyResource("plus.svg",dname);
Doxygen::indexList->addImageFile("plus.svg");
mgr.copyResource("minus.svg",dname);
Doxygen::indexList->addImageFile("minus.svg");
mgr.copyResource("plusd.svg",dname);
Doxygen::indexList->addImageFile("plusd.svg");
mgr.copyResource("minusd.svg",dname);
Doxygen::indexList->addImageFile("minusd.svg");
}
void HtmlGenerator::writeSearchData(const QCString &dname)
{
//bool serverBasedSearch = Config_getBool(SERVER_BASED_SEARCH);
//writeImgData(dname,serverBasedSearch ? search_server_data : search_client_data);
ResourceMgr &mgr = ResourceMgr::instance();
// server side search resources
mgr.copyResource("mag.svg",dname);
mgr.copyResource("mag_d.svg",dname);
Doxygen::indexList->addImageFile("search/mag.svg");
Doxygen::indexList->addImageFile("search/mag_d.svg");
// client side search resources
mgr.copyResource("close.svg",dname);
Doxygen::indexList->addImageFile("search/close.svg");
mgr.copyResource("mag_sel.svg",dname);
mgr.copyResource("mag_seld.svg",dname);
Doxygen::indexList->addImageFile("search/mag_sel.svg");
Doxygen::indexList->addImageFile("search/mag_seld.svg");
QCString searchDirName = dname;
std::ofstream f = Portable::openOutputStream(searchDirName+"/search.css");
if (f.is_open())
{
TextStream t(&f);
QCString searchCss;
// the position of the search box depends on a number of settings.
// Insert the right piece of CSS code depending on which options are selected
if (Config_getBool(DISABLE_INDEX))
{
if (Config_getBool(GENERATE_TREEVIEW) && Config_getBool(FULL_SIDEBAR))
{
searchCss = mgr.getAsString("search_sidebar.css"); // we have a full height side bar
}
else if (Config_getBool(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::TOGGLE)
{
searchCss = mgr.getAsString("search_nomenu_toggle.css"); // we have no tabs but do have a darkmode button
}
else
{
searchCss = mgr.getAsString("search_nomenu.css"); // we have no tabs and no darkmode button
}
}
else if (!Config_getBool(HTML_DYNAMIC_MENUS))
{
searchCss = mgr.getAsString("search_fixedtabs.css"); // we have tabs, but they are static
}
else
{
searchCss = mgr.getAsString("search.css"); // default case with a dynamic menu bar
}
// and then add the option independent part of the styling
searchCss += mgr.getAsString("search_common.css");
searchCss = substitute(searchCss,"$doxygenversion",getDoxygenVersion());
t << replaceVariables(searchCss);
Doxygen::indexList->addStyleSheetFile("search/search.css");
}
}
static void writeDefaultStyleSheet(TextStream &t)
{
t << "/* The standard CSS for doxygen " << getDoxygenVersion() << "*/\n\n";
switch (Config_getEnum(HTML_COLORSTYLE))
{
case HTML_COLORSTYLE_t::LIGHT:
case HTML_COLORSTYLE_t::DARK:
/* variables will be resolved while writing to the CSS file */
break;
case HTML_COLORSTYLE_t::AUTO_LIGHT:
case HTML_COLORSTYLE_t::TOGGLE:
t << "html {\n";
t << replaceColorMarkers(ResourceMgr::instance().getAsString("lightmode_settings.css"));
t << "}\n\n";
break;
case HTML_COLORSTYLE_t::AUTO_DARK:
t << "html {\n";
t << replaceColorMarkers(ResourceMgr::instance().getAsString("darkmode_settings.css"));
t << "}\n\n";
break;
}
if (Config_getEnum(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::AUTO_LIGHT)
{
t << "@media (prefers-color-scheme: dark) {\n";
t << " html:not(.dark-mode) {\n";
t << " color-scheme: dark;\n\n";
t << replaceColorMarkers(ResourceMgr::instance().getAsString("darkmode_settings.css"));
t << "}}\n";
}
else if (Config_getEnum(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::AUTO_DARK)
{
t << "@media (prefers-color-scheme: light) {\n";
t << " html:not(.light-mode) {\n";
t << " color-scheme: light;\n\n";
t << replaceColorMarkers(ResourceMgr::instance().getAsString("lightmode_settings.css"));
t << "}}\n";
}
else if (Config_getEnum(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::TOGGLE)
{
t << "html.dark-mode {\n";
t << replaceColorMarkers(ResourceMgr::instance().getAsString("darkmode_settings.css"));
t << "}\n\n";
}
t << replaceVariables(ResourceMgr::instance().getAsString("doxygen.css"));
// For Webkit based the scrollbar styling cannot be overruled (bug in chromium?).
// To allow the user to style the scrollbars differently we should only add it in case
// the user did not specify any extra stylesheets.
bool addScrollbarStyling = Config_getList(HTML_EXTRA_STYLESHEET).empty();
if (addScrollbarStyling)
{
t << replaceVariables(ResourceMgr::instance().getAsString("scrollbar.css"));
}
}
void HtmlGenerator::writeStyleSheetFile(TextStream &t)
{
fillColorStyleMaps();
writeDefaultStyleSheet(t);
}
void HtmlGenerator::writeHeaderFile(TextStream &t, const QCString & /*cssname*/)
{
t << "<!-- HTML header for doxygen " << getDoxygenVersion() << "-->\n";
t << ResourceMgr::instance().getAsString("header.html");
}
void HtmlGenerator::writeFooterFile(TextStream &t)
{
t << "<!-- HTML footer for doxygen " << getDoxygenVersion() << "-->\n";
t << ResourceMgr::instance().getAsString("footer.html");
}
static std::mutex g_indexLock;
void HtmlGenerator::startFile(const QCString &name,const QCString &,
const QCString &title,int /*id*/, int /*hierarchyLevel*/)
{
//printf("HtmlGenerator::startFile(%s)\n",qPrint(name));
m_relPath = relativePathToRoot(name);
QCString fileName = name;
addHtmlExtensionIfMissing(fileName);
m_lastTitle=title;
startPlainFile(fileName);
m_codeGen->setFileName(fileName);
m_codeGen->setRelativePath(m_relPath);
{
std::lock_guard<std::mutex> lock(g_indexLock);
Doxygen::indexList->addIndexFile(fileName);
}
m_lastFile = fileName;
m_t << substituteHtmlKeywords(g_header,convertToHtml(filterTitle(title)),m_relPath);
m_t << "<!-- " << theTranslator->trGeneratedBy() << " Doxygen "
<< getDoxygenVersion() << " -->\n";
bool searchEngine = Config_getBool(SEARCHENGINE);
if (searchEngine /*&& !generateTreeView*/)
{
m_t << "<script type=\"text/javascript\">\n";
m_t << "/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n";
m_t << "var searchBox = new SearchBox(\"searchBox\", \""
<< m_relPath<< "search/\",'" << Doxygen::htmlFileExtension << "');\n";
m_t << "/* @license-end */\n";
m_t << "</script>\n";
}
if (Config_getBool(HTML_CODE_FOLDING))
{
m_t << "<script type=\"text/javascript\">\n";
m_t << "/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n";
m_t << "$(function() { codefold.init(" << (m_relPath.isEmpty() ? "0" : "1") << "); });\n";
m_t << "/* @license-end */\n";
m_t << "</script>\n";
}
m_sectionCount=0;
}
void HtmlGenerator::writeSearchInfoStatic(TextStream &t,const QCString &)
{
bool searchEngine = Config_getBool(SEARCHENGINE);
bool serverBasedSearch = Config_getBool(SERVER_BASED_SEARCH);
if (searchEngine && !serverBasedSearch)
{
t << "<!-- window showing the filter options -->\n";
t << "<div id=\"MSearchSelectWindow\"\n";
t << " onmouseover=\"return searchBox.OnSearchSelectShow()\"\n";
t << " onmouseout=\"return searchBox.OnSearchSelectHide()\"\n";
t << " onkeydown=\"return searchBox.OnSearchSelectKey(event)\">\n";
t << "</div>\n";
t << "\n";
t << "<!-- iframe showing the search results (closed by default) -->\n";
t << "<div id=\"MSearchResultsWindow\">\n";
t << "<div id=\"MSearchResults\">\n";
t << "<div class=\"SRPage\">\n";
t << "<div id=\"SRIndex\">\n";
t << "<div id=\"SRResults\"></div>\n"; // here the results will be inserted
t << "<div class=\"SRStatus\" id=\"Loading\">" << theTranslator->trLoading() << "</div>\n";
t << "<div class=\"SRStatus\" id=\"Searching\">" << theTranslator->trSearching() << "</div>\n";
t << "<div class=\"SRStatus\" id=\"NoMatches\">" << theTranslator->trNoMatches() << "</div>\n";
t << "</div>\n"; // SRIndex
t << "</div>\n"; // SRPage
t << "</div>\n"; // MSearchResults
t << "</div>\n"; // MSearchResultsWindow
t << "\n";
}
}
void HtmlGenerator::writeSearchInfo()
{
writeSearchInfoStatic(m_t,m_relPath);
}
QCString HtmlGenerator::writeLogoAsString(const QCString &path)
{
QCString result;
switch (Config_getEnum(TIMESTAMP))
{
case TIMESTAMP_t::YES:
case TIMESTAMP_t::DATETIME:
result += theTranslator->trGeneratedAt(
dateToString(DateTimeType::DateTime),
Config_getString(PROJECT_NAME)
);
break;
case TIMESTAMP_t::DATE:
result += theTranslator->trGeneratedAt(
dateToString(DateTimeType::Date),
Config_getString(PROJECT_NAME)
);
break;
case TIMESTAMP_t::NO:
result += theTranslator->trGeneratedBy();
break;
}
result += " \n<a href=\"https://www.doxygen.org/index.html\">\n"
"<img class=\"footer\" src=\"";
result += path;
result += "doxygen.svg\" width=\"104\" height=\"31\" alt=\"doxygen\"/></a> ";
result += getDoxygenVersion();
result += " ";
return result;
}
void HtmlGenerator::writeLogo()
{
m_t << writeLogoAsString(m_relPath);
}
void HtmlGenerator::writePageFooter(TextStream &t,const QCString &lastTitle,
const QCString &relPath,const QCString &navPath)
{
t << substituteHtmlKeywords(g_footer,convertToHtml(lastTitle),relPath,navPath);
}
void HtmlGenerator::writeFooter(const QCString &navPath)
{
writePageFooter(m_t,m_lastTitle,m_relPath,navPath);
}
void HtmlGenerator::endFile()
{
endPlainFile();
}
void HtmlGenerator::startProjectNumber()
{
m_t << "<h3 class=\"version\">";
}
void HtmlGenerator::endProjectNumber()
{
m_t << "</h3>";
}
void HtmlGenerator::writeStyleInfo(int part)
{
//printf("writeStyleInfo(%d)\n",part);
if (part==0)
{
if (Config_getString(HTML_STYLESHEET).isEmpty()) // write default style sheet
{
//printf("write doxygen.css\n");
startPlainFile("doxygen.css");
writeDefaultStyleSheet(m_t);
endPlainFile();
Doxygen::indexList->addStyleSheetFile("doxygen.css");
}
else // write user defined style sheet
{
QCString cssName=Config_getString(HTML_STYLESHEET);
if (!cssName.startsWith("http:") && !cssName.startsWith("https:"))
{
FileInfo cssfi(cssName.str());
if (!cssfi.exists() || !cssfi.isFile() || !cssfi.isReadable())
{
err("style sheet %s does not exist or is not readable!\n", qPrint(Config_getString(HTML_STYLESHEET)));
}
else
{
// convert style sheet to string
QCString fileStr = fileToString(cssName);
// write the string into the output dir
startPlainFile(cssfi.fileName().c_str());
m_t << fileStr;
endPlainFile();
}
Doxygen::indexList->addStyleSheetFile(cssfi.fileName().c_str());
}
}
const StringVector &extraCssFiles = Config_getList(HTML_EXTRA_STYLESHEET);
for (const auto &fileName : extraCssFiles)
{
if (!fileName.empty())
{
FileInfo fi(fileName);
if (fi.exists())
{
Doxygen::indexList->addStyleSheetFile(fi.fileName().c_str());
}
}
}
Doxygen::indexList->addStyleSheetFile("jquery.js");
Doxygen::indexList->addStyleSheetFile("resize.js");
Doxygen::indexList->addStyleSheetFile("navtree.css");
Doxygen::indexList->addStyleSheetFile("dynsections.js");
if (Config_getEnum(HTML_COLORSTYLE)==HTML_COLORSTYLE_t::TOGGLE)
{
Doxygen::indexList->addStyleSheetFile("darkmode_toggle.js");
}
if (Config_getBool(INTERACTIVE_SVG))
{
Doxygen::indexList->addStyleSheetFile("svg.min.js");
}
if (!Config_getBool(DISABLE_INDEX) && Config_getBool(HTML_DYNAMIC_MENUS))
{
Doxygen::indexList->addStyleSheetFile("menu.js");
Doxygen::indexList->addStyleSheetFile("menudata.js");
}
}
}
void HtmlGenerator::startDoxyAnchor(const QCString &,const QCString &,
const QCString &anchor, const QCString &,
const QCString &)
{
m_t << "<a id=\"" << anchor << "\" name=\"" << anchor << "\"></a>";
}
void HtmlGenerator::endDoxyAnchor(const QCString &,const QCString &)
{
}
void HtmlGenerator::addLabel(const QCString &,const QCString &)
{
}
void HtmlGenerator::startParagraph(const QCString &classDef)
{
if (!classDef.isEmpty())
m_t << "\n<p class=\"" << classDef << "\">";
else
m_t << "\n<p>";
}
void HtmlGenerator::endParagraph()
{
m_t << "</p>\n";
}
void HtmlGenerator::writeString(const QCString &text)
{
m_t << text;
}
void HtmlGenerator::startIndexListItem()
{
m_t << "<li>";
}
void HtmlGenerator::endIndexListItem()
{
m_t << "</li>\n";
}
void HtmlGenerator::startIndexItem(const QCString &ref,const QCString &f)
{
//printf("HtmlGenerator::startIndexItem(%s,%s)\n",ref,f);
if (!ref.isEmpty() || !f.isEmpty())
{
if (!ref.isEmpty())
{
m_t << "<a class=\"elRef\" ";
m_t << externalLinkTarget();
}
else
{
m_t << "<a class=\"el\" ";
}
m_t << "href=\"";
m_t << externalRef(m_relPath,ref,TRUE);
if (!f.isEmpty())
{
QCString fn=f;
addHtmlExtensionIfMissing(fn);
m_t << fn;
}
m_t << "\">";
}
else
{
m_t << "<b>";
}
}
void HtmlGenerator::endIndexItem(const QCString &ref,const QCString &f)
{
//printf("HtmlGenerator::endIndexItem(%s,%s,%s)\n",ref,f,name);
if (!ref.isEmpty() || !f.isEmpty())
{
m_t << "</a>";
}
else
{
m_t << "</b>";
}
}
void HtmlGenerator::writeStartAnnoItem(const QCString &,const QCString &f,
const QCString &path,const QCString &name)
{
m_t << "<li>";
if (!path.isEmpty()) docify(path);
QCString fn = f;
addHtmlExtensionIfMissing(fn);
m_t << "<a class=\"el\" href=\"" << fn << "\">";
docify(name);
m_t << "</a> ";
}
void HtmlGenerator::writeObjectLink(const QCString &ref,const QCString &f,
const QCString &anchor, const QCString &name)
{
if (!ref.isEmpty())
{
m_t << "<a class=\"elRef\" ";
m_t << externalLinkTarget();
}
else
{
m_t << "<a class=\"el\" ";
}
m_t << "href=\"";
QCString fn = f;
addHtmlExtensionIfMissing(fn);
m_t << createHtmlUrl(m_relPath,ref,true,
fileName() == Config_getString(HTML_OUTPUT)+"/"+fn,
fn,
anchor);
m_t << "\">";
docify(name);
m_t << "</a>";
}
void HtmlGenerator::startTextLink(const QCString &f,const QCString &anchor)
{
m_t << "<a href=\"";
QCString fn = f;
addHtmlExtensionIfMissing(fn);
m_t << createHtmlUrl(m_relPath,"",true,
fileName() == Config_getString(HTML_OUTPUT)+"/"+fn,
fn,
anchor);
m_t << "\">";
}
void HtmlGenerator::endTextLink()
{
m_t << "</a>";
}
void HtmlGenerator::startGroupHeader(int extraIndentLevel)
{
if (extraIndentLevel==2)
{
m_t << "<h4 class=\"groupheader\">";
}
else if (extraIndentLevel==1)
{
m_t << "<h3 class=\"groupheader\">";
}
else // extraIndentLevel==0
{
m_t << "<h2 class=\"groupheader\">";
}
}
void HtmlGenerator::endGroupHeader(int extraIndentLevel)
{
if (extraIndentLevel==2)
{
m_t << "</h4>\n";
}
else if (extraIndentLevel==1)
{
m_t << "</h3>\n";
}
else
{
m_t << "</h2>\n";
}
}
void HtmlGenerator::startSection(const QCString &lab,const QCString &,SectionType type)
{
switch(type.level())
{
case SectionType::Page: m_t << "\n\n<h1>"; break;
case SectionType::Section: m_t << "\n\n<h2>"; break;
case SectionType::Subsection: m_t << "\n\n<h3>"; break;
case SectionType::Subsubsection: m_t << "\n\n<h4>"; break;
case SectionType::Paragraph: m_t << "\n\n<h5>"; break;
case SectionType::Subparagraph: m_t << "\n\n<h6>"; break;
case SectionType::Subsubparagraph: m_t << "\n\n<h6>"; break;
default: ASSERT(0); break;
}
m_t << "<a id=\"" << lab << "\" name=\"" << lab << "\"></a>";
}
void HtmlGenerator::endSection(const QCString &,SectionType type)
{
switch(type.level())
{
case SectionType::Page: m_t << "</h1>"; break;
case SectionType::Section: m_t << "</h2>"; break;
case SectionType::Subsection: m_t << "</h3>"; break;
case SectionType::Subsubsection: m_t << "</h4>"; break;
case SectionType::Paragraph: m_t << "</h5>"; break;
case SectionType::Subparagraph: m_t << "</h6>"; break;
case SectionType::Subsubparagraph: m_t << "</h6>"; break;
default: ASSERT(0); break;
}
}
void HtmlGenerator::docify(const QCString &str)
{
docify_(str,FALSE);
}
void HtmlGenerator::docify_(const QCString &str,bool inHtmlComment)
{
if (!str.isEmpty())
{
const char *p=str.data();
while (*p)
{
char c=*p++;
switch(c)
{
case '<': m_t << "<"; break;
case '>': m_t << ">"; break;
case '&': m_t << "&"; break;
case '"': m_t << """; break;
case '-': if (inHtmlComment) m_t << "-"; else m_t << "-"; break;
case '\\':
if (*p=='<')
{ m_t << "<"; p++; }
else if (*p=='>')
{ m_t << ">"; p++; }
else if (*p=='(')
{ m_t << "\\‍("; p++; }
else if (*p==')')
{ m_t << "\\‍)"; p++; }
else
m_t << "\\";
break;
default: m_t << c;
}
}
}
}
void HtmlGenerator::writeChar(char c)
{
char cs[2];
cs[0]=c;
cs[1]=0;
docify(cs);
}
//--- helper function for dynamic sections -------------------------
static void startSectionHeader(TextStream &t,
const QCString &relPath,int sectionCount)
{
//t << "<!-- startSectionHeader -->";
bool dynamicSections = Config_getBool(HTML_DYNAMIC_SECTIONS);
if (dynamicSections)
{
t << "<div id=\"dynsection-" << sectionCount << "\" "
"onclick=\"return dynsection.toggleVisibility(this)\" "
"class=\"dynheader closed\" "
"style=\"cursor:pointer;\">\n";
t << " <img id=\"dynsection-" << sectionCount << "-trigger\" src=\""
<< relPath << "closed.png\" alt=\"+\"/> ";
}
else
{
t << "<div class=\"dynheader\">\n";
}
}
static void endSectionHeader(TextStream &t)
{
//t << "<!-- endSectionHeader -->";
t << "</div>\n";
}
static void startSectionSummary(TextStream &t,int sectionCount)
{
//t << "<!-- startSectionSummary -->";
bool dynamicSections = Config_getBool(HTML_DYNAMIC_SECTIONS);
if (dynamicSections)
{
t << "<div id=\"dynsection-" << sectionCount << "-summary\" "
"class=\"dynsummary\" "
"style=\"display:block;\">\n";
}
}
static void endSectionSummary(TextStream &t)
{
//t << "<!-- endSectionSummary -->";
bool dynamicSections = Config_getBool(HTML_DYNAMIC_SECTIONS);
if (dynamicSections)
{
t << "</div>\n";
}
}
static void startSectionContent(TextStream &t,int sectionCount)
{
//t << "<!-- startSectionContent -->";
bool dynamicSections = Config_getBool(HTML_DYNAMIC_SECTIONS);
if (dynamicSections)
{
t << "<div id=\"dynsection-" << sectionCount << "-content\" "
"class=\"dyncontent\" "
"style=\"display:none;\">\n";
}
else
{
t << "<div class=\"dyncontent\">\n";
}
}
static void endSectionContent(TextStream &t)
{
//t << "<!-- endSectionContent -->";
t << "</div>\n";
}
//----------------------------
void HtmlGenerator::startClassDiagram()
{
startSectionHeader(m_t,m_relPath,m_sectionCount);
}
void HtmlGenerator::endClassDiagram(const ClassDiagram &d,
const QCString &fileName,const QCString &name)
{
endSectionHeader(m_t);
startSectionSummary(m_t,m_sectionCount);
endSectionSummary(m_t);
startSectionContent(m_t,m_sectionCount);
TextStream tt;
d.writeImage(tt,dir(),m_relPath,fileName);
if (!tt.empty())
{
m_t << " <div class=\"center\">\n";
m_t << " <img src=\"";
m_t << m_relPath << fileName << ".png\" usemap=\"#" << convertToId(name);
m_t << "_map\" alt=\"\"/>\n";
m_t << " <map id=\"" << convertToId(name);
m_t << "_map\" name=\"" << convertToId(name);
m_t << "_map\">\n";
m_t << tt.str();
m_t << " </map>\n";
m_t << "</div>";
}
else
{
m_t << " <div class=\"center\">\n";
m_t << " <img src=\"";
m_t << m_relPath << fileName << ".png\" alt=\"\"/>\n";
m_t << " </div>";
}
endSectionContent(m_t);
m_sectionCount++;
}
void HtmlGenerator::startMemberList()
{
DBG_HTML(m_t << "<!-- startMemberList -->\n")
}
void HtmlGenerator::endMemberList()
{
DBG_HTML(m_t << "<!-- endMemberList -->\n")
}
// anonymous type:
// 0 = single column right aligned
// 1 = double column left aligned
// 2 = single column left aligned
void HtmlGenerator::startMemberItem(const QCString &anchor,MemberItemType type,const QCString &inheritId)
{
DBG_HTML(m_t << "<!-- startMemberItem() -->\n")
if (m_emptySection)
{
m_t << "<table class=\"memberdecls\">\n";
m_emptySection=FALSE;
}
m_t << "<tr class=\"memitem:" << anchor;
if (!inheritId.isEmpty())
{
m_t << " inherit " << inheritId;
}
m_t << "\"";
if (!anchor.isEmpty())
{
m_t << " id=\"r_" << anchor << "\"";
}
m_t << ">";
insertMemberAlignLeft(type, true);
}
void HtmlGenerator::endMemberItem(MemberItemType type)
{
if (type==MemberItemType::AnonymousStart || type==MemberItemType::AnonymousEnd)
{
insertMemberAlign(false);
}
m_t << "</td></tr>\n";
}
void HtmlGenerator::startMemberTemplateParams()
{
}
void HtmlGenerator::endMemberTemplateParams(const QCString &anchor,const QCString &inheritId)
{
m_t << "</td></tr>\n";
m_t << "<tr class=\"memitem:" << anchor;
if (!inheritId.isEmpty())
{
m_t << " inherit " << inheritId;
}
m_t << "\"><td class=\"memTemplItemLeft\" align=\"right\" valign=\"top\">";
}
void HtmlGenerator::startCompoundTemplateParams()
{
m_t << "<div class=\"compoundTemplParams\">";
}
void HtmlGenerator::endCompoundTemplateParams()
{
m_t << "</div>";
}
void HtmlGenerator::insertMemberAlign(bool templ)
{
DBG_HTML(m_t << "<!-- insertMemberAlign -->\n")
QCString className = templ ? "memTemplItemRight" : "memItemRight";
m_t << " </td><td class=\"" << className << "\" valign=\"bottom\">";
}
void HtmlGenerator::insertMemberAlignLeft(MemberItemType type, bool initTag)
{
if (!initTag) m_t << " </td>";
switch (type)
{
case MemberItemType::Normal: m_t << "<td class=\"memItemLeft\" align=\"right\" valign=\"top\">"; break;
case MemberItemType::AnonymousStart: m_t << "<td class=\"memItemLeft\" >"; break;
case MemberItemType::AnonymousEnd: m_t << "<td class=\"memItemLeft\" valign=\"top\">"; break;
case MemberItemType::Templated: m_t << "<td class=\"memTemplParams\" colspan=\"2\">"; break;
}
}
void HtmlGenerator::startMemberDescription(const QCString &anchor,const QCString &inheritId, bool typ)
{
DBG_HTML(m_t << "<!-- startMemberDescription -->\n")
if (m_emptySection)
{
m_t << "<table class=\"memberdecls\">\n";
m_emptySection=FALSE;
}
m_t << "<tr class=\"memdesc:" << anchor;
if (!inheritId.isEmpty())
{
m_t << " inherit " << inheritId;
}
m_t << "\">";
m_t << "<td class=\"mdescLeft\"> </td>";
if (typ) m_t << "<td class=\"mdescLeft\"> </td>";
m_t << "<td class=\"mdescRight\">";
}
void HtmlGenerator::endMemberDescription()
{
DBG_HTML(m_t << "<!-- endMemberDescription -->\n")
m_t << "<br /></td></tr>\n";
}
void HtmlGenerator::startMemberSections()
{
DBG_HTML(m_t << "<!-- startMemberSections -->\n")
m_emptySection=TRUE; // we postpone writing <table> until we actually
// write a row to prevent empty tables, which
// are not valid XHTML!
}
void HtmlGenerator::endMemberSections()
{
DBG_HTML(m_t << "<!-- endMemberSections -->\n")
if (!m_emptySection)
{
m_t << "</table>\n";
}
}
void HtmlGenerator::startMemberHeader(const QCString &anchor, int typ)
{
DBG_HTML(m_t << "<!-- startMemberHeader -->\n")
if (!m_emptySection)
{
m_t << "</table>";
m_emptySection=TRUE;
}
if (m_emptySection)
{
m_t << "<table class=\"memberdecls\">\n";
m_emptySection=FALSE;
}
m_t << "<tr class=\"heading\"><td colspan=\"" << typ << "\"><h2 class=\"groupheader\">";
if (!anchor.isEmpty())
{
m_t << "<a id=\"" << anchor << "\" name=\"" << anchor << "\"></a>\n";
}
}
void HtmlGenerator::endMemberHeader()
{
DBG_HTML(m_t << "<!-- endMemberHeader -->\n")
m_t << "</h2></td></tr>\n";
}
void HtmlGenerator::startMemberSubtitle()
{
DBG_HTML(m_t << "<!-- startMemberSubtitle -->\n")
m_t << "<tr><td class=\"ititle\" colspan=\"2\">";
}
void HtmlGenerator::endMemberSubtitle()
{
DBG_HTML(m_t << "<!-- endMemberSubtitle -->\n")
m_t << "</td></tr>\n";
}
void HtmlGenerator::startIndexList()
{
m_t << "<table>\n";
}
void HtmlGenerator::endIndexList()
{
m_t << "</table>\n";
}
void HtmlGenerator::startIndexKey()
{
//m_t << " <tr><td class=\"indexkey\">";
}
void HtmlGenerator::endIndexKey()
{
//m_t << "</td>";
}
void HtmlGenerator::startIndexValue(bool)
{
//m_t << "<td class=\"indexvalue\">";
}
void HtmlGenerator::endIndexValue(const QCString &,bool)
{
//m_t << "</td></tr>\n";
}
void HtmlGenerator::startMemberDocList()
{
DBG_HTML(m_t << "<!-- startMemberDocList -->\n";)
}
void HtmlGenerator::endMemberDocList()
{
DBG_HTML(m_t << "<!-- endMemberDocList -->\n";)
}
void HtmlGenerator::startMemberDoc( const QCString &/* clName */, const QCString &/* memName */,
const QCString &anchor, const QCString &title,
int memCount, int memTotal, bool /* showInline */)
{
DBG_HTML(m_t << "<!-- startMemberDoc -->\n";)
m_t << "\n<h2 class=\"memtitle\">"
<< "<span class=\"permalink\"><a href=\"#" << anchor << "\">◆ </a></span>";
docify(title);
if (memTotal>1)
{
m_t << " <span class=\"overload\">[" << memCount << "/" << memTotal <<"]</span>";
}
m_t << "</h2>\n";
m_t << "\n<div class=\"memitem\">\n";
m_t << "<div class=\"memproto\">\n";
}
void HtmlGenerator::startMemberDocPrefixItem()
{
DBG_HTML(m_t << "<!-- startMemberDocPrefixItem -->\n";)
m_t << "<div class=\"memtemplate\">\n";
}
void HtmlGenerator::endMemberDocPrefixItem()
{
DBG_HTML(m_t << "<!-- endMemberDocPrefixItem -->\n";)
m_t << "</div>\n";
}
void HtmlGenerator::startMemberDocName(bool /*align*/)
{
DBG_HTML(m_t << "<!-- startMemberDocName -->\n";)
m_t << " <table class=\"memname\">\n";
m_t << " <tr>\n";
m_t << " <td class=\"memname\">";
}
void HtmlGenerator::endMemberDocName()
{
DBG_HTML(m_t << "<!-- endMemberDocName -->\n";)
m_t << "</td>\n";
}
void HtmlGenerator::startParameterList(bool openBracket)
{
DBG_HTML(m_t << "<!-- startParameterList -->\n";)
m_t << " <td>";
if (openBracket) m_t << "(";
m_t << "</td>\n";
}
void HtmlGenerator::startParameterType(bool first,const QCString &key)
{
if (first)
{
DBG_HTML(m_t << "<!-- startFirstParameterType -->\n";)
m_t << " <td class=\"paramtype\">";
}
else
{
DBG_HTML(m_t << "<!-- startParameterType -->\n";)
m_t << " <tr>\n";
m_t << " <td class=\"paramkey\">" << key << "</td>\n";
m_t << " <td></td>\n";
m_t << " <td class=\"paramtype\">";
}
}
void HtmlGenerator::endParameterType()
{
DBG_HTML(m_t << "<!-- endParameterType -->\n";)
m_t << "</td>";
}
void HtmlGenerator::startParameterName(bool /*oneArgOnly*/)
{
DBG_HTML(m_t << "<!-- startParameterName -->\n";)
m_t << " <td class=\"paramname\"><span class=\"paramname\"><em>";
}
void HtmlGenerator::endParameterName()
{
DBG_HTML(m_t << "<!-- endParameterName -->\n";)
m_t << "</em></span>";
}
void HtmlGenerator::startParameterExtra()
{
DBG_HTML(m_t << "<!-- startParameterExtra -->\n";)
}
void HtmlGenerator::endParameterExtra(bool last,bool emptyList, bool closeBracket)
{
DBG_HTML(m_t << "<!-- endParameterExtra -->\n";)
if (last)
{
if (emptyList)
{
if (closeBracket) m_t << "</td><td>)";
m_t << "</td>\n";
m_t << " <td>";
}
else
{
m_t << " ";
if (closeBracket) m_t << ")";
}
}
else
{
m_t << "</td>\n";
m_t << " </tr>\n";
}
}
void HtmlGenerator::startParameterDefVal(const char *s)
{
m_t << "<span class=\"paramdefsep\">";
docify(s);
m_t << "</span><span class=\"paramdefval\">";
}
void HtmlGenerator::endParameterDefVal()
{
m_t << "</span>";
}
void HtmlGenerator::endParameterList()
{
DBG_HTML(m_t << "<!-- endParameterList -->\n";)
m_t << "</td>\n";
m_t << " </tr>\n";
}
void HtmlGenerator::exceptionEntry(const QCString &prefix,bool closeBracket)
{
DBG_HTML(m_t << "<!-- exceptionEntry -->\n";)
if (!closeBracket)
{
m_t << "</td>\n";
m_t << " </tr>\n";
m_t << " <tr>\n";
m_t << " <td align=\"right\">";
}
// colspan 2 so it gets both parameter type and parameter name columns
if (!prefix.isEmpty())
m_t << prefix << "</td><td>(</td><td colspan=\"2\">";
else if (closeBracket)
m_t << " )</td><td></td><td></td><td>";
else
m_t << "</td><td></td><td colspan=\"2\">";
}
void HtmlGenerator::endMemberDoc(bool hasArgs)
{
DBG_HTML(m_t << "<!-- endMemberDoc -->\n";)
if (!hasArgs)
{
m_t << " </tr>\n";
}
m_t << " </table>\n";
// m_t << "</div>\n";
}
void HtmlGenerator::startDotGraph()
{
startSectionHeader(m_t,m_relPath,m_sectionCount);
}
void HtmlGenerator::endDotGraph(DotClassGraph &g)
{
bool generateLegend = Config_getBool(GENERATE_LEGEND);
bool umlLook = Config_getBool(UML_LOOK);
endSectionHeader(m_t);
startSectionSummary(m_t,m_sectionCount);
endSectionSummary(m_t);
startSectionContent(m_t,m_sectionCount);
g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Html,dir(),fileName(),m_relPath,TRUE,TRUE,m_sectionCount);
if (generateLegend && !umlLook)
{
QCString url = m_relPath+"graph_legend"+Doxygen::htmlFileExtension;
m_t << "<center><span class=\"legend\">[";
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
m_t << "<a ";
if (generateTreeView) m_t << "target=\"top\" ";
m_t << "href=\"";
if (!url.isEmpty()) m_t << url;
m_t << "\">";
m_t << theTranslator->trLegend();
m_t << "</a>";
m_t << "]</span></center>";
}
endSectionContent(m_t);
m_sectionCount++;
}
void HtmlGenerator::startInclDepGraph()
{
startSectionHeader(m_t,m_relPath,m_sectionCount);
}
void HtmlGenerator::endInclDepGraph(DotInclDepGraph &g)
{
endSectionHeader(m_t);
startSectionSummary(m_t,m_sectionCount);
endSectionSummary(m_t);
startSectionContent(m_t,m_sectionCount);
g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Html,dir(),fileName(),m_relPath,TRUE,m_sectionCount);
endSectionContent(m_t);
m_sectionCount++;
}
void HtmlGenerator::startGroupCollaboration()
{
startSectionHeader(m_t,m_relPath,m_sectionCount);
}
void HtmlGenerator::endGroupCollaboration(DotGroupCollaboration &g)
{
endSectionHeader(m_t);
startSectionSummary(m_t,m_sectionCount);
endSectionSummary(m_t);
startSectionContent(m_t,m_sectionCount);
g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Html,dir(),fileName(),m_relPath,TRUE,m_sectionCount);
endSectionContent(m_t);
m_sectionCount++;
}
void HtmlGenerator::startCallGraph()
{
startSectionHeader(m_t,m_relPath,m_sectionCount);
}
void HtmlGenerator::endCallGraph(DotCallGraph &g)
{
endSectionHeader(m_t);
startSectionSummary(m_t,m_sectionCount);
endSectionSummary(m_t);
startSectionContent(m_t,m_sectionCount);
g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Html,dir(),fileName(),m_relPath,TRUE,m_sectionCount);
endSectionContent(m_t);
m_sectionCount++;
}
void HtmlGenerator::startDirDepGraph()
{
startSectionHeader(m_t,m_relPath,m_sectionCount);
}
void HtmlGenerator::endDirDepGraph(DotDirDeps &g)
{
endSectionHeader(m_t);
startSectionSummary(m_t,m_sectionCount);
endSectionSummary(m_t);
startSectionContent(m_t,m_sectionCount);
g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Html,dir(),fileName(),m_relPath,TRUE,m_sectionCount);
endSectionContent(m_t);
m_sectionCount++;
}
void HtmlGenerator::writeGraphicalHierarchy(DotGfxHierarchyTable &g)
{
g.writeGraph(m_t,dir(),fileName());
}
void HtmlGenerator::startMemberGroupHeader(bool)
{
m_t << "<tr><td colspan=\"2\"><div class=\"groupHeader\">";
}
void HtmlGenerator::endMemberGroupHeader()
{
m_t << "</div></td></tr>\n";
}
void HtmlGenerator::startMemberGroupDocs()
{
m_t << "<tr><td colspan=\"2\"><div class=\"groupText\">";
}
void HtmlGenerator::endMemberGroupDocs()
{
m_t << "</div></td></tr>\n";
}
void HtmlGenerator::startMemberGroup()
{
}
void HtmlGenerator::endMemberGroup(bool)
{
}
void HtmlGenerator::startIndent()
{
DBG_HTML(m_t << "<!-- startIndent -->\n";)
m_t << "<div class=\"memdoc\">\n";
}
void HtmlGenerator::endIndent()
{
DBG_HTML(m_t << "<!-- endIndent -->\n";)
m_t << "\n</div>\n" << "</div>\n";
}
void HtmlGenerator::addIndexItem(const QCString &,const QCString &)
{
}
void HtmlGenerator::writeNonBreakableSpace(int n)
{
for (int i=0; i<n; i++)
{
m_t << " ";
}
}
void HtmlGenerator::startDescTable(const QCString &title,const bool hasInits)
{
m_t << "<table class=\"fieldtable\">\n"
<< "<tr><th colspan=\"" << (hasInits?3:2) << "\">" << title << "</th></tr>";
}
void HtmlGenerator::endDescTable()
{
m_t << "</table>\n";
}
void HtmlGenerator::startDescTableRow()
{
m_t << "<tr>";
}
void HtmlGenerator::endDescTableRow()
{
m_t << "</tr>\n";
}
void HtmlGenerator::startDescTableTitle()
{
m_t << "<td class=\"fieldname\">";
}
void HtmlGenerator::endDescTableTitle()
{
m_t << " </td>";
}
void HtmlGenerator::startDescTableInit()
{
m_t << "<td class=\"fieldinit\">";
}
void HtmlGenerator::endDescTableInit()
{
m_t << " </td>";
}
void HtmlGenerator::startDescTableData()
{
m_t << "<td class=\"fielddoc\">";
}
void HtmlGenerator::endDescTableData()
{
m_t << "</td>";
}
void HtmlGenerator::startExamples()
{
m_t << "<dl class=\"section examples\"><dt>";
docify(theTranslator->trExamples());
m_t << "</dt>";
}
void HtmlGenerator::endExamples()
{
m_t << "</dl>\n";
}
void HtmlGenerator::writeDoc(const IDocNodeAST *ast,const Definition *ctx,const MemberDef *,int id)
{
const DocNodeAST *astImpl = dynamic_cast<const DocNodeAST*>(ast);
if (astImpl)
{
m_codeList->setId(id);
HtmlDocVisitor visitor(m_t,*m_codeList,ctx,fileName());
std::visit(visitor,astImpl->root);
}
}
//---------------- helpers for index generation -----------------------------
static void startQuickIndexList(TextStream &t,bool topLevel=TRUE)
{
if (!Config_getBool(DISABLE_INDEX))
{
if (topLevel)
{
t << " <div id=\"navrow1\" class=\"tabs\">\n";
}
else
{
t << " <div id=\"navrow2\" class=\"tabs2\">\n";
}
t << " <ul class=\"tablist\">\n";
}
else
{
t << "<ul>";
}
}
static void endQuickIndexList(TextStream &t)
{
if (!Config_getBool(DISABLE_INDEX))
{
t << " </ul>\n";
t << " </div>\n";
}
else
{
t << "</ul>\n";
}
}
static void startQuickIndexItem(TextStream &t,const QCString &l,
bool hl,bool /*compact*/,
const QCString &relPath)
{
t << " <li";
if (hl)
{
t << " class=\"current\"";
}
t << ">";
if (!l.isEmpty()) t << "<a href=\"" << correctURL(l,relPath) << "\">";
t << "<span>";
}
static void endQuickIndexItem(TextStream &t,const QCString &l)
{
t << "</span>";
if (!l.isEmpty()) t << "</a>";
t << "</li>\n";
}
static bool quickLinkVisible(LayoutNavEntry::Kind kind)
{
const auto &index = Index::instance();
bool showNamespaces = Config_getBool(SHOW_NAMESPACES);
bool showFiles = Config_getBool(SHOW_FILES);
switch (kind)
{
case LayoutNavEntry::MainPage: return TRUE;
case LayoutNavEntry::User: return TRUE;
case LayoutNavEntry::UserGroup: return TRUE;
case LayoutNavEntry::Pages: return index.numIndexedPages()>0;
case LayoutNavEntry::Topics: return index.numDocumentedGroups()>0;
case LayoutNavEntry::Modules: return index.numDocumentedModules()>0;
case LayoutNavEntry::ModuleList: return index.numDocumentedModules()>0;
case LayoutNavEntry::ModuleMembers: return index.numDocumentedModuleMembers(ModuleMemberHighlight::All)>0;
case LayoutNavEntry::Namespaces: return showNamespaces && index.numDocumentedNamespaces()>0;
case LayoutNavEntry::NamespaceList: return showNamespaces && index.numDocumentedNamespaces()>0;
case LayoutNavEntry::NamespaceMembers: return showNamespaces && index.numDocumentedNamespaceMembers(NamespaceMemberHighlight::All)>0;
case LayoutNavEntry::Concepts: return index.numDocumentedConcepts()>0;
case LayoutNavEntry::Classes: return index.numAnnotatedClasses()>0;
case LayoutNavEntry::ClassList: return index.numAnnotatedClasses()>0;
case LayoutNavEntry::ClassIndex: return index.numAnnotatedClasses()>0;
case LayoutNavEntry::ClassHierarchy: return index.numHierarchyClasses()>0;
case LayoutNavEntry::ClassMembers: return index.numDocumentedClassMembers(ClassMemberHighlight::All)>0;
case LayoutNavEntry::Files: return showFiles && index.numDocumentedFiles()>0;
case LayoutNavEntry::FileList: return showFiles && index.numDocumentedFiles()>0;
case LayoutNavEntry::FileGlobals: return showFiles && index.numDocumentedFileMembers(FileMemberHighlight::All)>0;
case LayoutNavEntry::Examples: return !Doxygen::exampleLinkedMap->empty();
case LayoutNavEntry::Interfaces: return index.numAnnotatedInterfaces()>0;
case LayoutNavEntry::InterfaceList: return index.numAnnotatedInterfaces()>0;
case LayoutNavEntry::InterfaceIndex: return index.numAnnotatedInterfaces()>0;
case LayoutNavEntry::InterfaceHierarchy: return index.numHierarchyInterfaces()>0;
case LayoutNavEntry::Structs: return index.numAnnotatedStructs()>0;
case LayoutNavEntry::StructList: return index.numAnnotatedStructs()>0;
case LayoutNavEntry::StructIndex: return index.numAnnotatedStructs()>0;
case LayoutNavEntry::Exceptions: return index.numAnnotatedExceptions()>0;
case LayoutNavEntry::ExceptionList: return index.numAnnotatedExceptions()>0;
case LayoutNavEntry::ExceptionIndex: return index.numAnnotatedExceptions()>0;
case LayoutNavEntry::ExceptionHierarchy: return index.numHierarchyExceptions()>0;
case LayoutNavEntry::None: // should never happen, means not properly initialized
assert(kind != LayoutNavEntry::None);
return FALSE;
}
return FALSE;
}
static void renderQuickLinksAsTree(TextStream &t,const QCString &relPath,LayoutNavEntry *root)
{
int count=0;
for (const auto &entry : root->children())
{
if (entry->visible() && quickLinkVisible(entry->kind())) count++;
}
if (count>0) // at least one item is visible
{
startQuickIndexList(t);
for (const auto &entry : root->children())
{
if (entry->visible() && quickLinkVisible(entry->kind()))
{
QCString url = entry->url();
t << "<li><a href=\"" << relPath << url << "\"><span>";
t << fixSpaces(entry->title());
t << "</span></a>\n";
// recursive into child list
renderQuickLinksAsTree(t,relPath,entry.get());
t << "</li>";
}
}
endQuickIndexList(t);
}
}
static void renderQuickLinksAsTabs(TextStream &t,const QCString &relPath,
LayoutNavEntry *hlEntry,LayoutNavEntry::Kind kind,
bool highlightParent,bool highlightSearch)
{
if (hlEntry->parent()) // first draw the tabs for the parent of hlEntry
{
renderQuickLinksAsTabs(t,relPath,hlEntry->parent(),kind,highlightParent,highlightSearch);
}
if (hlEntry->parent() && !hlEntry->parent()->children().empty()) // draw tabs for row containing hlEntry
{
bool topLevel = hlEntry->parent()->parent()==nullptr;
int count=0;
for (const auto &entry : hlEntry->parent()->children())
{
if (entry->visible() && quickLinkVisible(entry->kind())) count++;
}
if (count>0) // at least one item is visible
{
startQuickIndexList(t,topLevel);
for (const auto &entry : hlEntry->parent()->children())
{
if (entry->visible() && quickLinkVisible(entry->kind()))
{
QCString url = entry->url();
startQuickIndexItem(t,url,
entry.get()==hlEntry &&
(!entry->children().empty() ||
(entry->kind()==kind && !highlightParent)
),
TRUE,relPath);
t << fixSpaces(entry->title());
endQuickIndexItem(t,url);
}
}
if (hlEntry->parent()==LayoutDocManager::instance().rootNavEntry()) // first row is special as it contains the search box
{
bool searchEngine = Config_getBool(SEARCHENGINE);
bool serverBasedSearch = Config_getBool(SERVER_BASED_SEARCH);
if (searchEngine)
{
t << " <li>\n";
if (!serverBasedSearch) // pure client side search
{
writeClientSearchBox(t,relPath);
t << " </li>\n";
}
else // server based search
{
writeServerSearchBox(t,relPath,highlightSearch);
if (!highlightSearch)
{
t << " </li>\n";
}
}
}
if (!highlightSearch) // on the search page the index will be ended by the
// page itself
{
endQuickIndexList(t);
}
}
else // normal case for other rows than first one
{
endQuickIndexList(t);
}
}
}
}
static void writeDefaultQuickLinks(TextStream &t,
HighlightedItem hli,
const QCString &file,
const QCString &relPath)
{
bool serverBasedSearch = Config_getBool(SERVER_BASED_SEARCH);
bool searchEngine = Config_getBool(SEARCHENGINE);
bool externalSearch = Config_getBool(EXTERNAL_SEARCH);
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
LayoutNavEntry *root = LayoutDocManager::instance().rootNavEntry();
LayoutNavEntry::Kind kind = LayoutNavEntry::None;
LayoutNavEntry::Kind altKind = LayoutNavEntry::None; // fall back for the old layout file
bool highlightParent=false;
switch (hli) // map HLI enums to LayoutNavEntry::Kind enums
{
case HighlightedItem::Main: kind = LayoutNavEntry::MainPage; break;
case HighlightedItem::Topics: kind = LayoutNavEntry::Topics; break;
case HighlightedItem::Modules: kind = LayoutNavEntry::ModuleList; altKind = LayoutNavEntry::Modules; break;
case HighlightedItem::Namespaces: kind = LayoutNavEntry::NamespaceList; altKind = LayoutNavEntry::Namespaces; break;
case HighlightedItem::ClassHierarchy: kind = LayoutNavEntry::ClassHierarchy; break;
case HighlightedItem::InterfaceHierarchy: kind = LayoutNavEntry::InterfaceHierarchy; break;
case HighlightedItem::ExceptionHierarchy: kind = LayoutNavEntry::ExceptionHierarchy; break;
case HighlightedItem::Classes: kind = LayoutNavEntry::ClassIndex; altKind = LayoutNavEntry::Classes; break;
case HighlightedItem::Concepts: kind = LayoutNavEntry::Concepts; break;
case HighlightedItem::Interfaces: kind = LayoutNavEntry::InterfaceIndex; altKind = LayoutNavEntry::Interfaces; break;
case HighlightedItem::Structs: kind = LayoutNavEntry::StructIndex; altKind = LayoutNavEntry::Structs; break;
case HighlightedItem::Exceptions: kind = LayoutNavEntry::ExceptionIndex; altKind = LayoutNavEntry::Exceptions; break;
case HighlightedItem::AnnotatedClasses: kind = LayoutNavEntry::ClassList; altKind = LayoutNavEntry::Classes; break;
case HighlightedItem::AnnotatedInterfaces: kind = LayoutNavEntry::InterfaceList; altKind = LayoutNavEntry::Interfaces; break;
case HighlightedItem::AnnotatedStructs: kind = LayoutNavEntry::StructList; altKind = LayoutNavEntry::Structs; break;
case HighlightedItem::AnnotatedExceptions: kind = LayoutNavEntry::ExceptionList; altKind = LayoutNavEntry::Exceptions; break;
case HighlightedItem::Files: kind = LayoutNavEntry::FileList; altKind = LayoutNavEntry::Files; break;
case HighlightedItem::NamespaceMembers: kind = LayoutNavEntry::NamespaceMembers; break;
case HighlightedItem::ModuleMembers: kind = LayoutNavEntry::ModuleMembers; break;
case HighlightedItem::Functions: kind = LayoutNavEntry::ClassMembers; break;
case HighlightedItem::Globals: kind = LayoutNavEntry::FileGlobals; break;
case HighlightedItem::Pages: kind = LayoutNavEntry::Pages; break;
case HighlightedItem::Examples: kind = LayoutNavEntry::Examples; break;
case HighlightedItem::UserGroup: kind = LayoutNavEntry::UserGroup; break;
case HighlightedItem::ClassVisible: kind = LayoutNavEntry::ClassList; altKind = LayoutNavEntry::Classes;
highlightParent = true; break;
case HighlightedItem::ConceptVisible: kind = LayoutNavEntry::Concepts;
highlightParent = true; break;
case HighlightedItem::ModuleVisible: kind = LayoutNavEntry::ModuleList; altKind = LayoutNavEntry::Modules;
highlightParent = true; break;
case HighlightedItem::InterfaceVisible: kind = LayoutNavEntry::InterfaceList; altKind = LayoutNavEntry::Interfaces;
highlightParent = true; break;
case HighlightedItem::StructVisible: kind = LayoutNavEntry::StructList; altKind = LayoutNavEntry::Structs;
highlightParent = true; break;
case HighlightedItem::ExceptionVisible: kind = LayoutNavEntry::ExceptionList; altKind = LayoutNavEntry::Exceptions;
highlightParent = true; break;
case HighlightedItem::NamespaceVisible: kind = LayoutNavEntry::NamespaceList; altKind = LayoutNavEntry::Namespaces;
highlightParent = true; break;
case HighlightedItem::FileVisible: kind = LayoutNavEntry::FileList; altKind = LayoutNavEntry::Files;
highlightParent = true; break;
case HighlightedItem::None: break;
case HighlightedItem::Search: break;
}
if (!Config_getBool(DISABLE_INDEX) && Config_getBool(HTML_DYNAMIC_MENUS))
{
QCString searchPage;
if (externalSearch)
{
searchPage = "search" + Doxygen::htmlFileExtension;
}
else
{
searchPage = "search.php";
}
t << "<script type=\"text/javascript\" src=\"" << relPath << "menudata.js\"></script>\n";
t << "<script type=\"text/javascript\" src=\"" << relPath << "menu.js\"></script>\n";
t << "<script type=\"text/javascript\">\n";
t << "/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n";
t << "$(function() {\n";
t << " initMenu('" << relPath << "',"
<< (searchEngine?"true":"false") << ","
<< (serverBasedSearch?"true":"false") << ",'"
<< searchPage << "','"
<< theTranslator->trSearch() << "',"
<< (generateTreeView?"true":"false")
<< ");\n";
if (Config_getBool(SEARCHENGINE))
{
if (!serverBasedSearch)
{
t << " $(function() { init_search(); });\n";
}
else
{
t << " $(function() {\n"
<< " if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); }\n";
t << " });\n";
}
}
t << "});\n";
t << "/* @license-end */\n";
t << "</script>\n";
t << "<div id=\"main-nav\"></div>\n";
}
else if (!Config_getBool(DISABLE_INDEX)) // && !Config_getBool(HTML_DYNAMIC_MENUS)
{
// find highlighted index item
LayoutNavEntry *hlEntry = root->find(kind,kind==LayoutNavEntry::UserGroup ? file : QCString());
if (!hlEntry && altKind!=LayoutNavEntry::None) { hlEntry=root->find(altKind); kind=altKind; }
if (!hlEntry) // highlighted item not found in the index! -> just show the level 1 index...
{
highlightParent=TRUE;
hlEntry = root->children().front().get();
if (hlEntry==nullptr)
{
return; // argl, empty index!
}
}
if (kind==LayoutNavEntry::UserGroup)
{
LayoutNavEntry *e = hlEntry->children().front().get();
if (e)
{
hlEntry = e;
}
}
renderQuickLinksAsTabs(t,relPath,hlEntry,kind,highlightParent,hli==HighlightedItem::Search);
}
else if (!Config_getBool(GENERATE_TREEVIEW))
{
renderQuickLinksAsTree(t,relPath,root);
}
}
void HtmlGenerator::endQuickIndices()
{
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
m_t << "</div><!-- top -->\n";
if (!generateTreeView)
{
m_t << "<div id=\"doc-content\">\n";
}
}
QCString HtmlGenerator::writeSplitBarAsString(const QCString &name,const QCString &relpath)
{
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
QCString result;
// write split bar
if (generateTreeView)
{
QCString fn = name;
addHtmlExtensionIfMissing(fn);
if (!Config_getBool(DISABLE_INDEX) || !Config_getBool(FULL_SIDEBAR))
{
result += QCString(
"<div id=\"side-nav\" class=\"ui-resizable side-nav-resizable\">\n");
}
result+= QCString(
" <div id=\"nav-tree\">\n"
" <div id=\"nav-tree-contents\">\n"
" <div id=\"nav-sync\" class=\"sync\"></div>\n"
" </div>\n"
" </div>\n"
" <div id=\"splitbar\" style=\"-moz-user-select:none;\" \n"
" class=\"ui-resizable-handle\">\n"
" </div>\n"
"</div>\n"
"<script type=\"text/javascript\">\n"
"/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n"
"$(function(){initNavTree('") + fn +
QCString("','") + relpath +
QCString("'); initResizable(true); });\n"
"/* @license-end */\n"
"</script>\n"
"<div id=\"doc-content\">\n");
}
else
{
result += "<script type=\"text/javascript\">\n"
"/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n"
"$(function(){ initResizable(false); });\n"
"/* @license-end */\n"
"</script>\n";
}
return result;
}
void HtmlGenerator::writeSplitBar(const QCString &name)
{
m_t << writeSplitBarAsString(name,m_relPath);
}
void HtmlGenerator::writeNavigationPath(const QCString &s)
{
m_t << substitute(s,"$relpath^",m_relPath);
}
void HtmlGenerator::startContents()
{
m_t << "<div class=\"contents\">\n";
}
void HtmlGenerator::endContents()
{
m_t << "</div><!-- contents -->\n";
}
void HtmlGenerator::startPageDoc(const QCString &/* pageTitle */)
{
m_t << "<div>";
}
void HtmlGenerator::endPageDoc()
{
m_t << "</div><!-- PageDoc -->\n";
}
void HtmlGenerator::writeQuickLinks(HighlightedItem hli,const QCString &file)
{
writeDefaultQuickLinks(m_t,hli,file,m_relPath);
}
// PHP based search script
void HtmlGenerator::writeSearchPage()
{
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
bool disableIndex = Config_getBool(DISABLE_INDEX);
QCString projectName = Config_getString(PROJECT_NAME);
QCString htmlOutput = Config_getString(HTML_OUTPUT);
// OPENSEARCH_PROVIDER {
QCString configFileName = htmlOutput+"/search_config.php";
std::ofstream f = Portable::openOutputStream(configFileName);
if (f.is_open())
{
TextStream t(&f);
t << "<?php\n\n";
t << "$config = array(\n";
t << " 'PROJECT_NAME' => \"" << convertToHtml(projectName) << "\",\n";
t << " 'GENERATE_TREEVIEW' => " << (generateTreeView?"true":"false") << ",\n";
t << " 'DISABLE_INDEX' => " << (disableIndex?"true":"false") << ",\n";
t << ");\n\n";
t << "$translator = array(\n";
t << " 'search_results_title' => \"" << theTranslator->trSearchResultsTitle() << "\",\n";
t << " 'search_results' => array(\n";
t << " 0 => \"" << theTranslator->trSearchResults(0) << "\",\n";
t << " 1 => \"" << theTranslator->trSearchResults(1) << "\",\n";
t << " 2 => \"" << substitute(theTranslator->trSearchResults(2), "$", "\\$") << "\",\n";
t << " ),\n";
t << " 'search_matches' => \"" << theTranslator->trSearchMatches() << "\",\n";
t << " 'search' => \"" << theTranslator->trSearch() << "\",\n";
t << " 'split_bar' => \"" << substitute(substitute(writeSplitBarAsString("search",""), "\"","\\\""), "\n","\\n") << "\",\n";
t << " 'logo' => \"" << substitute(substitute(writeLogoAsString(""), "\"","\\\""), "\n","\\n") << "\",\n";
t << ");\n\n";
t << "?>\n";
}
f.close();
ResourceMgr::instance().copyResource("search_functions.php",htmlOutput);
ResourceMgr::instance().copyResource("search_opensearch.php",htmlOutput);
// OPENSEARCH_PROVIDER }
QCString fileName = htmlOutput+"/search.php";
f = Portable::openOutputStream(fileName);
if (f.is_open())
{
TextStream t(&f);
t << substituteHtmlKeywords(g_header,"Search","");
t << "<!-- " << theTranslator->trGeneratedBy() << " Doxygen "
<< getDoxygenVersion() << " -->\n";
t << "<script type=\"text/javascript\">\n";
t << "/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n";
t << "var searchBox = new SearchBox(\"searchBox\", \""
<< "search/\",'" << Doxygen::htmlFileExtension << "');\n";
t << "/* @license-end */\n";
t << "</script>\n";
if (!Config_getBool(DISABLE_INDEX))
{
writeDefaultQuickLinks(t,HighlightedItem::Search,QCString(),QCString());
}
else
{
t << "</div>\n";
}
t << "<?php\n";
t << "require_once \"search_functions.php\";\n";
t << "main();\n";
t << "?>\n";
// Write empty navigation path, to make footer connect properly
if (generateTreeView)
{
t << "</div><!-- doc-content -->\n";
}
writePageFooter(t,"Search","","");
}
f.close();
QCString scriptName = htmlOutput+"/search/search.js";
f = Portable::openOutputStream(scriptName);
if (f.is_open())
{
TextStream t(&f);
t << ResourceMgr::instance().getAsString("extsearch.js");
}
else
{
err("Failed to open file '%s' for writing...\n",qPrint(scriptName));
}
}
void HtmlGenerator::writeExternalSearchPage()
{
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
QCString dname = Config_getString(HTML_OUTPUT);
QCString fileName = dname+"/search"+Doxygen::htmlFileExtension;
std::ofstream f = Portable::openOutputStream(fileName);
if (f.is_open())
{
TextStream t(&f);
t << substituteHtmlKeywords(g_header,"Search","");
t << "<!-- " << theTranslator->trGeneratedBy() << " Doxygen "
<< getDoxygenVersion() << " -->\n";
t << "<script type=\"text/javascript\">\n";
t << "/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */\n";
t << "var searchBox = new SearchBox(\"searchBox\", \""
<< "search/\",'" << Doxygen::htmlFileExtension << "');\n";
t << "/* @license-end */\n";
t << "</script>\n";
if (!Config_getBool(DISABLE_INDEX))
{
writeDefaultQuickLinks(t,HighlightedItem::Search,QCString(),QCString());
if (!Config_getBool(HTML_DYNAMIC_MENUS)) // for dynamic menus, menu.js creates this part
{
t << " <input type=\"text\" id=\"MSearchField\" name=\"query\" value=\"\" placeholder=\"" << theTranslator->trSearch() <<
"\" size=\"20\" accesskey=\"S\" onfocus=\"searchBox.OnSearchFieldFocus(true)\" onblur=\"searchBox.OnSearchFieldFocus(false)\"/>\n";
}
t << " </form>\n";
t << " </div><div class=\"right\"></div>\n";
t << " </div>\n";
t << " </li>\n";
t << " </ul>\n";
t << " </div>\n";
t << "</div>\n";
}
else
{
t << "</div>\n";
}
t << writeSplitBarAsString("search","");
t << "<div class=\"header\">\n";
t << " <div class=\"headertitle\">\n";
t << " <div class=\"title\">" << theTranslator->trSearchResultsTitle() << "</div>\n";
t << " </div>\n";
t << "</div>\n";
t << "<div class=\"contents\">\n";
t << "<div id=\"searchresults\"></div>\n";
t << "</div>\n";
if (generateTreeView)
{
t << "</div><!-- doc-content -->\n";
}
writePageFooter(t,"Search","","");
}
f.close();
QCString scriptName = dname+"/search/search.js";
f = Portable::openOutputStream(scriptName);
if (f.is_open())
{
TextStream t(&f);
t << "var searchResultsText=["
<< "\"" << theTranslator->trSearchResults(0) << "\","
<< "\"" << theTranslator->trSearchResults(1) << "\","
<< "\"" << theTranslator->trSearchResults(2) << "\"];\n";
t << "var serverUrl=\"" << Config_getString(SEARCHENGINE_URL) << "\";\n";
t << "var tagMap = {\n";
bool first=TRUE;
// add search mappings
const StringVector &extraSearchMappings = Config_getList(EXTRA_SEARCH_MAPPINGS);
for (const auto &ml : extraSearchMappings)
{
QCString mapLine = ml.c_str();
int eqPos = mapLine.find('=');
if (eqPos!=-1) // tag command contains a destination
{
QCString tagName = mapLine.left(eqPos).stripWhiteSpace();
QCString destName = mapLine.right(mapLine.length()-eqPos-1).stripWhiteSpace();
if (!tagName.isEmpty())
{
if (!first) t << ",\n";
t << " \"" << tagName << "\": \"" << destName << "\"";
first=FALSE;
}
}
}
if (!first) t << "\n";
t << "};\n\n";
t << ResourceMgr::instance().getAsString("extsearch.js");
t << "\n";
t << "$(function() {\n";
t << " var query = trim(getURLParameter('query'));\n";
t << " if (query) {\n";
t << " searchFor(query,0,20);\n";
t << " } else {\n";
t << " var results = $('#results');\n";
t << " results.html('<p>" << theTranslator->trSearchResults(0) << "</p>');\n";
t << " }\n";
t << "});\n";
}
else
{
err("Failed to open file '%s' for writing...\n",qPrint(scriptName));
}
}
void HtmlGenerator::startConstraintList(const QCString &header)
{
m_t << "<div class=\"typeconstraint\">\n";
m_t << "<dl><dt><b>" << header << "</b></dt><dd>\n";
m_t << "<table border=\"0\" cellspacing=\"2\" cellpadding=\"0\">\n";
}
void HtmlGenerator::startConstraintParam()
{
m_t << "<tr><td valign=\"top\"><em>";
}
void HtmlGenerator::endConstraintParam()
{
m_t << "</em></td>";
}
void HtmlGenerator::startConstraintType()
{
m_t << "<td> :</td><td valign=\"top\"><em>";
}
void HtmlGenerator::endConstraintType()
{
m_t << "</em></td>";
}
void HtmlGenerator::startConstraintDocs()
{
m_t << "<td> ";
}
void HtmlGenerator::endConstraintDocs()
{
m_t << "</td></tr>\n";
}
void HtmlGenerator::endConstraintList()
{
m_t << "</table>\n";
m_t << "</dd>\n";
m_t << "</dl>\n";
m_t << "</div>\n";
}
void HtmlGenerator::lineBreak(const QCString &style)
{
if (!style.isEmpty())
{
m_t << "<br class=\"" << style << "\" />\n";
}
else
{
m_t << "<br />\n";
}
}
void HtmlGenerator::startHeaderSection()
{
m_t << "<div class=\"header\">\n";
}
void HtmlGenerator::startTitleHead(const QCString &)
{
m_t << " <div class=\"headertitle\">";
startTitle();
}
void HtmlGenerator::endTitleHead(const QCString &,const QCString &)
{
endTitle();
m_t << "</div>\n";
}
void HtmlGenerator::endHeaderSection()
{
m_t << "</div><!--header-->\n";
}
void HtmlGenerator::startInlineHeader()
{
if (m_emptySection)
{
m_t << "<table class=\"memberdecls\">\n";
m_emptySection=FALSE;
}
m_t << "<tr><td colspan=\"2\"><h3>";
}
void HtmlGenerator::endInlineHeader()
{
m_t << "</h3></td></tr>\n";
}
void HtmlGenerator::startMemberDocSimple(bool isEnum)
{
DBG_HTML(m_t << "<!-- startMemberDocSimple -->\n";)
m_t << "<table class=\"fieldtable\">\n";
m_t << "<tr><th colspan=\"" << (isEnum?"2":"3") << "\">";
m_t << (isEnum? theTranslator->trEnumerationValues() :
theTranslator->trCompoundMembers()) << "</th></tr>\n";
}
void HtmlGenerator::endMemberDocSimple(bool)
{
DBG_HTML(m_t << "<!-- endMemberDocSimple -->\n";)
m_t << "</table>\n";
}
void HtmlGenerator::startInlineMemberType()
{
DBG_HTML(m_t << "<!-- startInlineMemberType -->\n";)
m_t << "<tr><td class=\"fieldtype\">\n";
}
void HtmlGenerator::endInlineMemberType()
{
DBG_HTML(m_t << "<!-- endInlineMemberType -->\n";)
m_t << "</td>\n";
}
void HtmlGenerator::startInlineMemberName()
{
DBG_HTML(m_t << "<!-- startInlineMemberName -->\n";)
m_t << "<td class=\"fieldname\">\n";
}
void HtmlGenerator::endInlineMemberName()
{
DBG_HTML(m_t << "<!-- endInlineMemberName -->\n";)
m_t << "</td>\n";
}
void HtmlGenerator::startInlineMemberDoc()
{
DBG_HTML(m_t << "<!-- startInlineMemberDoc -->\n";)
m_t << "<td class=\"fielddoc\">\n";
}
void HtmlGenerator::endInlineMemberDoc()
{
DBG_HTML(m_t << "<!-- endInlineMemberDoc -->\n";)
m_t << "</td></tr>\n";
}
void HtmlGenerator::startLabels()
{
DBG_HTML(m_t << "<!-- startLabels -->\n";)
m_t << "<span class=\"mlabels\">";
}
void HtmlGenerator::writeLabel(const QCString &l,bool /*isLast*/)
{
DBG_HTML(m_t << "<!-- writeLabel(" << l << ") -->\n";)
//m_t << "<tt>[" << l << "]</tt>";
//if (!isLast) m_t << ", ";
m_t << "<span class=\"mlabel\">" << l << "</span>";
}
void HtmlGenerator::endLabels()
{
DBG_HTML(m_t << "<!-- endLabels -->\n";)
m_t << "</span>";
}
void HtmlGenerator::writeInheritedSectionTitle(
const QCString &id, const QCString &ref,
const QCString &file, const QCString &anchor,
const QCString &title, const QCString &name)
{
DBG_HTML(m_t << "<!-- writeInheritedSectionTitle -->\n";)
QCString a = anchor;
if (!a.isEmpty()) a.prepend("#");
QCString classLink = QCString("<a class=\"el\" ");
if (!ref.isEmpty())
{
classLink+= externalLinkTarget();
classLink += " href=\"";
classLink+= externalRef(m_relPath,ref,TRUE);
}
else
{
classLink += "href=\"";
classLink+=m_relPath;
}
QCString fn = file;
addHtmlExtensionIfMissing(fn);
classLink=classLink+fn+a;
classLink+=QCString("\">")+convertToHtml(name,FALSE)+"</a>";
m_t << "<tr class=\"inherit_header " << id << "\">"
<< "<td colspan=\"2\" onclick=\"javascript:dynsection.toggleInherit('" << id << "')\">"
<< "<img src=\"" << m_relPath << "closed.png\" alt=\"-\"/> "
<< theTranslator->trInheritedFrom(convertToHtml(title,FALSE),classLink)
<< "</td></tr>\n";
}
void HtmlGenerator::writeSummaryLink(const QCString &file,const QCString &anchor,const QCString &title,bool first)
{
if (first)
{
m_t << " <div class=\"summary\">\n";
}
else
{
m_t << " |\n";
}
m_t << "<a href=\"";
if (!file.isEmpty())
{
QCString fn = file;
addHtmlExtensionIfMissing(fn);
m_t << m_relPath << fn;
}
else if (!anchor.isEmpty())
{
m_t << "#";
m_t << anchor;
}
m_t << "\">";
m_t << title;
m_t << "</a>";
}
void HtmlGenerator::endMemberDeclaration(const QCString &anchor,const QCString &inheritId)
{
m_t << "<tr class=\"separator:" << anchor;
if (!inheritId.isEmpty())
{
m_t << " inherit " << inheritId;
}
m_t << "\"><td class=\"memSeparator\" colspan=\"2\"> </td></tr>\n";
}
QCString HtmlGenerator::getMathJaxMacros()
{
return getConvertLatexMacro();
}
QCString HtmlGenerator::getNavTreeCss()
{
ResourceMgr &mgr = ResourceMgr::instance();
return replaceVariables(mgr.getAsString("navtree.css"));
}
void HtmlGenerator::writeLocalToc(const SectionRefs §ionRefs,const LocalToc &localToc)
{
if (localToc.isHtmlEnabled())
{
int level=0;
int indent=0;
auto writeIndent = [&]() { for (int i=0;i<indent*2;i++) m_t << " "; };
auto incIndent = [&](const QCString &text) { writeIndent(); m_t << text << "\n"; indent++; };
auto decIndent = [&](const QCString &text) { indent--; writeIndent(); m_t << text << "\n"; };
m_t << "<div class=\"toc\">";
m_t << "<h3>" << theTranslator->trRTFTableOfContents() << "</h3>\n";
int maxLevel = localToc.htmlLevel();
char cs[2];
cs[1]='\0';
BoolVector inLi(maxLevel+1,false);
for (const SectionInfo *si : sectionRefs)
{
//printf("Section: label=%s type=%d isSection()=%d\n",qPrint(si->label()),si->type(),isSection(si->type()));
SectionType type = si->type();
if (type.isSection())
{
//printf(" level=%d title=%s maxLevel=%d\n",level,qPrint(si->title()),maxLevel);
int nextLevel = type.level();
if (nextLevel>level)
{
for (int l=level;l<nextLevel;l++)
{
if (l < maxLevel)
{
incIndent("<ul>");
cs[0]=static_cast<char>('0'+l+1);
const char *empty = (l!=nextLevel-1) ? " empty" : "";
incIndent("<li class=\"level" + QCString(cs) + empty + "\">");
}
}
}
else if (nextLevel<level)
{
for (int l=level;l>nextLevel;l--)
{
if (l <= maxLevel) decIndent("</li>");
inLi[l] = false;
if (l <= maxLevel) decIndent("</ul>");
}
}
if (nextLevel <= maxLevel)
{
if (inLi[nextLevel] || level>nextLevel)
{
decIndent("</li>");
cs[0]=static_cast<char>('0'+nextLevel);
incIndent("<li class=\"level" + QCString(cs) + "\">");
}
QCString titleDoc = si->title();
QCString label = si->label();
if (titleDoc.isEmpty()) titleDoc = label;
writeIndent();
m_t << "<a href=\"#"+label+"\">"
<< convertToHtml(filterTitle(titleDoc))
<< "</a>\n";
inLi[nextLevel]=true;
level = nextLevel;
}
}
}
if (level > maxLevel) level = maxLevel;
while (level>0)
{
decIndent("</li>");
decIndent("</ul>");
level--;
}
m_t << "</div>\n";
}
}
| 108,187
|
C++
|
.cpp
| 3,277
| 27.803174
| 147
| 0.591265
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,407
|
datetime.cpp
|
doxygen_doxygen/src/datetime.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2022 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.
*
*/
#include <cstdlib>
#include <chrono>
#include <memory>
#include <array>
#include <functional>
#include "regex.h"
#include "datetime.h"
#include "config.h"
#include "portable.h"
#include "language.h"
#include "message.h"
#include "growbuf.h"
std::tm getCurrentDateTime()
{
QCString sourceDateEpoch = Portable::getenv("SOURCE_DATE_EPOCH");
if (!sourceDateEpoch.isEmpty()) // see https://reproducible-builds.org/specs/source-date-epoch/
{
bool ok = false;
uint64_t epoch = sourceDateEpoch.toUInt64(&ok);
if (!ok)
{
static bool warnedOnce=FALSE;
if (!warnedOnce)
{
warn_uncond("Environment variable SOURCE_DATE_EPOCH does not contain a valid number; value is '%s'\n",
qPrint(sourceDateEpoch));
warnedOnce=TRUE;
}
}
else // use given epoch value as current 'built' time
{
auto epoch_start = std::chrono::time_point<std::chrono::system_clock>{};
auto epoch_seconds = std::chrono::seconds(epoch);
auto build_time = epoch_start + epoch_seconds;
std::time_t time = std::chrono::system_clock::to_time_t(build_time);
return *gmtime(&time);
}
}
// return current local time
auto now = std::chrono::system_clock::now();
std::time_t time = std::chrono::system_clock::to_time_t(now);
return *localtime(&time);
}
QCString dateToString(DateTimeType includeTime)
{
auto current = getCurrentDateTime();
return theTranslator->trDateTime(current.tm_year + 1900,
current.tm_mon + 1,
current.tm_mday,
(current.tm_wday+6)%7+1, // map: Sun=0..Sat=6 to Mon=1..Sun=7
current.tm_hour,
current.tm_min,
current.tm_sec,
includeTime);
}
QCString yearToString()
{
auto current = getCurrentDateTime();
return QCString().setNum(current.tm_year+1900);
}
struct SpecFormat
{
const reg::Ex re;
int count;
int offset;
int format;
};
using TMFieldAssigner = std::function< void(std::tm &,int value) >;
struct DateTimeField
{
TMFieldAssigner assigner;
int minVal;
int maxVal;
const char *name;
};
static std::array g_specFormats
{
// regular expression, num values, offset, format bits
SpecFormat{ std::string_view(R"((\d+)-(\d+)-(\d+)\s*(\d+):(\d+):(\d+))"), 6, 0, SF_Date|SF_Time|SF_Seconds }, // format 13-04-2015 12:34:56
SpecFormat{ std::string_view(R"((\d+)-(\d+)-(\d+)\s*(\d+):(\d+))"), 5, 0, SF_Date|SF_Time }, // format 13-04-2015 12:34
SpecFormat{ std::string_view(R"((\d+)-(\d+)-(\d+))"), 3, 0, SF_Date }, // format 13-04-2015
SpecFormat{ std::string_view(R"((\d+):(\d+):(\d+))"), 3, 3, SF_Time|SF_Seconds }, // format 12:34:56
SpecFormat{ std::string_view(R"((\d+):(\d+))"), 2, 3, SF_Time } // format 12:34
};
static std::array g_assignValues
{
// assigner, minVal, maxVal, name
DateTimeField{ [](std::tm &tm,int value) { tm.tm_year = value-1900; }, 1900, 9999, "year" },
DateTimeField{ [](std::tm &tm,int value) { tm.tm_mon = value-1; }, 1, 12, "month" },
DateTimeField{ [](std::tm &tm,int value) { tm.tm_mday = value; }, 1, 31, "day" },
DateTimeField{ [](std::tm &tm,int value) { tm.tm_hour = value; }, 0, 23, "hour" },
DateTimeField{ [](std::tm &tm,int value) { tm.tm_min = value; }, 0, 59, "minute" },
DateTimeField{ [](std::tm &tm,int value) { tm.tm_sec = value; }, 0, 59, "second" }
};
static void determine_weekday( std::tm& tm )
{
auto cpy = tm;
// there are some problems when the hr:min:sec are on 00:00:00 in determining the weekday
cpy.tm_hour = 12;
const auto as_time_t = std::mktime( &cpy ) ;
if (as_time_t != -1)
{
cpy = *std::localtime( &as_time_t ) ;
tm.tm_wday = cpy.tm_wday;
}
}
QCString dateTimeFromString(const QCString &spec,std::tm &dt,int &format)
{
// for an empty spec field return the current date and time
dt = getCurrentDateTime();
if (spec.isEmpty())
{
format = SF_Date | SF_Time | SF_Seconds;
return QCString();
}
// find a matching pattern
std::string s = spec.str();
for (const auto &fmt : g_specFormats)
{
reg::Match m;
if (reg::match(s,m,fmt.re)) // match found
{
for (int i=0; i<fmt.count; i++)
{
int value = std::atoi(m[i+1].str().c_str());
const DateTimeField &dtf = g_assignValues[i+fmt.offset];
if (value<dtf.minVal || value>dtf.maxVal) // check if the value is in the expected range
{
return QCString().sprintf("value for %s is %d which is outside of the value range [%d..%d]",
dtf.name, value, dtf.minVal, dtf.maxVal);
}
dtf.assigner(dt,value);
}
format = fmt.format;
if (format&SF_Date) // if we have a date also determine the weekday
{
determine_weekday(dt);
}
return QCString();
}
}
// no matching pattern found
return "invalid or non representable date/time argument";
}
QCString formatDateTime(const QCString &format,const std::tm &dt,int &formatUsed)
{
formatUsed = 0;
auto getYear = [](const std::tm &dat) { return dat.tm_year+1900; };
auto getMonth = [](const std::tm &dat) { return dat.tm_mon+1; };
auto getDay = [](const std::tm &dat) { return dat.tm_mday; };
auto getDayOfWeek = [](const std::tm &dat) { return (dat.tm_wday+6)%7+1; };
GrowBuf growBuf;
char c = 0;
const char *p = format.data();
const char *fmt_zero = "%02d";
const char *fmt_nonzero = "%d";
const char *fmt_selected = nullptr;
if (p==nullptr) return QCString();
while ((c=*p++))
{
char nc = *p;
switch (c)
{
case '%':
fmt_selected = nc=='-' ? fmt_nonzero : fmt_zero; // %-H produces 1 and %H produces 01
if (nc=='-') nc=*++p; // skip over -
switch (nc)
{
case '%': growBuf.addChar('%'); break;
case 'y': growBuf.addInt(fmt_selected,getYear(dt)%100); formatUsed|=SF_Date; break;
case 'Y': growBuf.addInt("%d",getYear(dt)); formatUsed|=SF_Date; break;
case 'm': growBuf.addInt(fmt_selected,getMonth(dt)); formatUsed|=SF_Date; break;
case 'b': growBuf.addStr(theTranslator->trMonth(getMonth(dt),false,false)); formatUsed|=SF_Date; break;
case 'B': growBuf.addStr(theTranslator->trMonth(getMonth(dt),false,true)); formatUsed|=SF_Date; break;
case 'd': growBuf.addInt(fmt_selected,getDay(dt)); formatUsed|=SF_Date; break;
case 'u': growBuf.addInt("%d",getDayOfWeek(dt)); /* Monday = 1 ... Sunday = 7 */ formatUsed|=SF_Date; break;
case 'w': growBuf.addInt("%d",getDayOfWeek(dt)%7); /* Sunday = 0 ... Saturday = 6 */ formatUsed|=SF_Date; break;
case 'a': growBuf.addStr(theTranslator->trDayOfWeek(getDayOfWeek(dt),false,false)); formatUsed|=SF_Date; break;
case 'A': growBuf.addStr(theTranslator->trDayOfWeek(getDayOfWeek(dt),false,true)); formatUsed|=SF_Date; break;
case 'H': growBuf.addInt(fmt_selected,dt.tm_hour); formatUsed|=SF_Time; break;
case 'I': growBuf.addInt(fmt_selected,dt.tm_hour%12); formatUsed|=SF_Time; break;
case 'p': growBuf.addStr(theTranslator->trDayPeriod(dt.tm_hour>=12)); formatUsed|=SF_Time; break;
case 'M': growBuf.addInt(fmt_selected,dt.tm_min); formatUsed|=SF_Time; break;
case 'S': growBuf.addInt(fmt_selected,dt.tm_sec); formatUsed|=SF_Seconds; break;
default:
growBuf.addChar(c);
if (*(p-1)=='-') growBuf.addChar('-');
growBuf.addChar(nc);
break;
}
p++;
break;
default:
growBuf.addChar(c);
break;
}
}
growBuf.addChar(0);
return growBuf.get();
}
| 9,239
|
C++
|
.cpp
| 214
| 37.476636
| 144
| 0.558837
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,408
|
arguments.cpp
|
doxygen_doxygen/src/arguments.cpp
|
/*****************************************************************************
* Copyright (C) 1997-2019 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.
*/
#include <algorithm>
#include "arguments.h"
/*! the argument list is documented if one of its
* arguments is documented
*/
bool ArgumentList::hasDocumentation() const
{
return std::any_of(begin(),end(),[](const Argument &a){ return a.hasDocumentation(); });
}
| 920
|
C++
|
.cpp
| 21
| 41.809524
| 90
| 0.696089
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,409
|
index.cpp
|
doxygen_doxygen/src/index.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 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.
*
*/
/** @file
* @brief This file contains functions for the various index pages.
*/
#include <cstdlib>
#include <array>
#include <assert.h>
#include "message.h"
#include "index.h"
#include "indexlist.h"
#include "doxygen.h"
#include "config.h"
#include "filedef.h"
#include "outputlist.h"
#include "util.h"
#include "groupdef.h"
#include "language.h"
#include "htmlgen.h"
#include "htmlhelp.h"
#include "ftvhelp.h"
#include "dot.h"
#include "dotgfxhierarchytable.h"
#include "dotlegendgraph.h"
#include "pagedef.h"
#include "dirdef.h"
#include "vhdldocgen.h"
#include "layout.h"
#include "memberlist.h"
#include "classlist.h"
#include "namespacedef.h"
#include "filename.h"
#include "tooltip.h"
#include "utf8.h"
#include "portable.h"
#include "moduledef.h"
#include "sitemap.h"
#define MAX_ITEMS_BEFORE_MULTIPAGE_INDEX 200
#define MAX_ITEMS_BEFORE_QUICK_INDEX 30
// helpers
static int countClassHierarchy(ClassDef::CompoundType ct);
static void countFiles(int &htmlFiles,int &files);
static int countGroups();
static int countDirs();
static int countNamespaces();
static int countConcepts();
static int countAnnotatedClasses(int *cp,ClassDef::CompoundType ct);
static void countRelatedPages(int &docPages,int &indexPages);
struct Index::Private
{
int annotatedClasses = 0;
int annotatedClassesPrinted = 0;
int hierarchyClasses = 0;
int annotatedInterfaces = 0;
int annotatedInterfacesPrinted = 0;
int hierarchyInterfaces = 0;
int annotatedStructs = 0;
int annotatedStructsPrinted = 0;
int annotatedExceptions = 0;
int annotatedExceptionsPrinted = 0;
int hierarchyExceptions = 0;
int documentedGroups = 0;
int documentedNamespaces = 0;
int documentedConcepts = 0;
int documentedModules = 0;
int indexedPages = 0;
int documentedFiles = 0;
int documentedPages = 0;
int documentedDirs = 0;
std::array<int, ClassMemberHighlight::Total> documentedClassMembers = {};
std::array<int, FileMemberHighlight::Total> documentedFileMembers = {};
std::array<int,NamespaceMemberHighlight::Total> documentedNamespaceMembers = {};
std::array<int, ModuleMemberHighlight::Total> documentedModuleMembers = {};
std::array<MemberIndexMap,ClassMemberHighlight::Total> classIndexLetterUsed;
std::array<MemberIndexMap,FileMemberHighlight::Total> fileIndexLetterUsed;
std::array<MemberIndexMap,NamespaceMemberHighlight::Total> namespaceIndexLetterUsed;
std::array<MemberIndexMap,ModuleMemberHighlight::Total> moduleIndexLetterUsed;
};
Index::Index() : p(std::make_unique<Private>())
{
}
Index::~Index() = default;
Index &Index::instance()
{
static Index index;
return index;
}
int Index::numAnnotatedClasses() const { return p->annotatedClasses; }
int Index::numAnnotatedClassesPrinted() const { return p->annotatedClassesPrinted; }
int Index::numHierarchyClasses() const { return p->hierarchyClasses; }
int Index::numAnnotatedInterfaces() const { return p->annotatedInterfaces; }
int Index::numAnnotatedInterfacesPrinted() const { return p->annotatedInterfacesPrinted; }
int Index::numHierarchyInterfaces() const { return p->hierarchyInterfaces; }
int Index::numAnnotatedStructs() const { return p->annotatedStructs; }
int Index::numAnnotatedStructsPrinted() const { return p->annotatedStructsPrinted; }
int Index::numAnnotatedExceptions() const { return p->annotatedExceptions; }
int Index::numAnnotatedExceptionsPrinted() const { return p->annotatedExceptionsPrinted; }
int Index::numHierarchyExceptions() const { return p->hierarchyExceptions; }
int Index::numDocumentedGroups() const { return p->documentedGroups; }
int Index::numDocumentedNamespaces() const { return p->documentedNamespaces; }
int Index::numDocumentedConcepts() const { return p->documentedConcepts; }
int Index::numDocumentedModules() const { return p->documentedModules; }
int Index::numIndexedPages() const { return p->indexedPages; }
int Index::numDocumentedFiles() const { return p->documentedFiles; }
int Index::numDocumentedPages() const { return p->documentedPages; }
int Index::numDocumentedDirs() const { return p->documentedDirs; }
int Index::numDocumentedClassMembers(ClassMemberHighlight::Enum e) const { return p->documentedClassMembers[e]; }
int Index::numDocumentedFileMembers(FileMemberHighlight::Enum e) const { return p->documentedFileMembers[e]; }
int Index::numDocumentedNamespaceMembers(NamespaceMemberHighlight::Enum e) const { return p->documentedNamespaceMembers[e]; }
int Index::numDocumentedModuleMembers(ModuleMemberHighlight::Enum e) const { return p->documentedModuleMembers[e]; }
Index::MemberIndexMap Index::isClassIndexLetterUsed(ClassMemberHighlight::Enum e) const
{
return p->classIndexLetterUsed[static_cast<int>(e)];
}
Index::MemberIndexMap Index::isFileIndexLetterUsed(FileMemberHighlight::Enum e) const
{
return p->fileIndexLetterUsed[static_cast<int>(e)];
}
Index::MemberIndexMap Index::isNamespaceIndexLetterUsed(NamespaceMemberHighlight::Enum e) const
{
return p->namespaceIndexLetterUsed[static_cast<int>(e)];
}
Index::MemberIndexMap Index::isModuleIndexLetterUsed(ModuleMemberHighlight::Enum e) const
{
return p->moduleIndexLetterUsed[static_cast<int>(e)];
}
void Index::resetDocumentedClassMembers(int i)
{
p->documentedClassMembers[i]=0;
p->classIndexLetterUsed[i].clear();
}
void Index::resetDocumentedFileMembers(int i)
{
p->documentedFileMembers[i]=0;
p->fileIndexLetterUsed[i].clear();
}
void Index::resetDocumentedNamespaceMembers(int i)
{
p->documentedNamespaceMembers[i]=0;
p->namespaceIndexLetterUsed[i].clear();
}
void Index::resetDocumentedModuleMembers(int i)
{
p->documentedModuleMembers[i]=0;
p->moduleIndexLetterUsed[i].clear();
}
static void MemberIndexMap_add(Index::MemberIndexMap &map,const std::string &letter,const MemberDef *md)
{
auto it = map.find(letter);
if (it!=map.end())
{
it->second.push_back(md);
}
else
{
map.emplace(letter,std::vector<const MemberDef*>({md}));
}
}
void Index::incrementDocumentedClassMembers(int i,const std::string &letter,const MemberDef *md)
{
p->documentedClassMembers[i]++;
MemberIndexMap_add(p->classIndexLetterUsed[i],letter,md);
}
void Index::incrementDocumentedFileMembers(int i,const std::string &letter,const MemberDef *md)
{
p->documentedFileMembers[i]++;
MemberIndexMap_add(p->fileIndexLetterUsed[i],letter,md);
}
void Index::incrementDocumentedNamespaceMembers(int i,const std::string &letter,const MemberDef *md)
{
p->documentedNamespaceMembers[i]++;
MemberIndexMap_add(p->namespaceIndexLetterUsed[i],letter,md);
}
void Index::incrementDocumentedModuleMembers(int i,const std::string &letter,const MemberDef *md)
{
p->documentedModuleMembers[i]++;
MemberIndexMap_add(p->moduleIndexLetterUsed[i],letter,md);
}
void Index::sortMemberIndexLists()
{
auto sortMemberIndexList = [](MemberIndexMap &map)
{
for (auto &[name,list] : map)
{
std::stable_sort(list.begin(),list.end(),
[](const MemberDef *md1,const MemberDef *md2)
{
// consider candidates A::a, B::b, B::a, A::b, A::A, B::B,
// want after sorting: A::A, A::a, B::a, B::B, A::b, B::b
// so we can later group entries
// - A: A
// - a: A, B
// - B: B
// - b: A, B
int result = qstricmp_sort(md1->name(),md2->name());
if (result==0) // next compare with full scope
{
result = qstricmp_sort(md1->qualifiedName(),md2->qualifiedName());
}
return result<0;
});
}
};
for (auto &idx : p->classIndexLetterUsed)
{
sortMemberIndexList(idx);
}
for (auto &idx : p->fileIndexLetterUsed)
{
sortMemberIndexList(idx);
}
for (auto &idx : p->namespaceIndexLetterUsed)
{
sortMemberIndexList(idx);
}
for (auto &idx : p->moduleIndexLetterUsed)
{
sortMemberIndexList(idx);
}
}
void Index::countDataStructures()
{
for (int j=0;j<ClassMemberHighlight::Total;j++)
{
resetDocumentedClassMembers(j);
}
for (int j=0;j<NamespaceMemberHighlight::Total;j++)
{
resetDocumentedNamespaceMembers(j);
}
for (int j=0;j<FileMemberHighlight::Total;j++)
{
resetDocumentedFileMembers(j);
}
for (int j=0;j<ModuleMemberHighlight::Total;j++)
{
resetDocumentedModuleMembers(j);
}
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
p->annotatedClasses = countAnnotatedClasses(&p->annotatedClassesPrinted, ClassDef::Class); // "classes" + "annotated"
p->hierarchyClasses = countClassHierarchy(ClassDef::Class); // "hierarchy"
// "interfaces" + "annotated"
p->annotatedInterfaces = sliceOpt ? countAnnotatedClasses(&p->annotatedInterfacesPrinted, ClassDef::Interface) : 0;
// "interfacehierarchy"
p->hierarchyInterfaces = sliceOpt ? countClassHierarchy(ClassDef::Interface) : 0;
// "structs" + "annotated"
p->annotatedStructs = sliceOpt ? countAnnotatedClasses(&p->annotatedStructsPrinted, ClassDef::Struct) : 0;
// "exceptions" + "annotated"
p->annotatedExceptions = sliceOpt ? countAnnotatedClasses(&p->annotatedExceptionsPrinted, ClassDef::Exception) : 0;
// "exceptionhierarchy"
p->hierarchyExceptions = sliceOpt ? countClassHierarchy(ClassDef::Exception) : 0;
countFiles(p->documentedFiles,p->documentedFiles); // "files"
countRelatedPages(p->documentedPages,p->indexedPages); // "pages"
p->documentedGroups = countGroups(); // "topics"
p->documentedNamespaces = countNamespaces(); // "namespaces"
p->documentedConcepts = countConcepts(); // "concepts"
p->documentedDirs = countDirs(); // "dirs"
p->documentedModules = ModuleManager::instance().numDocumentedModules();
// "globals"
// "namespacemembers"
// "functions"
}
static void startIndexHierarchy(OutputList &ol,int level)
{
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.disable(OutputType::Html);
if (level<6) ol.startIndexList();
ol.popGeneratorState();
ol.pushGeneratorState();
ol.disable(OutputType::Latex);
ol.disable(OutputType::RTF);
ol.disable(OutputType::Docbook);
ol.startItemList();
ol.popGeneratorState();
}
static void endIndexHierarchy(OutputList &ol,int level)
{
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.disable(OutputType::Html);
if (level<6) ol.endIndexList();
ol.popGeneratorState();
ol.pushGeneratorState();
ol.disable(OutputType::Latex);
ol.disable(OutputType::Docbook);
ol.disable(OutputType::RTF);
ol.endItemList();
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
const int maxItemsBeforeQuickIndex = MAX_ITEMS_BEFORE_QUICK_INDEX;
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
static void startQuickIndexList(OutputList &ol,bool letterTabs=FALSE)
{
if (letterTabs)
{
ol.writeString(" <div id=\"navrow4\" class=\"tabs3\">\n");
}
else
{
ol.writeString(" <div id=\"navrow3\" class=\"tabs2\">\n");
}
ol.writeString(" <ul class=\"tablist\">\n");
}
static void endQuickIndexList(OutputList &ol)
{
ol.writeString(" </ul>\n");
ol.writeString(" </div>\n");
}
static void startQuickIndexItem(OutputList &ol,const QCString &l,
bool hl,bool /* compact */,bool &first)
{
first=FALSE;
ol.writeString(" <li");
if (hl) ol.writeString(" class=\"current\"");
ol.writeString("><a ");
ol.writeString("href=\"");
ol.writeString(l);
ol.writeString("\">");
ol.writeString("<span>");
}
static void endQuickIndexItem(OutputList &ol)
{
ol.writeString("</span>");
ol.writeString("</a>");
ol.writeString("</li>\n");
}
void startTitle(OutputList &ol,const QCString &fileName,const DefinitionMutable *def)
{
ol.startHeaderSection();
if (def) def->writeSummaryLinks(ol);
ol.startTitleHead(fileName);
ol.pushGeneratorState();
ol.disable(OutputType::Man);
}
void endTitle(OutputList &ol,const QCString &fileName,const QCString &name)
{
ol.popGeneratorState();
ol.endTitleHead(fileName,name);
ol.endHeaderSection();
}
void startFile(OutputList &ol,const QCString &name,const QCString &manName,
const QCString &title,HighlightedItem hli,bool additionalIndices,
const QCString &altSidebarName, int hierarchyLevel)
{
bool disableIndex = Config_getBool(DISABLE_INDEX);
ol.startFile(name,manName,title,hierarchyLevel);
ol.startQuickIndices();
if (!disableIndex)
{
ol.writeQuickLinks(hli,name);
}
if (!additionalIndices)
{
ol.endQuickIndices();
}
ol.writeSplitBar(!altSidebarName.isEmpty() ? altSidebarName : name);
ol.writeSearchInfo();
}
void endFile(OutputList &ol,bool skipNavIndex,bool skipEndContents,
const QCString &navPath)
{
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
if (!skipNavIndex)
{
if (!skipEndContents) ol.endContents();
if (generateTreeView)
{
ol.writeString("</div><!-- doc-content -->\n");
}
}
ol.writeFooter(navPath); // write the footer
ol.popGeneratorState();
ol.endFile();
}
void endFileWithNavPath(OutputList &ol,const Definition *d)
{
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
QCString navPath;
if (generateTreeView)
{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.writeString("</div><!-- doc-content -->\n");
ol.popGeneratorState();
navPath = d->navigationPathAsString();
}
endFile(ol,generateTreeView,TRUE,navPath);
}
//----------------------------------------------------------------------
static void writeMemberToIndex(const Definition *def,const MemberDef *md,bool addToIndex)
{
bool isAnonymous = md->isAnonymous();
bool hideUndocMembers = Config_getBool(HIDE_UNDOC_MEMBERS);
const MemberVector &enumList = md->enumFieldList();
bool isDir = !enumList.empty() && md->isEnumerate();
auto defType = def->definitionType();
bool namespaceMemberInFileDocs = md->getNamespaceDef() && defType==Definition::TypeFile;
bool lAddToIndex = addToIndex && !namespaceMemberInFileDocs;
QCString name = namespaceMemberInFileDocs || defType==Definition::TypeModule ?
md->qualifiedName() : md->name();
if (md->getOuterScope()==def ||
(md->getNamespaceDef()!=nullptr && defType==Definition::TypeFile) ||
md->getOuterScope()==Doxygen::globalScope)
{
Doxygen::indexList->addContentsItem(isDir,
name,md->getReference(),md->getOutputFileBase(),md->anchor(),FALSE,lAddToIndex && md->getGroupDef()==nullptr);
}
else // inherited member
{
Doxygen::indexList->addContentsItem(isDir,
name,def->getReference(),def->getOutputFileBase(),md->anchor(),FALSE,lAddToIndex && md->getGroupDef()==nullptr);
}
if (isDir)
{
if (!isAnonymous)
{
Doxygen::indexList->incContentsDepth();
}
for (const auto &emd : enumList)
{
if (!hideUndocMembers || emd->hasDocumentation())
{
namespaceMemberInFileDocs = emd->getNamespaceDef() && defType==Definition::TypeFile;
lAddToIndex = addToIndex && !namespaceMemberInFileDocs;
QCString ename = namespaceMemberInFileDocs || defType==Definition::TypeModule ?
emd->qualifiedName() : emd->name();
if (emd->getOuterScope()==def ||
(emd->getNamespaceDef()!=nullptr && defType==Definition::TypeFile) ||
emd->getOuterScope()==Doxygen::globalScope)
{
Doxygen::indexList->addContentsItem(FALSE,
ename,emd->getReference(),emd->getOutputFileBase(),emd->anchor(),FALSE,lAddToIndex && emd->getGroupDef()==nullptr);
}
else // inherited member
{
Doxygen::indexList->addContentsItem(FALSE,
ename,def->getReference(),def->getOutputFileBase(),emd->anchor(),FALSE,lAddToIndex && emd->getGroupDef()==nullptr);
}
}
}
if (!isAnonymous)
{
Doxygen::indexList->decContentsDepth();
}
}
}
//----------------------------------------------------------------------
template<class T>
void addMembersToIndex(T *def,LayoutDocManager::LayoutPart part,
const QCString &name,const QCString &anchor,
bool addToIndex=TRUE,bool preventSeparateIndex=FALSE,
const ConceptLinkedRefMap *concepts = nullptr)
{
int numClasses=0;
for (const auto &cd : def->getClasses())
{
if (cd->isLinkable()) numClasses++;
}
int numConcepts=0;
if (concepts)
{
for (const auto &cd : *concepts)
{
if (cd->isLinkable()) numConcepts++;
}
}
bool hasMembers = !def->getMemberLists().empty() || !def->getMemberGroups().empty() || (numClasses>0) || (numConcepts>0);
Doxygen::indexList->addContentsItem(hasMembers,name,
def->getReference(),def->getOutputFileBase(),anchor,
hasMembers && !preventSeparateIndex,
addToIndex,
def);
//printf("addMembersToIndex(def=%s hasMembers=%d numClasses=%d)\n",qPrint(def->name()),hasMembers,numClasses);
if (hasMembers || numClasses>0 || numConcepts>0)
{
Doxygen::indexList->incContentsDepth();
for (const auto &lde : LayoutDocManager::instance().docEntries(part))
{
auto kind = lde->kind();
if (kind==LayoutDocEntry::MemberDef)
{
const LayoutDocEntryMemberDef *lmd = dynamic_cast<const LayoutDocEntryMemberDef*>(lde.get());
if (lmd)
{
MemberList *ml = def->getMemberList(lmd->type);
if (ml)
{
for (const auto &md : *ml)
{
if (md->visibleInIndex())
{
writeMemberToIndex(def,md,addToIndex);
}
}
}
}
}
else if (kind==LayoutDocEntry::NamespaceClasses ||
kind==LayoutDocEntry::FileClasses ||
kind==LayoutDocEntry::ClassNestedClasses ||
kind==LayoutDocEntry::ModuleClasses
)
{
for (const auto &cd : def->getClasses())
{
if (cd->isLinkable() && (cd->partOfGroups().empty() || def->definitionType()==Definition::TypeGroup))
{
bool inlineSimpleStructs = Config_getBool(INLINE_SIMPLE_STRUCTS);
bool isNestedClass = def->definitionType()==Definition::TypeClass;
addMembersToIndex(cd,LayoutDocManager::Class,cd->displayName(lde->kind()==LayoutDocEntry::FileClasses),cd->anchor(),
addToIndex && (isNestedClass || (cd->isSimple() && inlineSimpleStructs)),
preventSeparateIndex || cd->isEmbeddedInOuterScope());
}
}
}
else if ((kind==LayoutDocEntry::FileConcepts || kind==LayoutDocEntry::ModuleConcepts) && concepts)
{
for (const auto &cd : *concepts)
{
if (cd->isLinkable() && (cd->partOfGroups().empty() || def->definitionType()==Definition::TypeGroup))
{
Doxygen::indexList->addContentsItem(false,cd->displayName(),
cd->getReference(),cd->getOutputFileBase(),QCString(),
addToIndex,
false,
cd);
}
}
}
}
Doxygen::indexList->decContentsDepth();
}
}
//----------------------------------------------------------------------------
/*! Generates HTML Help tree of classes */
static void writeClassTreeToOutput(OutputList &ol,const BaseClassList &bcl,int level,FTVHelp* ftv,bool addToIndex,ClassDefSet &visitedClasses)
{
if (bcl.empty()) return;
bool started=FALSE;
for (const auto &bcd : bcl)
{
ClassDef *cd=bcd.classDef;
if (cd->getLanguage()==SrcLangExt::VHDL && VhdlDocGen::convert(cd->protection())!=VhdlDocGen::ENTITYCLASS)
{
continue;
}
bool b = cd->getLanguage()==SrcLangExt::VHDL ? classHasVisibleRoot(cd->subClasses()) : classHasVisibleRoot(cd->baseClasses());
if (cd->isVisibleInHierarchy() && b) // classHasVisibleRoot(cd->baseClasses()))
{
if (!started)
{
startIndexHierarchy(ol,level);
if (addToIndex)
{
Doxygen::indexList->incContentsDepth();
}
if (ftv)
{
ftv->incContentsDepth();
}
started=TRUE;
}
ol.startIndexListItem();
//printf("Passed...\n");
bool hasChildren = visitedClasses.find(cd)==visitedClasses.end() &&
classHasVisibleChildren(cd);
//printf("tree4: Has children %s: %d\n",qPrint(cd->name()),hasChildren);
if (cd->isLinkable())
{
//printf("Writing class %s\n",qPrint(cd->displayName()));
ol.startIndexItem(cd->getReference(),cd->getOutputFileBase());
ol.parseText(cd->displayName());
ol.endIndexItem(cd->getReference(),cd->getOutputFileBase());
if (cd->isReference())
{
ol.startTypewriter();
ol.docify(" [external]");
ol.endTypewriter();
}
if (addToIndex)
{
Doxygen::indexList->addContentsItem(hasChildren,cd->displayName(),cd->getReference(),cd->getOutputFileBase(),cd->anchor());
}
if (ftv)
{
if (cd->getLanguage()==SrcLangExt::VHDL)
{
ftv->addContentsItem(hasChildren,bcd.usedName,cd->getReference(),cd->getOutputFileBase(),cd->anchor(),FALSE,FALSE,cd);
}
else
{
ftv->addContentsItem(hasChildren,cd->displayName(),cd->getReference(),cd->getOutputFileBase(),cd->anchor(),FALSE,FALSE,cd);
}
}
}
else
{
ol.startIndexItem(QCString(),QCString());
ol.parseText(cd->name());
ol.endIndexItem(QCString(),QCString());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(hasChildren,cd->displayName(),QCString(),QCString(),QCString());
}
if (ftv)
{
ftv->addContentsItem(hasChildren,cd->displayName(),QCString(),QCString(),QCString(),FALSE,FALSE,cd);
}
}
if (hasChildren)
{
//printf("Class %s at %p visited=%d\n",qPrint(cd->name()),cd,cd->visited);
visitedClasses.insert(cd);
if (cd->getLanguage()==SrcLangExt::VHDL)
{
writeClassTreeToOutput(ol,cd->baseClasses(),level+1,ftv,addToIndex,visitedClasses);
}
else
{
writeClassTreeToOutput(ol,cd->subClasses(),level+1,ftv,addToIndex,visitedClasses);
}
}
ol.endIndexListItem();
}
}
if (started)
{
endIndexHierarchy(ol,level);
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
if (ftv)
{
ftv->decContentsDepth();
}
}
}
//----------------------------------------------------------------------------
static bool dirHasVisibleChildren(const DirDef *dd)
{
if (dd->hasDocumentation()) return TRUE;
for (const auto &fd : dd->getFiles())
{
bool genSourceFile = false;
if (fileVisibleInIndex(fd,genSourceFile))
{
return TRUE;
}
if (genSourceFile)
{
return TRUE;
}
}
for(const auto &subdd : dd->subDirs())
{
if (dirHasVisibleChildren(subdd))
{
return TRUE;
}
}
return FALSE;
}
//----------------------------------------------------------------------------
static void writeDirTreeNode(OutputList &ol, const DirDef *dd, int level, FTVHelp* ftv,bool addToIndex)
{
if (level>20)
{
warn(dd->getDefFileName(),dd->getDefLine(),
"maximum nesting level exceeded for directory %s: "
"check for possible recursive directory relation!",qPrint(dd->name())
);
return;
}
if (!dirHasVisibleChildren(dd))
{
return;
}
bool tocExpand = TRUE; //Config_getBool(TOC_EXPAND);
bool isDir = !dd->subDirs().empty() || // there are subdirs
(tocExpand && // or toc expand and
!dd->getFiles().empty() // there are files
);
//printf("gd='%s': pageDict=%d\n",qPrint(gd->name()),gd->pageDict->count());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(isDir,dd->shortName(),dd->getReference(),dd->getOutputFileBase(),QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
if (ftv)
{
ftv->addContentsItem(isDir,dd->shortName(),dd->getReference(),
dd->getOutputFileBase(),QCString(),FALSE,TRUE,dd);
ftv->incContentsDepth();
}
ol.startIndexListItem();
ol.startIndexItem(dd->getReference(),dd->getOutputFileBase());
ol.parseText(dd->shortName());
ol.endIndexItem(dd->getReference(),dd->getOutputFileBase());
if (dd->isReference())
{
ol.startTypewriter();
ol.docify(" [external]");
ol.endTypewriter();
}
// write sub directories
if (dd->subDirs().size()>0)
{
startIndexHierarchy(ol,level+1);
for(const auto &subdd : dd->subDirs())
{
writeDirTreeNode(ol,subdd,level+1,ftv,addToIndex);
}
endIndexHierarchy(ol,level+1);
}
int fileCount=0;
if (!dd->getFiles().empty())
{
for (const auto &fd : dd->getFiles())
{
//bool allExternals = Config_getBool(ALLEXTERNALS);
//if ((allExternals && fd->isLinkable()) || fd->isLinkableInProject())
//{
// fileCount++;
//}
bool genSourceFile = false;
if (fileVisibleInIndex(fd,genSourceFile))
{
fileCount++;
}
else if (genSourceFile)
{
fileCount++;
}
}
if (fileCount>0)
{
startIndexHierarchy(ol,level+1);
for (const auto &fd : dd->getFiles())
{
bool src = false;
bool doc = fileVisibleInIndex(fd,src);
QCString reference;
QCString outputBase;
if (doc)
{
reference = fd->getReference();
outputBase = fd->getOutputFileBase();
}
if (doc || src)
{
ol.startIndexListItem();
ol.startIndexItem(reference,outputBase);
ol.parseText(fd->displayName());
ol.endIndexItem(reference,outputBase);
ol.endIndexListItem();
if (ftv && (src || doc))
{
ftv->addContentsItem(FALSE,
fd->displayName(),
reference,outputBase,
QCString(),FALSE,FALSE,fd);
}
}
}
endIndexHierarchy(ol,level+1);
}
}
if (tocExpand && addToIndex)
{
// write files of this directory
if (fileCount>0)
{
for (const auto &fd : dd->getFiles())
{
bool src = false;
bool doc = fileVisibleInIndex(fd,src);
if (doc)
{
addMembersToIndex(fd,LayoutDocManager::File,fd->displayName(),QCString(),
!fd->isLinkableViaGroup(),FALSE,&fd->getConcepts());
}
else if (src)
{
Doxygen::indexList->addContentsItem(
FALSE, fd->name(), QCString(),
fd->getSourceFileBase(), QCString(), FALSE, TRUE, fd);
}
}
}
}
ol.endIndexListItem();
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
if (ftv)
{
ftv->decContentsDepth();
}
}
static void writeDirHierarchy(OutputList &ol, FTVHelp* ftv,bool addToIndex)
{
if (ftv)
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
}
startIndexHierarchy(ol,0);
for (const auto &dd : *Doxygen::dirLinkedMap)
{
if (dd->getOuterScope()==Doxygen::globalScope)
{
writeDirTreeNode(ol,dd.get(),0,ftv,addToIndex);
}
}
if (ftv)
{
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->getDirDef()==nullptr) // top level file
{
bool src = false;
bool doc = fileVisibleInIndex(fd.get(),src);
QCString reference, outputBase;
if (doc)
{
reference = fd->getReference();
outputBase = fd->getOutputFileBase();
}
if (doc || src)
{
ftv->addContentsItem(FALSE,fd->displayName(),
reference, outputBase, QCString(),
FALSE,FALSE,fd.get());
}
if (addToIndex)
{
if (doc)
{
addMembersToIndex(fd.get(),LayoutDocManager::File,fd->displayName(),QCString(),TRUE,FALSE,&fd->getConcepts());
}
else if (src)
{
Doxygen::indexList->addContentsItem(
FALSE, fd->displayName(), QCString(),
fd->getSourceFileBase(), QCString(), FALSE, TRUE, fd.get());
}
}
}
}
}
}
endIndexHierarchy(ol,0);
if (ftv)
{
ol.popGeneratorState();
}
}
//----------------------------------------------------------------------------
static void writeClassTreeForList(OutputList &ol,const ClassLinkedMap &cl,bool &started,FTVHelp* ftv,bool addToIndex,
ClassDef::CompoundType ct,ClassDefSet &visitedClasses)
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
for (const auto &cd : cl)
{
//printf("class %s classHasVisibleRoot=%d isVisibleInHierarchy=%d\n",
// qPrint(cd->name()),
// classHasVisibleRoot(cd->baseClasses()),
// cd->isVisibleInHierarchy()
// );
bool b = false;
if (cd->getLanguage()==SrcLangExt::VHDL)
{
if (VhdlDocGen::convert(cd->protection())!=VhdlDocGen::ENTITYCLASS)
{
continue;
}
b=!classHasVisibleRoot(cd->subClasses());
}
else if (sliceOpt && cd->compoundType() != ct)
{
continue;
}
else
{
b=!classHasVisibleRoot(cd->baseClasses());
}
if (b) //filter on root classes
{
if (cd->isVisibleInHierarchy()) // should it be visible
{
if (!started)
{
startIndexHierarchy(ol,0);
if (addToIndex)
{
Doxygen::indexList->incContentsDepth();
}
started=TRUE;
}
ol.startIndexListItem();
bool hasChildren = visitedClasses.find(cd.get())==visitedClasses.end() &&
classHasVisibleChildren(cd.get());
//printf("list: Has children %s: %d\n",qPrint(cd->name()),hasChildren);
if (cd->isLinkable())
{
//printf("Writing class %s isLinkable()=%d isLinkableInProject()=%d cd->isImplicitTemplateinstance()=%d\n",
// qPrint(cd->displayName()),cd->isLinkable(),cd->isLinkableInProject(),cd->isImplicitTemplateInstance());
ol.startIndexItem(cd->getReference(),cd->getOutputFileBase());
ol.parseText(cd->displayName());
ol.endIndexItem(cd->getReference(),cd->getOutputFileBase());
if (cd->isReference())
{
ol.startTypewriter();
ol.docify(" [external]");
ol.endTypewriter();
}
if (addToIndex)
{
if (cd->getLanguage()!=SrcLangExt::VHDL) // prevents double insertion in Design Unit List
Doxygen::indexList->addContentsItem(hasChildren,cd->displayName(),cd->getReference(),cd->getOutputFileBase(),cd->anchor(),FALSE,FALSE);
}
if (ftv)
{
ftv->addContentsItem(hasChildren,cd->displayName(),cd->getReference(),cd->getOutputFileBase(),cd->anchor(),FALSE,FALSE,cd.get());
}
}
else
{
ol.startIndexItem(QCString(),QCString());
ol.parseText(cd->displayName());
ol.endIndexItem(QCString(),QCString());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(hasChildren,cd->displayName(),QCString(),QCString(),QCString(),FALSE,FALSE);
}
if (ftv)
{
ftv->addContentsItem(hasChildren,cd->displayName(),QCString(),QCString(),QCString(),FALSE,FALSE,cd.get());
}
}
if (cd->getLanguage()==SrcLangExt::VHDL && hasChildren)
{
writeClassTreeToOutput(ol,cd->baseClasses(),1,ftv,addToIndex,visitedClasses);
visitedClasses.insert(cd.get());
}
else if (hasChildren)
{
writeClassTreeToOutput(ol,cd->subClasses(),1,ftv,addToIndex,visitedClasses);
visitedClasses.insert(cd.get());
}
ol.endIndexListItem();
}
}
}
}
static void writeClassHierarchy(OutputList &ol, FTVHelp* ftv,bool addToIndex,ClassDef::CompoundType ct)
{
ClassDefSet visitedClasses;
if (ftv)
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
}
bool started=FALSE;
writeClassTreeForList(ol,*Doxygen::classLinkedMap,started,ftv,addToIndex,ct,visitedClasses);
writeClassTreeForList(ol,*Doxygen::hiddenClassLinkedMap,started,ftv,addToIndex,ct,visitedClasses);
if (started)
{
endIndexHierarchy(ol,0);
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
if (ftv)
{
ol.popGeneratorState();
}
}
//----------------------------------------------------------------------------
static int countClassesInTreeList(const ClassLinkedMap &cl, ClassDef::CompoundType ct)
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
int count=0;
for (const auto &cd : cl)
{
if (sliceOpt && cd->compoundType() != ct)
{
continue;
}
if (!classHasVisibleRoot(cd->baseClasses())) // filter on root classes
{
if (cd->isVisibleInHierarchy()) // should it be visible
{
if (!cd->subClasses().empty()) // should have sub classes
{
count++;
}
}
}
}
return count;
}
static int countClassHierarchy(ClassDef::CompoundType ct)
{
int count=0;
count+=countClassesInTreeList(*Doxygen::classLinkedMap, ct);
count+=countClassesInTreeList(*Doxygen::hiddenClassLinkedMap, ct);
return count;
}
//----------------------------------------------------------------------------
static void writeHierarchicalIndex(OutputList &ol)
{
if (Index::instance().numHierarchyClasses()==0) return;
ol.pushGeneratorState();
//1.{
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ClassHierarchy);
QCString title = lne ? lne->title() : theTranslator->trClassHierarchy();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"hierarchy",QCString(), title, HighlightedItem::ClassHierarchy);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
if (Config_getBool(HAVE_DOT) && Config_getBool(GRAPHICAL_HIERARCHY))
{
ol.pushGeneratorState();
ol.disable(OutputType::Latex);
ol.disable(OutputType::RTF);
ol.disable(OutputType::Docbook);
ol.startParagraph();
ol.startTextLink("inherits",QCString());
ol.parseText(theTranslator->trGotoGraphicalHierarchy());
ol.endTextLink();
ol.endParagraph();
ol.popGeneratorState();
}
ol.parseText(lne ? lne->intro() : theTranslator->trClassHierarchyDescription());
ol.endTextBlock();
// ---------------
// Static class hierarchy for Latex/RTF
// ---------------
ol.pushGeneratorState();
//2.{
ol.disable(OutputType::Html);
Doxygen::indexList->disable();
writeClassHierarchy(ol,nullptr,addToIndex,ClassDef::Class);
Doxygen::indexList->enable();
ol.popGeneratorState();
//2.}
// ---------------
// Dynamic class hierarchical index for HTML
// ---------------
ol.pushGeneratorState();
//2.{
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"hierarchy",QCString(),TRUE,TRUE);
}
FTVHelp ftv(false);
writeClassHierarchy(ol,&ftv,addToIndex,ClassDef::Class);
TextStream t;
ftv.generateTreeViewInline(t);
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.writeString(t.str().c_str());
ol.popGeneratorState();
}
ol.popGeneratorState();
//2.}
// ------
endFile(ol);
ol.popGeneratorState();
//1.}
}
//----------------------------------------------------------------------------
static void writeGraphicalClassHierarchy(OutputList &ol)
{
if (Index::instance().numHierarchyClasses()==0) return;
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ClassHierarchy);
QCString title = lne ? lne->title() : theTranslator->trClassHierarchy();
startFile(ol,"inherits",QCString(),title,HighlightedItem::ClassHierarchy,FALSE,"hierarchy");
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.startParagraph();
ol.startTextLink("hierarchy",QCString());
ol.parseText(theTranslator->trGotoTextualHierarchy());
ol.endTextLink();
ol.endParagraph();
ol.endTextBlock();
DotGfxHierarchyTable g;
ol.writeGraphicalHierarchy(g);
endFile(ol);
ol.enableAll();
}
//----------------------------------------------------------------------------
static void writeHierarchicalInterfaceIndex(OutputList &ol)
{
if (Index::instance().numHierarchyInterfaces()==0) return;
ol.pushGeneratorState();
//1.{
ol.disable(OutputType::Man);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::InterfaceHierarchy);
QCString title = lne ? lne->title() : theTranslator->trInterfaceHierarchy();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"interfacehierarchy",QCString(), title, HighlightedItem::InterfaceHierarchy);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
if (Config_getBool(HAVE_DOT) && Config_getBool(GRAPHICAL_HIERARCHY))
{
ol.disable(OutputType::Latex);
ol.disable(OutputType::RTF);
ol.startParagraph();
ol.startTextLink("interfaceinherits",QCString());
ol.parseText(theTranslator->trGotoGraphicalHierarchy());
ol.endTextLink();
ol.endParagraph();
ol.enable(OutputType::Latex);
ol.enable(OutputType::RTF);
}
ol.parseText(lne ? lne->intro() : theTranslator->trInterfaceHierarchyDescription());
ol.endTextBlock();
// ---------------
// Static interface hierarchy for Latex/RTF
// ---------------
ol.pushGeneratorState();
//2.{
ol.disable(OutputType::Html);
Doxygen::indexList->disable();
writeClassHierarchy(ol,nullptr,addToIndex,ClassDef::Interface);
Doxygen::indexList->enable();
ol.popGeneratorState();
//2.}
// ---------------
// Dynamic interface hierarchical index for HTML
// ---------------
ol.pushGeneratorState();
//2.{
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"interfacehierarchy",QCString(),TRUE,TRUE);
}
FTVHelp ftv(false);
writeClassHierarchy(ol,&ftv,addToIndex,ClassDef::Interface);
TextStream t;
ftv.generateTreeViewInline(t);
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.writeString(t.str().c_str());
ol.popGeneratorState();
}
ol.popGeneratorState();
//2.}
// ------
endFile(ol);
ol.popGeneratorState();
//1.}
}
//----------------------------------------------------------------------------
static void writeGraphicalInterfaceHierarchy(OutputList &ol)
{
if (Index::instance().numHierarchyInterfaces()==0) return;
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::InterfaceHierarchy);
QCString title = lne ? lne->title() : theTranslator->trInterfaceHierarchy();
startFile(ol,"interfaceinherits",QCString(),title,HighlightedItem::InterfaceHierarchy,FALSE,"interfacehierarchy");
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.startParagraph();
ol.startTextLink("interfacehierarchy",QCString());
ol.parseText(theTranslator->trGotoTextualHierarchy());
ol.endTextLink();
ol.endParagraph();
ol.endTextBlock();
DotGfxHierarchyTable g("interface_",ClassDef::Interface);
ol.writeGraphicalHierarchy(g);
endFile(ol);
ol.enableAll();
}
//----------------------------------------------------------------------------
static void writeHierarchicalExceptionIndex(OutputList &ol)
{
if (Index::instance().numHierarchyExceptions()==0) return;
ol.pushGeneratorState();
//1.{
ol.disable(OutputType::Man);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ExceptionHierarchy);
QCString title = lne ? lne->title() : theTranslator->trExceptionHierarchy();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"exceptionhierarchy",QCString(), title, HighlightedItem::ExceptionHierarchy);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
if (Config_getBool(HAVE_DOT) && Config_getBool(GRAPHICAL_HIERARCHY))
{
ol.disable(OutputType::Latex);
ol.disable(OutputType::RTF);
ol.startParagraph();
ol.startTextLink("exceptioninherits",QCString());
ol.parseText(theTranslator->trGotoGraphicalHierarchy());
ol.endTextLink();
ol.endParagraph();
ol.enable(OutputType::Latex);
ol.enable(OutputType::RTF);
}
ol.parseText(lne ? lne->intro() : theTranslator->trExceptionHierarchyDescription());
ol.endTextBlock();
// ---------------
// Static exception hierarchy for Latex/RTF
// ---------------
ol.pushGeneratorState();
//2.{
ol.disable(OutputType::Html);
Doxygen::indexList->disable();
writeClassHierarchy(ol,nullptr,addToIndex,ClassDef::Exception);
Doxygen::indexList->enable();
ol.popGeneratorState();
//2.}
// ---------------
// Dynamic exception hierarchical index for HTML
// ---------------
ol.pushGeneratorState();
//2.{
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"exceptionhierarchy",QCString(),TRUE,TRUE);
}
FTVHelp ftv(false);
writeClassHierarchy(ol,&ftv,addToIndex,ClassDef::Exception);
TextStream t;
ftv.generateTreeViewInline(t);
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.writeString(t.str().c_str());
ol.popGeneratorState();
}
ol.popGeneratorState();
//2.}
// ------
endFile(ol);
ol.popGeneratorState();
//1.}
}
//----------------------------------------------------------------------------
static void writeGraphicalExceptionHierarchy(OutputList &ol)
{
if (Index::instance().numHierarchyExceptions()==0) return;
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ExceptionHierarchy);
QCString title = lne ? lne->title() : theTranslator->trExceptionHierarchy();
startFile(ol,"exceptioninherits",QCString(),title,HighlightedItem::ExceptionHierarchy,FALSE,"exceptionhierarchy");
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.startParagraph();
ol.startTextLink("exceptionhierarchy",QCString());
ol.parseText(theTranslator->trGotoTextualHierarchy());
ol.endTextLink();
ol.endParagraph();
ol.endTextBlock();
DotGfxHierarchyTable g("exception_",ClassDef::Exception);
ol.writeGraphicalHierarchy(g);
endFile(ol);
ol.enableAll();
}
//----------------------------------------------------------------------------
static void countFiles(int &allFiles,int &docFiles)
{
allFiles=0;
docFiles=0;
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd: *fn)
{
bool src = false;
bool doc = fileVisibleInIndex(fd.get(),src);
if (doc || src)
{
allFiles++;
}
if (doc)
{
docFiles++;
}
}
}
}
static void writeSingleFileIndex(OutputList &ol,const FileDef *fd)
{
//printf("Found filedef %s\n",qPrint(fd->name()));
bool doc = fd->isLinkableInProject();
bool src = fd->generateSourceFile();
bool nameOk = !fd->isDocumentationFile();
if (nameOk && (doc || src) && !fd->isReference())
{
QCString path;
if (Config_getBool(FULL_PATH_NAMES))
{
path=stripFromPath(fd->getPath());
}
QCString fullName=fd->name();
if (!path.isEmpty())
{
if (path.at(path.length()-1)!='/') fullName.prepend("/");
fullName.prepend(path);
}
ol.startIndexKey();
ol.docify(path);
if (doc)
{
ol.writeObjectLink(QCString(),fd->getOutputFileBase(),QCString(),fd->name());
//if (addToIndex)
//{
// addMembersToIndex(fd,LayoutDocManager::File,fullName,QCString());
//}
}
else if (src)
{
ol.writeObjectLink(QCString(),fd->getSourceFileBase(),QCString(),fd->name());
}
if (doc && src)
{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.docify(" ");
ol.startTextLink(fd->includeName(),QCString());
ol.docify("[");
ol.parseText(theTranslator->trCode());
ol.docify("]");
ol.endTextLink();
ol.popGeneratorState();
}
ol.endIndexKey();
bool hasBrief = !fd->briefDescription().isEmpty();
ol.startIndexValue(hasBrief);
if (hasBrief)
{
//ol.docify(" (");
ol.generateDoc(
fd->briefFile(),fd->briefLine(),
fd,nullptr,
fd->briefDescription(TRUE),
FALSE, // index words
FALSE, // isExample
QCString(), // example name
TRUE, // single line
TRUE, // link from index
Config_getBool(MARKDOWN_SUPPORT)
);
//ol.docify(")");
}
if (doc)
{
ol.endIndexValue(fd->getOutputFileBase(),hasBrief);
}
else // src
{
ol.endIndexValue(fd->getSourceFileBase(),hasBrief);
}
//ol.popGeneratorState();
// --------------------------------------------------------
}
}
//----------------------------------------------------------------------------
static void writeFileIndex(OutputList &ol)
{
if (Index::instance().numDocumentedFiles()==0 || !Config_getBool(SHOW_FILES)) return;
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::FileList);
if (lne==nullptr) lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Files); // fall back
QCString title = lne ? lne->title() : theTranslator->trFileList();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"files",QCString(),title,HighlightedItem::Files);
startTitle(ol,QCString());
//if (!Config_getString(PROJECT_NAME).isEmpty())
//{
// title.prepend(Config_getString(PROJECT_NAME)+" ");
//}
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"files",QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
ol.parseText(lne ? lne->intro() : theTranslator->trFileListDescription(Config_getBool(EXTRACT_ALL)));
ol.endTextBlock();
// ---------------
// Flat file index
// ---------------
// 1. {
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.startIndexList();
if (Config_getBool(FULL_PATH_NAMES))
{
std::unordered_map<std::string,size_t> pathMap;
std::vector<FilesInDir> outputFiles;
// re-sort input files in (dir,file) output order instead of (file,dir) input order
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
QCString path=fd->getPath();
if (path.isEmpty()) path="[external]";
auto it = pathMap.find(path.str());
if (it!=pathMap.end()) // existing path -> append
{
outputFiles.at(it->second).files.push_back(fd.get());
}
else // new path -> create path entry + append
{
pathMap.emplace(path.str(),outputFiles.size());
outputFiles.emplace_back(path);
outputFiles.back().files.push_back(fd.get());
}
}
}
// sort the files by path
std::stable_sort(outputFiles.begin(),
outputFiles.end(),
[](const auto &fp1,const auto &fp2) { return qstricmp_sort(fp1.path,fp2.path)<0; });
// sort the files inside the directory by name
for (auto &fp : outputFiles)
{
std::stable_sort(fp.files.begin(), fp.files.end(), compareFileDefs);
}
// write the results
for (const auto &fp : outputFiles)
{
for (const auto &fd : fp.files)
{
writeSingleFileIndex(ol,fd);
}
}
}
else
{
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
writeSingleFileIndex(ol,fd.get());
}
}
}
ol.endIndexList();
// 1. }
ol.popGeneratorState();
// ---------------
// Hierarchical file index for HTML
// ---------------
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{
FTVHelp ftv(false);
writeDirHierarchy(ol,&ftv,addToIndex);
TextStream t;
ftv.generateTreeViewInline(t);
ol.writeString(t.str().c_str());
}
ol.popGeneratorState();
// ------
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
endFile(ol);
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static int countNamespaces()
{
int count=0;
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject()) count++;
}
return count;
}
//----------------------------------------------------------------------------
static int countConcepts()
{
int count=0;
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject()) count++;
}
return count;
}
//----------------------------------------------------------------------------
template<typename Ptr> const ClassDef *get_pointer(const Ptr &p);
template<> const ClassDef *get_pointer(const ClassLinkedMap::Ptr &p) { return p.get(); }
template<> const ClassDef *get_pointer(const ClassLinkedRefMap::Ptr &p) { return p; }
template<class ListType>
static void writeClassTree(const ListType &cl,FTVHelp *ftv,bool addToIndex,bool globalOnly,ClassDef::CompoundType ct)
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
for (const auto &cdi : cl)
{
const ClassDef *cd = get_pointer(cdi);
if (cd->getLanguage()==SrcLangExt::VHDL)
{
if (VhdlDocGen::convert(cd->protection())==VhdlDocGen::PACKAGECLASS ||
VhdlDocGen::convert(cd->protection())==VhdlDocGen::PACKBODYCLASS
)// no architecture
{
continue;
}
}
if (sliceOpt && cd->compoundType() != ct)
{
continue;
}
if (!globalOnly ||
cd->getOuterScope()==nullptr ||
cd->getOuterScope()==Doxygen::globalScope
)
{
int count=0;
for (const auto &ccd : cd->getClasses())
{
if (ccd->isLinkableInProject() && !ccd->isImplicitTemplateInstance())
{
count++;
}
}
if (classVisibleInIndex(cd) && !cd->isImplicitTemplateInstance())
{
if (ftv)
{
ftv->addContentsItem(count>0,cd->displayName(FALSE),cd->getReference(),
cd->getOutputFileBase(),cd->anchor(),FALSE,TRUE,cd);
}
if (addToIndex &&
(cd->getOuterScope()==nullptr ||
cd->getOuterScope()->definitionType()!=Definition::TypeClass
)
)
{
addMembersToIndex(cd,LayoutDocManager::Class,
cd->displayName(FALSE),
cd->anchor(),
cd->partOfGroups().empty() && !cd->isSimple());
}
if (count>0)
{
if (ftv) ftv->incContentsDepth();
writeClassTree(cd->getClasses(),ftv,addToIndex,FALSE,ct);
if (ftv) ftv->decContentsDepth();
}
}
}
}
}
static void writeNamespaceMembers(const NamespaceDef *nd,bool addToIndex)
{
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Namespace))
{
if (lde->kind()==LayoutDocEntry::MemberDef)
{
const LayoutDocEntryMemberDef *lmd = dynamic_cast<const LayoutDocEntryMemberDef*>(lde.get());
if (lmd)
{
MemberList *ml = nd->getMemberList(lmd->type);
if (ml)
{
for (const auto &md : *ml)
{
//printf(" member %s visible=%d\n",qPrint(md->name()),md->visibleInIndex());
if (md->visibleInIndex())
{
writeMemberToIndex(nd,md,addToIndex);
}
}
}
}
}
}
}
static void writeModuleMembers(const ModuleDef *mod,bool addToIndex)
{
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Module))
{
if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
MemberList *ml = mod->getMemberList(lmd->type);
if (ml)
{
for (const auto &md : *ml)
{
//printf(" member %s visible=%d\n",qPrint(md->name()),md->visibleInIndex());
if (md->visibleInIndex())
{
writeMemberToIndex(mod,md,addToIndex);
}
}
}
}
}
}
}
static void writeConceptList(const ConceptLinkedRefMap &concepts, FTVHelp *ftv,bool addToIndex);
static void writeNamespaceTree(const NamespaceLinkedRefMap &nsLinkedMap,FTVHelp *ftv,
bool rootOnly,bool addToIndex);
static void writeNamespaceTreeElement(const NamespaceDef *nd,FTVHelp *ftv,
bool rootOnly,bool addToIndex)
{
if (!nd->isAnonymous() &&
(!rootOnly || nd->getOuterScope()==Doxygen::globalScope))
{
bool hasNestedNamespace = namespaceHasNestedNamespace(nd);
bool hasChildren = hasNestedNamespace ||
namespaceHasNestedClass(nd,false,ClassDef::Class) ||
namespaceHasNestedConcept(nd);
bool isLinkable = nd->isLinkable();
int visibleMembers = nd->countVisibleMembers();
//printf("namespace %s hasChildren=%d visibleMembers=%d\n",qPrint(nd->name()),hasChildren,visibleMembers);
QCString ref;
QCString file;
if (isLinkable)
{
ref = nd->getReference();
file = nd->getOutputFileBase();
if (nd->getLanguage()==SrcLangExt::VHDL) // UGLY HACK
{
file=file.replace(0,qstrlen("namespace"),"class");
}
}
bool isDir = hasChildren || visibleMembers>0;
if (isLinkable || isDir)
{
ftv->addContentsItem(hasNestedNamespace,nd->localName(),ref,file,QCString(),FALSE,nd->partOfGroups().empty(),nd);
if (addToIndex)
{
Doxygen::indexList->addContentsItem(isDir,nd->localName(),ref,file,QCString(),
hasChildren && !file.isEmpty(),nd->partOfGroups().empty());
}
if (addToIndex && isDir)
{
Doxygen::indexList->incContentsDepth();
}
if (isDir)
{
ftv->incContentsDepth();
writeNamespaceTree(nd->getNamespaces(),ftv,FALSE,addToIndex);
writeClassTree(nd->getClasses(),nullptr,addToIndex,FALSE,ClassDef::Class);
writeConceptList(nd->getConcepts(),nullptr,addToIndex);
writeNamespaceMembers(nd,addToIndex);
ftv->decContentsDepth();
}
if (addToIndex && isDir)
{
Doxygen::indexList->decContentsDepth();
}
}
}
}
static void writeNamespaceTree(const NamespaceLinkedRefMap &nsLinkedMap,FTVHelp *ftv,
bool rootOnly,bool addToIndex)
{
for (const auto &nd : nsLinkedMap)
{
if (nd->isVisibleInHierarchy())
{
writeNamespaceTreeElement(nd,ftv,rootOnly,addToIndex);
}
}
}
static void writeNamespaceTree(const NamespaceLinkedMap &nsLinkedMap,FTVHelp *ftv,
bool rootOnly,bool addToIndex)
{
for (const auto &nd : nsLinkedMap)
{
if (nd->isVisibleInHierarchy())
{
writeNamespaceTreeElement(nd.get(),ftv,rootOnly,addToIndex);
}
}
}
static void writeClassTreeInsideNamespace(const NamespaceLinkedRefMap &nsLinkedMap,FTVHelp *ftv,
bool rootOnly,bool addToIndex,ClassDef::CompoundType ct);
static void writeClassTreeInsideNamespaceElement(const NamespaceDef *nd,FTVHelp *ftv,
bool rootOnly,bool addToIndex,ClassDef::CompoundType ct)
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
if (!nd->isAnonymous() &&
(!rootOnly || nd->getOuterScope()==Doxygen::globalScope))
{
bool isDir = namespaceHasNestedClass(nd,sliceOpt,ct);
bool isLinkable = nd->isLinkableInProject();
//printf("writeClassTreeInsideNamespaceElement namespace %s isLinkable=%d isDir=%d\n",qPrint(nd->name()),isLinkable,isDir);
QCString ref;
QCString file;
if (isLinkable)
{
ref = nd->getReference();
file = nd->getOutputFileBase();
if (nd->getLanguage()==SrcLangExt::VHDL) // UGLY HACK
{
file=file.replace(0,qstrlen("namespace"),"class");
}
}
if (isDir)
{
ftv->addContentsItem(isDir,nd->localName(),ref,file,QCString(),FALSE,TRUE,nd);
if (addToIndex)
{
// the namespace entry is already shown under the namespace list so don't
// add it to the nav index and don't create a separate index file for it otherwise
// it will overwrite the one written for the namespace list.
Doxygen::indexList->addContentsItem(isDir,nd->localName(),ref,file,QCString(),
false, // separateIndex
false // addToNavIndex
);
}
if (addToIndex)
{
Doxygen::indexList->incContentsDepth();
}
ftv->incContentsDepth();
writeClassTreeInsideNamespace(nd->getNamespaces(),ftv,FALSE,addToIndex,ct);
ClassLinkedRefMap d = nd->getClasses();
if (sliceOpt)
{
if (ct == ClassDef::Interface)
{
d = nd->getInterfaces();
}
else if (ct == ClassDef::Struct)
{
d = nd->getStructs();
}
else if (ct == ClassDef::Exception)
{
d = nd->getExceptions();
}
}
writeClassTree(d,ftv,addToIndex,FALSE,ct);
ftv->decContentsDepth();
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
}
}
static void writeClassTreeInsideNamespace(const NamespaceLinkedRefMap &nsLinkedMap,FTVHelp *ftv,
bool rootOnly,bool addToIndex,ClassDef::CompoundType ct)
{
for (const auto &nd : nsLinkedMap)
{
writeClassTreeInsideNamespaceElement(nd,ftv,rootOnly,addToIndex,ct);
}
}
static void writeClassTreeInsideNamespace(const NamespaceLinkedMap &nsLinkedMap,FTVHelp *ftv,
bool rootOnly,bool addToIndex,ClassDef::CompoundType ct)
{
for (const auto &nd : nsLinkedMap)
{
writeClassTreeInsideNamespaceElement(nd.get(),ftv,rootOnly,addToIndex,ct);
}
}
static void writeNamespaceIndex(OutputList &ol)
{
if (Index::instance().numDocumentedNamespaces()==0) return;
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::NamespaceList);
if (lne==nullptr) lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Namespaces); // fall back
QCString title = lne ? lne->title() : theTranslator->trNamespaceList();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"namespaces",QCString(),title,HighlightedItem::Namespaces);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.parseText(lne ? lne->intro() : theTranslator->trNamespaceListDescription(Config_getBool(EXTRACT_ALL)));
ol.endTextBlock();
bool first=TRUE;
// ---------------
// Linear namespace index for Latex/RTF
// ---------------
ol.pushGeneratorState();
ol.disable(OutputType::Html);
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject())
{
if (first)
{
ol.startIndexList();
first=FALSE;
}
//ol.writeStartAnnoItem("namespace",nd->getOutputFileBase(),0,nd->name());
ol.startIndexKey();
if (nd->getLanguage()==SrcLangExt::VHDL)
{
ol.writeObjectLink(QCString(), nd->getOutputFileBase().replace(0,qstrlen("namespace"),"class"),QCString(),nd->displayName());
}
else
{
ol.writeObjectLink(QCString(),nd->getOutputFileBase(),QCString(),nd->displayName());
}
ol.endIndexKey();
bool hasBrief = !nd->briefDescription().isEmpty();
ol.startIndexValue(hasBrief);
if (hasBrief)
{
//ol.docify(" (");
ol.generateDoc(
nd->briefFile(),nd->briefLine(),
nd.get(),nullptr,
nd->briefDescription(TRUE),
FALSE, // index words
FALSE, // isExample
QCString(), // example name
TRUE, // single line
TRUE, // link from index
Config_getBool(MARKDOWN_SUPPORT)
);
//ol.docify(")");
}
ol.endIndexValue(nd->getOutputFileBase(),hasBrief);
}
}
if (!first) ol.endIndexList();
ol.popGeneratorState();
// ---------------
// Hierarchical namespace index for HTML
// ---------------
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"namespaces",QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
FTVHelp ftv(false);
writeNamespaceTree(*Doxygen::namespaceLinkedMap,&ftv,TRUE,addToIndex);
TextStream t;
ftv.generateTreeViewInline(t);
ol.writeString(t.str().c_str());
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
ol.popGeneratorState();
// ------
endFile(ol);
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static int countAnnotatedClasses(int *cp, ClassDef::CompoundType ct)
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
int count=0;
int countPrinted=0;
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (sliceOpt && cd->compoundType() != ct)
{
continue;
}
if (cd->isLinkableInProject() && !cd->isImplicitTemplateInstance())
{
if (!cd->isEmbeddedInOuterScope())
{
countPrinted++;
}
count++;
}
}
*cp = countPrinted;
return count;
}
static void writeAnnotatedClassList(OutputList &ol,ClassDef::CompoundType ct)
{
//LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ClassList);
//bool addToIndex = lne==nullptr || lne->visible();
bool first=TRUE;
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->getLanguage()==SrcLangExt::VHDL &&
(VhdlDocGen::convert(cd->protection())==VhdlDocGen::PACKAGECLASS ||
VhdlDocGen::convert(cd->protection())==VhdlDocGen::PACKBODYCLASS)
) // no architecture
{
continue;
}
if (first)
{
ol.startIndexList();
first=FALSE;
}
if (sliceOpt && cd->compoundType() != ct)
{
continue;
}
ol.pushGeneratorState();
if (cd->isEmbeddedInOuterScope())
{
ol.disable(OutputType::Latex);
ol.disable(OutputType::Docbook);
ol.disable(OutputType::RTF);
}
if (cd->isLinkableInProject() && !cd->isImplicitTemplateInstance())
{
ol.startIndexKey();
if (cd->getLanguage()==SrcLangExt::VHDL)
{
QCString prot= VhdlDocGen::getProtectionName(VhdlDocGen::convert(cd->protection()));
ol.docify(prot);
ol.writeString(" ");
}
ol.writeObjectLink(QCString(),cd->getOutputFileBase(),cd->anchor(),cd->displayName());
ol.endIndexKey();
bool hasBrief = !cd->briefDescription().isEmpty();
ol.startIndexValue(hasBrief);
if (hasBrief)
{
ol.generateDoc(
cd->briefFile(),cd->briefLine(),
cd.get(),nullptr,
cd->briefDescription(TRUE),
FALSE, // indexWords
FALSE, // isExample
QCString(), // example name
TRUE, // single line
TRUE, // link from index
Config_getBool(MARKDOWN_SUPPORT)
);
}
ol.endIndexValue(cd->getOutputFileBase(),hasBrief);
//if (addToIndex)
//{
// addMembersToIndex(cd,LayoutDocManager::Class,cd->displayName(),cd->anchor());
//}
}
ol.popGeneratorState();
}
if (!first) ol.endIndexList();
}
inline bool isId1(int c)
{
return (c<127 && c>31); // printable ASCII character
}
static QCString letterToLabel(const QCString &startLetter)
{
if (startLetter.isEmpty()) return startLetter;
const char *p = startLetter.data();
char c = *p;
QCString result;
if (isId1(c))
{
result+=c;
}
else
{
result="0x";
const char hex[]="0123456789abcdef";
while ((c=*p++))
{
result+=hex[static_cast<unsigned char>(c)>>4];
result+=hex[static_cast<unsigned char>(c)&0xf];
}
}
return result;
}
//----------------------------------------------------------------------------
/** Class representing a cell in the alphabetical class index. */
class AlphaIndexTableCell
{
public:
AlphaIndexTableCell(int row,int col,const std::string &letter,const ClassDef *cd) :
m_letter(letter), m_class(cd), m_row(row), m_col(col)
{
}
const ClassDef *classDef() const { return m_class; }
std::string letter() const { return m_letter; }
int row() const { return m_row; }
int column() const { return m_col; }
private:
std::string m_letter;
const ClassDef *m_class;
int m_row;
int m_col;
};
using UsedIndexLetters = std::set<std::string>;
// write an alphabetical index of all class with a header for each letter
static void writeAlphabeticalClassList(OutputList &ol, ClassDef::CompoundType ct, int /* annotatedCount */)
{
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
// What starting letters are used
UsedIndexLetters indexLettersUsed;
// first count the number of headers
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (sliceOpt && cd->compoundType() != ct)
continue;
if (cd->isLinkableInProject() && !cd->isImplicitTemplateInstance())
{
if (cd->getLanguage()==SrcLangExt::VHDL && !(VhdlDocGen::convert(cd->protection())==VhdlDocGen::ENTITYCLASS ))// no architecture
continue;
// get the first UTF8 character (after the part that should be ignored)
int index = getPrefixIndex(cd->className());
std::string letter = getUTF8CharAt(cd->className().str(),index);
if (!letter.empty())
{
indexLettersUsed.insert(convertUTF8ToUpper(letter));
}
}
}
// write quick link index (row of letters)
QCString alphaLinks = "<div class=\"qindex\">";
bool first=true;
for (const auto &letter : indexLettersUsed)
{
if (!first) alphaLinks += " | ";
first=false;
QCString li = letterToLabel(letter.c_str());
alphaLinks += "<a class=\"qindex\" href=\"#letter_" +
li + "\">" +
QCString(letter) + "</a>";
}
alphaLinks += "</div>\n";
ol.writeString(alphaLinks);
std::map<std::string, std::vector<const ClassDef*> > classesByLetter;
// fill the columns with the class list (row elements in each column,
// expect for the columns with number >= itemsInLastRow, which get one
// item less.
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (sliceOpt && cd->compoundType() != ct)
continue;
if (cd->getLanguage()==SrcLangExt::VHDL && !(VhdlDocGen::convert(cd->protection())==VhdlDocGen::ENTITYCLASS ))// no architecture
continue;
if (cd->isLinkableInProject() && !cd->isImplicitTemplateInstance())
{
QCString className = cd->className();
int index = getPrefixIndex(className);
std::string letter = getUTF8CharAt(className.str(),index);
if (!letter.empty())
{
letter = convertUTF8ToUpper(letter);
auto it = classesByLetter.find(letter);
if (it!=classesByLetter.end()) // add class to the existing list
{
it->second.push_back(cd.get());
}
else // new entry
{
classesByLetter.emplace(letter, std::vector<const ClassDef*>({ cd.get() }));
}
}
}
}
// sort the class lists per letter while ignoring the prefix
for (auto &[letter,list] : classesByLetter)
{
std::stable_sort(list.begin(), list.end(),
[](const auto &c1,const auto &c2)
{
QCString n1 = c1->className();
QCString n2 = c2->className();
return qstricmp_sort(n1.data()+getPrefixIndex(n1), n2.data()+getPrefixIndex(n2))<0;
});
}
// generate table
if (!classesByLetter.empty())
{
ol.writeString("<div class=\"classindex\">\n");
int counter=0;
for (const auto &cl : classesByLetter)
{
QCString parity = (counter++%2)==0 ? "even" : "odd";
ol.writeString("<dl class=\"classindex " + parity + "\">\n");
// write character heading
ol.writeString("<dt class=\"alphachar\">");
QCString s = letterToLabel(cl.first.c_str());
ol.writeString("<a id=\"letter_");
ol.writeString(s);
ol.writeString("\" name=\"letter_");
ol.writeString(s);
ol.writeString("\">");
ol.writeString(cl.first.c_str());
ol.writeString("</a>");
ol.writeString("</dt>\n");
// write class links
for (const auto &cd : cl.second)
{
ol.writeString("<dd>");
QCString namesp,cname;
extractNamespaceName(cd->name(),cname,namesp);
QCString nsDispName;
SrcLangExt lang = cd->getLanguage();
QCString sep = getLanguageSpecificSeparator(lang);
if (sep!="::")
{
nsDispName=substitute(namesp,"::",sep);
cname=substitute(cname,"::",sep);
}
else
{
nsDispName=namesp;
}
ol.writeObjectLink(cd->getReference(),
cd->getOutputFileBase(),cd->anchor(),cname);
if (!namesp.isEmpty())
{
ol.writeString(" (");
NamespaceDef *nd = getResolvedNamespace(namesp);
if (nd && nd->isLinkable())
{
ol.writeObjectLink(nd->getReference(),
nd->getOutputFileBase(),QCString(),nsDispName);
}
else
{
ol.docify(nsDispName);
}
ol.writeString(")");
}
ol.writeString("</dd>");
}
ol.writeString("</dl>\n");
}
ol.writeString("</div>\n");
}
}
//----------------------------------------------------------------------------
static void writeAlphabeticalIndex(OutputList &ol)
{
if (Index::instance().numAnnotatedClasses()==0) return;
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ClassIndex);
QCString title = lne ? lne->title() : theTranslator->trCompoundIndex();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"classes",QCString(),title,HighlightedItem::Classes);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,title,QCString(),"classes",QCString(),FALSE,TRUE);
}
ol.startContents();
writeAlphabeticalClassList(ol, ClassDef::Class, Index::instance().numAnnotatedClasses());
endFile(ol); // contains ol.endContents()
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static void writeAlphabeticalInterfaceIndex(OutputList &ol)
{
if (Index::instance().numAnnotatedInterfaces()==0) return;
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::InterfaceIndex);
QCString title = lne ? lne->title() : theTranslator->trInterfaceIndex();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"interfaces",QCString(),title,HighlightedItem::Interfaces);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,title,QCString(),"interfaces",QCString(),FALSE,TRUE);
}
ol.startContents();
writeAlphabeticalClassList(ol, ClassDef::Interface, Index::instance().numAnnotatedInterfaces());
endFile(ol); // contains ol.endContents()
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static void writeAlphabeticalStructIndex(OutputList &ol)
{
if (Index::instance().numAnnotatedStructs()==0) return;
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::StructIndex);
QCString title = lne ? lne->title() : theTranslator->trStructIndex();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"structs",QCString(),title,HighlightedItem::Structs);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,title,QCString(),"structs",QCString(),FALSE,TRUE);
}
ol.startContents();
writeAlphabeticalClassList(ol, ClassDef::Struct, Index::instance().numAnnotatedStructs());
endFile(ol); // contains ol.endContents()
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static void writeAlphabeticalExceptionIndex(OutputList &ol)
{
if (Index::instance().numAnnotatedExceptions()==0) return;
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ExceptionIndex);
QCString title = lne ? lne->title() : theTranslator->trExceptionIndex();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"exceptions",QCString(),title,HighlightedItem::Exceptions);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,title,QCString(),"exceptions",QCString(),FALSE,TRUE);
}
ol.startContents();
writeAlphabeticalClassList(ol, ClassDef::Exception, Index::instance().numAnnotatedExceptions());
endFile(ol); // contains ol.endContents()
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
struct AnnotatedIndexContext
{
AnnotatedIndexContext(int numAnno,int numPrint,
LayoutNavEntry::Kind lk,LayoutNavEntry::Kind fk,
const QCString &title,const QCString &intro,
ClassDef::CompoundType ct,
const QCString &fn,
HighlightedItem hi) :
numAnnotated(numAnno), numPrinted(numPrint),
listKind(lk), fallbackKind(fk),
listDefaultTitleText(title), listDefaultIntroText(intro),
compoundType(ct),fileBaseName(fn),
hiItem(hi) { }
const int numAnnotated;
const int numPrinted;
const LayoutNavEntry::Kind listKind;
const LayoutNavEntry::Kind fallbackKind;
const QCString listDefaultTitleText;
const QCString listDefaultIntroText;
const ClassDef::CompoundType compoundType;
const QCString fileBaseName;
const HighlightedItem hiItem;
};
static void writeAnnotatedIndexGeneric(OutputList &ol,const AnnotatedIndexContext ctx)
{
//printf("writeAnnotatedIndex: count=%d printed=%d\n",
// annotatedClasses,annotatedClassesPrinted);
if (ctx.numAnnotated==0) return;
ol.pushGeneratorState();
ol.disable(OutputType::Man);
if (ctx.numPrinted==0)
{
ol.disable(OutputType::Latex);
ol.disable(OutputType::RTF);
}
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(ctx.listKind);
if (lne==nullptr) lne = LayoutDocManager::instance().rootNavEntry()->find(ctx.fallbackKind); // fall back
QCString title = lne ? lne->title() : ctx.listDefaultTitleText;
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,ctx.fileBaseName,QCString(),title,ctx.hiItem);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.parseText(lne ? lne->intro() : ctx.listDefaultIntroText);
ol.endTextBlock();
// ---------------
// Linear class index for Latex/RTF
// ---------------
ol.pushGeneratorState();
ol.disable(OutputType::Html);
Doxygen::indexList->disable();
writeAnnotatedClassList(ol, ctx.compoundType);
Doxygen::indexList->enable();
ol.popGeneratorState();
// ---------------
// Hierarchical class index for HTML
// ---------------
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),ctx.fileBaseName,QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
FTVHelp ftv(false);
writeClassTreeInsideNamespace(*Doxygen::namespaceLinkedMap,&ftv,TRUE,addToIndex,ctx.compoundType);
writeClassTree(*Doxygen::classLinkedMap,&ftv,addToIndex,TRUE,ctx.compoundType);
TextStream t;
ftv.generateTreeViewInline(t);
ol.writeString(t.str().c_str());
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
ol.popGeneratorState();
// ------
endFile(ol); // contains ol.endContents()
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static void writeAnnotatedIndex(OutputList &ol)
{
const auto &index = Index::instance();
writeAnnotatedIndexGeneric(ol,
AnnotatedIndexContext(index.numAnnotatedClasses(),index.numAnnotatedClassesPrinted(),
LayoutNavEntry::ClassList,LayoutNavEntry::Classes,
theTranslator->trCompoundList(),theTranslator->trCompoundListDescription(),
ClassDef::Class,
"annotated",
HighlightedItem::AnnotatedClasses));
}
//----------------------------------------------------------------------------
static void writeAnnotatedInterfaceIndex(OutputList &ol)
{
const auto &index = Index::instance();
writeAnnotatedIndexGeneric(ol,
AnnotatedIndexContext(index.numAnnotatedInterfaces(),index.numAnnotatedInterfacesPrinted(),
LayoutNavEntry::InterfaceList,LayoutNavEntry::Interfaces,
theTranslator->trInterfaceList(),theTranslator->trInterfaceListDescription(),
ClassDef::Interface,
"annotatedinterfaces",
HighlightedItem::AnnotatedInterfaces));
}
//----------------------------------------------------------------------------
static void writeAnnotatedStructIndex(OutputList &ol)
{
const auto &index = Index::instance();
writeAnnotatedIndexGeneric(ol,
AnnotatedIndexContext(index.numAnnotatedStructs(),index.numAnnotatedStructsPrinted(),
LayoutNavEntry::StructList,LayoutNavEntry::Structs,
theTranslator->trStructList(),theTranslator->trStructListDescription(),
ClassDef::Struct,
"annotatedstructs",
HighlightedItem::AnnotatedStructs));
}
//----------------------------------------------------------------------------
static void writeAnnotatedExceptionIndex(OutputList &ol)
{
const auto &index = Index::instance();
writeAnnotatedIndexGeneric(ol,
AnnotatedIndexContext(index.numAnnotatedExceptions(),index.numAnnotatedExceptionsPrinted(),
LayoutNavEntry::ExceptionList,LayoutNavEntry::Exceptions,
theTranslator->trExceptionList(),theTranslator->trExceptionListDescription(),
ClassDef::Exception,
"annotatedexceptions",
HighlightedItem::AnnotatedExceptions));
}
//----------------------------------------------------------------------------
static void writeClassLinkForMember(OutputList &ol,const MemberDef *md,const QCString &separator,
QCString &prevClassName)
{
const ClassDef *cd=md->getClassDef();
if ( cd && prevClassName!=cd->displayName())
{
ol.writeString(separator);
ol.writeObjectLink(md->getReference(),md->getOutputFileBase(),md->anchor(),
cd->displayName());
prevClassName = cd->displayName();
}
}
static void writeFileLinkForMember(OutputList &ol,const MemberDef *md,const QCString &separator,
QCString &prevFileName)
{
const FileDef *fd=md->getFileDef();
if (fd && prevFileName!=fd->name())
{
ol.writeString(separator);
ol.writeObjectLink(md->getReference(),md->getOutputFileBase(),md->anchor(),
fd->name());
prevFileName = fd->name();
}
}
static void writeNamespaceLinkForMember(OutputList &ol,const MemberDef *md,const QCString &separator,
QCString &prevNamespaceName)
{
const NamespaceDef *nd=md->getNamespaceDef();
if (nd && prevNamespaceName!=nd->displayName())
{
ol.writeString(separator);
ol.writeObjectLink(md->getReference(),md->getOutputFileBase(),md->anchor(),
nd->displayName());
prevNamespaceName = nd->displayName();
}
}
static void writeModuleLinkForMember(OutputList &ol,const MemberDef *md,const QCString &separator,
QCString &prevModuleName)
{
const ModuleDef *mod=md->getModuleDef();
if (mod && prevModuleName!=mod->displayName())
{
ol.writeString(separator);
// link to the member declaration in the module page
ol.writeObjectLink(mod->getReference(),mod->getOutputFileBase(),"r_"+md->anchor(),
mod->displayName());
prevModuleName = mod->displayName();
}
}
static void writeMemberList(OutputList &ol,bool useSections,const std::string &page,
const Index::MemberIndexMap &memberIndexMap,
Definition::DefType type)
{
int index = static_cast<int>(type);
const int numIndices = 4;
ASSERT(index<numIndices);
typedef void (*writeLinkForMember_t)(OutputList &ol,const MemberDef *md,const QCString &separator,
QCString &prevNamespaceName);
// each index tab has its own write function
static writeLinkForMember_t writeLinkForMemberMap[numIndices] =
{
&writeClassLinkForMember,
&writeFileLinkForMember,
&writeNamespaceLinkForMember,
&writeModuleLinkForMember
};
QCString prevName;
QCString prevDefName;
bool first=TRUE;
bool firstSection=TRUE;
bool firstItem=TRUE;
const Index::MemberIndexList *mil = nullptr;
std::string letter;
for (const auto &kv : memberIndexMap)
{
if (!page.empty()) // specific page mode
{
auto it = memberIndexMap.find(page);
if (it != memberIndexMap.end())
{
mil = &it->second;
letter = page;
}
}
else // do all pages
{
mil = &kv.second;
letter = kv.first;
}
if (mil==nullptr || mil->empty()) continue;
for (const auto &md : *mil)
{
const char *sep = nullptr;
bool isFunc=!md->isObjCMethod() &&
(md->isFunction() || md->isSlot() || md->isSignal());
QCString name=type==Definition::TypeModule ? md->qualifiedName() : md->name();
int startIndex = getPrefixIndex(name);
if (name.data()+startIndex!=prevName) // new entry
{
if ((prevName.isEmpty() ||
tolower(name.at(startIndex))!=tolower(prevName.at(0))) &&
useSections) // new section
{
if (!firstItem) ol.endItemListItem();
if (!firstSection) ol.endItemList();
QCString cs = letterToLabel(letter.c_str());
QCString anchor=QCString("index_")+convertToId(cs);
QCString title=QCString("- ")+letter.c_str()+" -";
ol.startSection(anchor,title,SectionType::Subsection);
ol.docify(title);
ol.endSection(anchor,SectionType::Subsection);
ol.startItemList();
firstSection=FALSE;
firstItem=TRUE;
}
else if (!useSections && first)
{
ol.startItemList();
first=FALSE;
}
// member name
if (!firstItem) ol.endItemListItem();
ol.startItemListItem();
firstItem=FALSE;
ol.docify(name);
if (isFunc) ol.docify("()");
//ol.writeString("\n");
// link to class
prevDefName="";
sep = " : ";
prevName = name.data()+startIndex;
}
else // same entry
{
sep = ", ";
// link to class for other members with the same name
}
if (index<numIndices)
{
// write the link for the specific list type
writeLinkForMemberMap[index](ol,md,sep,prevDefName);
}
}
if (!page.empty())
{
break;
}
}
if (!firstItem) ol.endItemListItem();
ol.endItemList();
}
//----------------------------------------------------------------------------
void Index::addClassMemberNameToIndex(const MemberDef *md)
{
bool hideFriendCompounds = Config_getBool(HIDE_FRIEND_COMPOUNDS);
const ClassDef *cd=nullptr;
if (md->isLinkableInProject() &&
(cd=md->getClassDef()) &&
cd->isLinkableInProject() &&
!cd->isImplicitTemplateInstance())
{
QCString n = md->name();
std::string letter = getUTF8CharAt(n.str(),getPrefixIndex(n));
if (!letter.empty())
{
letter = convertUTF8ToLower(letter);
bool isFriendToHide = hideFriendCompounds &&
(QCString(md->typeString())=="friend class" ||
QCString(md->typeString())=="friend struct" ||
QCString(md->typeString())=="friend union");
if (!(md->isFriend() && isFriendToHide) &&
(!md->isEnumValue() || (md->getEnumScope() && !md->getEnumScope()->isStrong()))
)
{
incrementDocumentedClassMembers(ClassMemberHighlight::All,letter,md);
}
if (md->isFunction() || md->isSlot() || md->isSignal())
{
incrementDocumentedClassMembers(ClassMemberHighlight::Functions,letter,md);
}
else if (md->isVariable())
{
incrementDocumentedClassMembers(ClassMemberHighlight::Variables,letter,md);
}
else if (md->isTypedef())
{
incrementDocumentedClassMembers(ClassMemberHighlight::Typedefs,letter,md);
}
else if (md->isEnumerate())
{
incrementDocumentedClassMembers(ClassMemberHighlight::Enums,letter,md);
}
else if (md->isEnumValue() && md->getEnumScope() && !md->getEnumScope()->isStrong())
{
incrementDocumentedClassMembers(ClassMemberHighlight::EnumValues,letter,md);
}
else if (md->isProperty())
{
incrementDocumentedClassMembers(ClassMemberHighlight::Properties,letter,md);
}
else if (md->isEvent())
{
incrementDocumentedClassMembers(ClassMemberHighlight::Events,letter,md);
}
else if (md->isRelated() || md->isForeign() ||
(md->isFriend() && !isFriendToHide))
{
incrementDocumentedClassMembers(ClassMemberHighlight::Related,letter,md);
}
}
}
}
//----------------------------------------------------------------------------
void Index::addNamespaceMemberNameToIndex(const MemberDef *md)
{
const NamespaceDef *nd=md->getNamespaceDef();
if (nd && nd->isLinkableInProject() && md->isLinkableInProject())
{
QCString n = md->name();
std::string letter = getUTF8CharAt(n.str(),getPrefixIndex(n));
if (!letter.empty())
{
letter = convertUTF8ToLower(letter);
if (!md->isEnumValue() || (md->getEnumScope() && !md->getEnumScope()->isStrong()))
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::All,letter,md);
}
if (md->isFunction())
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::Functions,letter,md);
}
else if (md->isVariable())
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::Variables,letter,md);
}
else if (md->isTypedef())
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::Typedefs,letter,md);
}
else if (md->isSequence())
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::Sequences,letter,md);
}
else if (md->isDictionary())
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::Dictionaries,letter,md);
}
else if (md->isEnumerate())
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::Enums,letter,md);
}
else if (md->isEnumValue() && md->getEnumScope() && !md->getEnumScope()->isStrong())
{
incrementDocumentedNamespaceMembers(NamespaceMemberHighlight::EnumValues,letter,md);
}
}
}
}
//----------------------------------------------------------------------------
void Index::addFileMemberNameToIndex(const MemberDef *md)
{
const FileDef *fd=md->getFileDef();
if (fd && fd->isLinkableInProject() && md->isLinkableInProject())
{
QCString n = md->name();
std::string letter = getUTF8CharAt(n.str(),getPrefixIndex(n));
if (!letter.empty())
{
letter = convertUTF8ToLower(letter);
if (!md->isEnumValue() || (md->getEnumScope() && !md->getEnumScope()->isStrong()))
{
incrementDocumentedFileMembers(FileMemberHighlight::All,letter,md);
}
if (md->isFunction())
{
incrementDocumentedFileMembers(FileMemberHighlight::Functions,letter,md);
}
else if (md->isVariable())
{
incrementDocumentedFileMembers(FileMemberHighlight::Variables,letter,md);
}
else if (md->isTypedef())
{
incrementDocumentedFileMembers(FileMemberHighlight::Typedefs,letter,md);
}
else if (md->isSequence())
{
incrementDocumentedFileMembers(FileMemberHighlight::Sequences,letter,md);
}
else if (md->isDictionary())
{
incrementDocumentedFileMembers(FileMemberHighlight::Dictionaries,letter,md);
}
else if (md->isEnumerate())
{
incrementDocumentedFileMembers(FileMemberHighlight::Enums,letter,md);
}
else if (md->isEnumValue() && md->getEnumScope() && !md->getEnumScope()->isStrong())
{
incrementDocumentedFileMembers(FileMemberHighlight::EnumValues,letter,md);
}
else if (md->isDefine())
{
incrementDocumentedFileMembers(FileMemberHighlight::Defines,letter,md);
}
}
}
}
//----------------------------------------------------------------------------
void Index::addModuleMemberNameToIndex(const MemberDef *md)
{
const ModuleDef *mod = md->getModuleDef();
if (mod && mod->isPrimaryInterface() && mod->isLinkableInProject() && md->isLinkableInProject())
{
QCString n = md->name();
std::string letter = getUTF8CharAt(n.str(),getPrefixIndex(n));
if (!letter.empty())
{
letter = convertUTF8ToLower(letter);
if (!md->isEnumValue() || (md->getEnumScope() && !md->getEnumScope()->isStrong()))
{
incrementDocumentedModuleMembers(ModuleMemberHighlight::All,letter,md);
}
if (md->isFunction())
{
incrementDocumentedModuleMembers(ModuleMemberHighlight::Functions,letter,md);
}
else if (md->isVariable())
{
incrementDocumentedModuleMembers(ModuleMemberHighlight::Variables,letter,md);
}
else if (md->isTypedef())
{
incrementDocumentedModuleMembers(ModuleMemberHighlight::Typedefs,letter,md);
}
else if (md->isEnumerate())
{
incrementDocumentedModuleMembers(ModuleMemberHighlight::Enums,letter,md);
}
else if (md->isEnumValue() && md->getEnumScope() && !md->getEnumScope()->isStrong())
{
incrementDocumentedModuleMembers(ModuleMemberHighlight::EnumValues,letter,md);
}
}
}
}
//----------------------------------------------------------------------------
static void writeQuickMemberIndex(OutputList &ol,
const Index::MemberIndexMap &map,const std::string &page,
QCString fullName,bool multiPage)
{
bool first=TRUE;
startQuickIndexList(ol,TRUE);
for (const auto &[letter,list] : map)
{
QCString ci(letter);
QCString is = letterToLabel(ci);
QCString anchor;
QCString extension=Doxygen::htmlFileExtension;
if (!multiPage)
anchor="#index_";
else if (first)
anchor=fullName+extension+"#index_";
else
anchor=fullName+"_"+is+extension+"#index_";
startQuickIndexItem(ol,anchor+convertToId(is),letter==page,TRUE,first);
ol.writeString(ci);
endQuickIndexItem(ol);
first=FALSE;
}
endQuickIndexList(ol);
}
//----------------------------------------------------------------------------
/** Helper class representing a class member in the navigation menu. */
struct CmhlInfo
{
CmhlInfo(const char *fn,const QCString &t) : fname(fn), title(t) {}
const char *fname;
QCString title;
};
static const CmhlInfo *getCmhlInfo(size_t hl)
{
bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
static CmhlInfo cmhlInfo[] =
{
CmhlInfo("functions", theTranslator->trAll()),
CmhlInfo("functions_func",
fortranOpt ? theTranslator->trSubprograms() :
vhdlOpt ? theTranslator->trFunctionAndProc() :
theTranslator->trFunctions()),
CmhlInfo("functions_vars",theTranslator->trVariables()),
CmhlInfo("functions_type",theTranslator->trTypedefs()),
CmhlInfo("functions_enum",theTranslator->trEnumerations()),
CmhlInfo("functions_eval",theTranslator->trEnumerationValues()),
CmhlInfo("functions_prop",theTranslator->trProperties()),
CmhlInfo("functions_evnt",theTranslator->trEvents()),
CmhlInfo("functions_rela",theTranslator->trRelatedSymbols())
};
return &cmhlInfo[hl];
}
static void writeClassMemberIndexFiltered(OutputList &ol, ClassMemberHighlight::Enum hl)
{
const auto &index = Index::instance();
if (index.numDocumentedClassMembers(hl)==0) return;
bool disableIndex = Config_getBool(DISABLE_INDEX);
bool multiPageIndex=FALSE;
if (index.numDocumentedClassMembers(hl)>MAX_ITEMS_BEFORE_MULTIPAGE_INDEX)
{
multiPageIndex=TRUE;
}
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
QCString extension=Doxygen::htmlFileExtension;
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ClassMembers);
QCString title = lne ? lne->title() : theTranslator->trCompoundMembers();
if (hl!=ClassMemberHighlight::All) title+=QCString(" - ")+getCmhlInfo(hl)->title;
bool addToIndex = lne==nullptr || lne->visible();
if (addToIndex)
{
Doxygen::indexList->addContentsItem(multiPageIndex,getCmhlInfo(hl)->title,QCString(),
getCmhlInfo(hl)->fname,QCString(),multiPageIndex,TRUE);
if (multiPageIndex) Doxygen::indexList->incContentsDepth();
}
bool first=TRUE;
for (const auto &[letter,list] : index.isClassIndexLetterUsed(hl))
{
QCString fileName = getCmhlInfo(hl)->fname;
if (multiPageIndex)
{
QCString cs(letter);
if (!first)
{
fileName+="_"+letterToLabel(cs);
}
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,cs,QCString(),fileName,QCString(),FALSE,TRUE);
}
}
bool quickIndex = index.numDocumentedClassMembers(hl)>maxItemsBeforeQuickIndex;
ol.startFile(fileName+extension,QCString(),title);
ol.startQuickIndices();
if (!disableIndex)
{
ol.writeQuickLinks(HighlightedItem::Functions,QCString());
if (!Config_getBool(HTML_DYNAMIC_MENUS))
{
startQuickIndexList(ol);
// index item for global member list
startQuickIndexItem(ol,
getCmhlInfo(0)->fname+Doxygen::htmlFileExtension,hl==ClassMemberHighlight::All,TRUE,first);
ol.writeString(fixSpaces(getCmhlInfo(0)->title));
endQuickIndexItem(ol);
// index items per category member lists
for (int i=1;i<ClassMemberHighlight::Total;i++)
{
if (index.numDocumentedClassMembers(static_cast<ClassMemberHighlight::Enum>(i))>0)
{
startQuickIndexItem(ol,getCmhlInfo(i)->fname+Doxygen::htmlFileExtension,hl==i,TRUE,first);
ol.writeString(fixSpaces(getCmhlInfo(i)->title));
//printf("multiPageIndex=%d first=%d fileName=%s file=%s title=%s\n",
// multiPageIndex,first,qPrint(fileName),getCmhlInfo(i)->fname,qPrint(getCmhlInfo(i)->title));
endQuickIndexItem(ol);
}
}
endQuickIndexList(ol);
// quick alphabetical index
if (quickIndex)
{
writeQuickMemberIndex(ol,index.isClassIndexLetterUsed(hl),letter,
getCmhlInfo(hl)->fname,multiPageIndex);
}
}
}
ol.endQuickIndices();
ol.writeSplitBar(fileName);
ol.writeSearchInfo();
ol.startContents();
ol.startTextBlock();
ol.parseText(hl == ClassMemberHighlight::All && lne ? lne->intro() : theTranslator->trCompoundMembersDescriptionTotal(hl));
ol.endTextBlock();
writeMemberList(ol,quickIndex,
multiPageIndex ? letter : std::string(),
index.isClassIndexLetterUsed(hl),
Definition::TypeClass);
endFile(ol);
first=FALSE;
}
if (multiPageIndex && addToIndex) Doxygen::indexList->decContentsDepth();
ol.popGeneratorState();
}
static void writeClassMemberIndex(OutputList &ol)
{
const auto &index = Index::instance();
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ClassMembers);
bool addToIndex = lne==nullptr || lne->visible();
if (index.numDocumentedClassMembers(ClassMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne ? lne->title() : theTranslator->trCompoundMembers(),QCString(),"functions",QCString());
Doxygen::indexList->incContentsDepth();
}
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::All);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::Functions);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::Variables);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::Typedefs);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::Enums);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::EnumValues);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::Properties);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::Events);
writeClassMemberIndexFiltered(ol,ClassMemberHighlight::Related);
if (index.numDocumentedClassMembers(ClassMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
//----------------------------------------------------------------------------
/** Helper class representing a file member in the navigation menu. */
struct FmhlInfo
{
FmhlInfo(const char *fn,const QCString &t) : fname(fn), title(t) {}
const char *fname;
QCString title;
};
static const FmhlInfo *getFmhlInfo(size_t hl)
{
bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
static FmhlInfo fmhlInfo[] =
{
FmhlInfo("globals", theTranslator->trAll()),
FmhlInfo("globals_func",
fortranOpt ? theTranslator->trSubprograms() :
vhdlOpt ? theTranslator->trFunctionAndProc() :
theTranslator->trFunctions()),
FmhlInfo("globals_vars",sliceOpt ? theTranslator->trConstants() : theTranslator->trVariables()),
FmhlInfo("globals_type",theTranslator->trTypedefs()),
FmhlInfo("globals_sequ",theTranslator->trSequences()),
FmhlInfo("globals_dict",theTranslator->trDictionaries()),
FmhlInfo("globals_enum",theTranslator->trEnumerations()),
FmhlInfo("globals_eval",theTranslator->trEnumerationValues()),
FmhlInfo("globals_defs",theTranslator->trDefines())
};
return &fmhlInfo[hl];
}
static void writeFileMemberIndexFiltered(OutputList &ol, FileMemberHighlight::Enum hl)
{
const auto &index = Index::instance();
if (index.numDocumentedFileMembers(hl)==0) return;
bool disableIndex = Config_getBool(DISABLE_INDEX);
bool multiPageIndex=FALSE;
if (Index::instance().numDocumentedFileMembers(hl)>MAX_ITEMS_BEFORE_MULTIPAGE_INDEX)
{
multiPageIndex=TRUE;
}
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
QCString extension=Doxygen::htmlFileExtension;
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::FileGlobals);
QCString title = lne ? lne->title() : theTranslator->trFileMembers();
bool addToIndex = lne==nullptr || lne->visible();
if (addToIndex)
{
Doxygen::indexList->addContentsItem(multiPageIndex,getFmhlInfo(hl)->title,QCString(),
getFmhlInfo(hl)->fname,QCString(),multiPageIndex,TRUE);
if (multiPageIndex) Doxygen::indexList->incContentsDepth();
}
bool first=TRUE;
for (const auto &[letter,list] : index.isFileIndexLetterUsed(hl))
{
QCString fileName = getFmhlInfo(hl)->fname;
if (multiPageIndex)
{
QCString cs(letter);
if (!first)
{
fileName+="_"+letterToLabel(cs);
}
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,cs,QCString(),fileName,QCString(),FALSE,TRUE);
}
}
bool quickIndex = index.numDocumentedFileMembers(hl)>maxItemsBeforeQuickIndex;
ol.startFile(fileName+extension,QCString(),title);
ol.startQuickIndices();
if (!disableIndex)
{
ol.writeQuickLinks(HighlightedItem::Globals,QCString());
if (!Config_getBool(HTML_DYNAMIC_MENUS))
{
startQuickIndexList(ol);
// index item for all file member lists
startQuickIndexItem(ol,
getFmhlInfo(0)->fname+Doxygen::htmlFileExtension,hl==FileMemberHighlight::All,TRUE,first);
ol.writeString(fixSpaces(getFmhlInfo(0)->title));
endQuickIndexItem(ol);
// index items for per category member lists
for (int i=1;i<FileMemberHighlight::Total;i++)
{
if (Index::instance().numDocumentedFileMembers(static_cast<FileMemberHighlight::Enum>(i))>0)
{
startQuickIndexItem(ol,
getFmhlInfo(i)->fname+Doxygen::htmlFileExtension,hl==i,TRUE,first);
ol.writeString(fixSpaces(getFmhlInfo(i)->title));
endQuickIndexItem(ol);
}
}
endQuickIndexList(ol);
if (quickIndex)
{
writeQuickMemberIndex(ol,index.isFileIndexLetterUsed(hl),letter,
getFmhlInfo(hl)->fname,multiPageIndex);
}
}
}
ol.endQuickIndices();
ol.writeSplitBar(fileName);
ol.writeSearchInfo();
ol.startContents();
ol.startTextBlock();
ol.parseText(hl == FileMemberHighlight::All && lne ? lne->intro() : theTranslator->trFileMembersDescriptionTotal(hl));
ol.endTextBlock();
writeMemberList(ol,quickIndex,
multiPageIndex ? letter : std::string(),
index.isFileIndexLetterUsed(hl),
Definition::TypeFile);
endFile(ol);
first=FALSE;
}
if (multiPageIndex && addToIndex) Doxygen::indexList->decContentsDepth();
ol.popGeneratorState();
}
static void writeFileMemberIndex(OutputList &ol)
{
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::FileGlobals);
bool addToIndex = lne==nullptr || lne->visible();
if (Index::instance().numDocumentedFileMembers(FileMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(true,lne ? lne->title() : theTranslator->trFileMembers(),QCString(),"globals",QCString());
Doxygen::indexList->incContentsDepth();
}
writeFileMemberIndexFiltered(ol,FileMemberHighlight::All);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::Functions);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::Variables);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::Typedefs);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::Sequences);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::Dictionaries);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::Enums);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::EnumValues);
writeFileMemberIndexFiltered(ol,FileMemberHighlight::Defines);
if (Index::instance().numDocumentedFileMembers(FileMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
//----------------------------------------------------------------------------
/** Helper class representing a namespace member in the navigation menu. */
struct NmhlInfo
{
NmhlInfo(const char *fn,const QCString &t) : fname(fn), title(t) {}
const char *fname;
QCString title;
};
static const NmhlInfo *getNmhlInfo(size_t hl)
{
bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
static NmhlInfo nmhlInfo[] =
{
NmhlInfo("namespacemembers", theTranslator->trAll()),
NmhlInfo("namespacemembers_func",
fortranOpt ? theTranslator->trSubprograms() :
vhdlOpt ? theTranslator->trFunctionAndProc() :
theTranslator->trFunctions()),
NmhlInfo("namespacemembers_vars",sliceOpt ? theTranslator->trConstants() : theTranslator->trVariables()),
NmhlInfo("namespacemembers_type",theTranslator->trTypedefs()),
NmhlInfo("namespacemembers_sequ",theTranslator->trSequences()),
NmhlInfo("namespacemembers_dict",theTranslator->trDictionaries()),
NmhlInfo("namespacemembers_enum",theTranslator->trEnumerations()),
NmhlInfo("namespacemembers_eval",theTranslator->trEnumerationValues())
};
return &nmhlInfo[hl];
}
//----------------------------------------------------------------------------
static void writeNamespaceMemberIndexFiltered(OutputList &ol,
NamespaceMemberHighlight::Enum hl)
{
const auto &index = Index::instance();
if (index.numDocumentedNamespaceMembers(hl)==0) return;
bool disableIndex = Config_getBool(DISABLE_INDEX);
bool multiPageIndex=FALSE;
if (index.numDocumentedNamespaceMembers(hl)>MAX_ITEMS_BEFORE_MULTIPAGE_INDEX)
{
multiPageIndex=TRUE;
}
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
QCString extension=Doxygen::htmlFileExtension;
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::NamespaceMembers);
QCString title = lne ? lne->title() : theTranslator->trNamespaceMembers();
bool addToIndex = lne==nullptr || lne->visible();
if (addToIndex)
{
Doxygen::indexList->addContentsItem(multiPageIndex,getNmhlInfo(hl)->title,QCString(),
getNmhlInfo(hl)->fname,QCString(),multiPageIndex,TRUE);
if (multiPageIndex) Doxygen::indexList->incContentsDepth();
}
bool first=TRUE;
for (const auto &[letter,list] : index.isNamespaceIndexLetterUsed(hl))
{
QCString fileName = getNmhlInfo(hl)->fname;
if (multiPageIndex)
{
QCString cs(letter);
if (!first)
{
fileName+="_"+letterToLabel(cs);
}
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,cs,QCString(),fileName,QCString(),FALSE,TRUE);
}
}
bool quickIndex = index.numDocumentedNamespaceMembers(hl)>maxItemsBeforeQuickIndex;
ol.startFile(fileName+extension,QCString(),title);
ol.startQuickIndices();
if (!disableIndex)
{
ol.writeQuickLinks(HighlightedItem::NamespaceMembers,QCString());
if (!Config_getBool(HTML_DYNAMIC_MENUS))
{
startQuickIndexList(ol);
// index item for all namespace member lists
startQuickIndexItem(ol,
getNmhlInfo(0)->fname+Doxygen::htmlFileExtension,hl==NamespaceMemberHighlight::All,TRUE,first);
ol.writeString(fixSpaces(getNmhlInfo(0)->title));
endQuickIndexItem(ol);
// index items per category member lists
for (int i=1;i<NamespaceMemberHighlight::Total;i++)
{
if (index.numDocumentedNamespaceMembers(static_cast<NamespaceMemberHighlight::Enum>(i))>0)
{
startQuickIndexItem(ol,
getNmhlInfo(i)->fname+Doxygen::htmlFileExtension,hl==i,TRUE,first);
ol.writeString(fixSpaces(getNmhlInfo(i)->title));
endQuickIndexItem(ol);
}
}
endQuickIndexList(ol);
if (quickIndex)
{
writeQuickMemberIndex(ol,index.isNamespaceIndexLetterUsed(hl),letter,
getNmhlInfo(hl)->fname,multiPageIndex);
}
}
}
ol.endQuickIndices();
ol.writeSplitBar(fileName);
ol.writeSearchInfo();
ol.startContents();
ol.startTextBlock();
ol.parseText(hl == NamespaceMemberHighlight::All && lne ? lne->intro() : theTranslator->trNamespaceMembersDescriptionTotal(hl));
ol.endTextBlock();
writeMemberList(ol,quickIndex,
multiPageIndex ? letter : std::string(),
index.isNamespaceIndexLetterUsed(hl),
Definition::TypeNamespace);
endFile(ol);
first=FALSE;
}
if (multiPageIndex && addToIndex) Doxygen::indexList->decContentsDepth();
ol.popGeneratorState();
}
static void writeNamespaceMemberIndex(OutputList &ol)
{
const auto &index = Index::instance();
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::NamespaceMembers);
bool addToIndex = lne==nullptr || lne->visible();
if (index.numDocumentedNamespaceMembers(NamespaceMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(true,lne ? lne->title() : theTranslator->trNamespaceMembers(),QCString(),"namespacemembers",QCString());
Doxygen::indexList->incContentsDepth();
}
//bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::All);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::Functions);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::Variables);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::Typedefs);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::Sequences);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::Dictionaries);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::Enums);
writeNamespaceMemberIndexFiltered(ol,NamespaceMemberHighlight::EnumValues);
if (index.numDocumentedNamespaceMembers(NamespaceMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
//----------------------------------------------------------------------------
/** Helper class representing a module member in the navigation menu. */
struct MmhlInfo
{
MmhlInfo(const char *fn,const QCString &t) : fname(fn), title(t) {}
const char *fname;
QCString title;
};
static const MmhlInfo *getMmhlInfo(size_t hl)
{
static MmhlInfo nmhlInfo[] =
{
MmhlInfo("modulemembers", theTranslator->trAll()),
MmhlInfo("modulemembers_func",theTranslator->trFunctions()),
MmhlInfo("modulemembers_vars",theTranslator->trVariables()),
MmhlInfo("modulemembers_type",theTranslator->trTypedefs()),
MmhlInfo("modulemembers_enum",theTranslator->trEnumerations()),
MmhlInfo("modulemembers_eval",theTranslator->trEnumerationValues())
};
return &nmhlInfo[hl];
}
//----------------------------------------------------------------------------
static void writeModuleMemberIndexFiltered(OutputList &ol,
ModuleMemberHighlight::Enum hl)
{
const auto &index = Index::instance();
if (index.numDocumentedModuleMembers(hl)==0) return;
bool disableIndex = Config_getBool(DISABLE_INDEX);
bool multiPageIndex=FALSE;
if (index.numDocumentedModuleMembers(hl)>MAX_ITEMS_BEFORE_MULTIPAGE_INDEX)
{
multiPageIndex=TRUE;
}
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
QCString extension=Doxygen::htmlFileExtension;
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ModuleMembers);
QCString title = lne ? lne->title() : theTranslator->trModulesMembers();
bool addToIndex = lne==nullptr || lne->visible();
if (addToIndex)
{
Doxygen::indexList->addContentsItem(multiPageIndex,getMmhlInfo(hl)->title,QCString(),
getMmhlInfo(hl)->fname,QCString(),multiPageIndex,TRUE);
if (multiPageIndex) Doxygen::indexList->incContentsDepth();
}
bool first=TRUE;
for (const auto &[letter,list] : index.isModuleIndexLetterUsed(hl))
{
QCString fileName = getMmhlInfo(hl)->fname;
if (multiPageIndex)
{
QCString cs(letter);
if (!first)
{
fileName+="_"+letterToLabel(cs);
}
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,cs,QCString(),fileName,QCString(),FALSE,TRUE);
}
}
bool quickIndex = index.numDocumentedModuleMembers(hl)>maxItemsBeforeQuickIndex;
ol.startFile(fileName+extension,QCString(),title);
ol.startQuickIndices();
if (!disableIndex)
{
ol.writeQuickLinks(HighlightedItem::ModuleMembers,QCString());
if (!Config_getBool(HTML_DYNAMIC_MENUS))
{
startQuickIndexList(ol);
// index item for all namespace member lists
startQuickIndexItem(ol,
getMmhlInfo(0)->fname+Doxygen::htmlFileExtension,hl==ModuleMemberHighlight::All,TRUE,first);
ol.writeString(fixSpaces(getMmhlInfo(0)->title));
endQuickIndexItem(ol);
// index items per category member lists
for (int i=1;i<ModuleMemberHighlight::Total;i++)
{
if (index.numDocumentedModuleMembers(static_cast<ModuleMemberHighlight::Enum>(i))>0)
{
startQuickIndexItem(ol,
getMmhlInfo(i)->fname+Doxygen::htmlFileExtension,hl==i,TRUE,first);
ol.writeString(fixSpaces(getMmhlInfo(i)->title));
endQuickIndexItem(ol);
}
}
endQuickIndexList(ol);
if (quickIndex)
{
writeQuickMemberIndex(ol,index.isModuleIndexLetterUsed(hl),letter,
getMmhlInfo(hl)->fname,multiPageIndex);
}
}
}
ol.endQuickIndices();
ol.writeSplitBar(fileName);
ol.writeSearchInfo();
ol.startContents();
ol.startTextBlock();
ol.parseText(hl == ModuleMemberHighlight::All && lne ? lne->intro() : theTranslator->trModuleMembersDescriptionTotal(hl));
ol.endTextBlock();
writeMemberList(ol,quickIndex,
multiPageIndex ? letter : std::string(),
index.isModuleIndexLetterUsed(hl),
Definition::TypeModule);
endFile(ol);
first=FALSE;
}
if (multiPageIndex && addToIndex) Doxygen::indexList->decContentsDepth();
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static void writeModuleMemberIndex(OutputList &ol)
{
const auto &index = Index::instance();
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ModuleMembers);
bool addToIndex = lne==nullptr || lne->visible();
if (index.numDocumentedModuleMembers(ModuleMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(true,lne ? lne->title() : theTranslator->trModulesMembers(),QCString(),"modulemembers",QCString());
Doxygen::indexList->incContentsDepth();
}
//bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
writeModuleMemberIndexFiltered(ol,ModuleMemberHighlight::All);
writeModuleMemberIndexFiltered(ol,ModuleMemberHighlight::Functions);
writeModuleMemberIndexFiltered(ol,ModuleMemberHighlight::Variables);
writeModuleMemberIndexFiltered(ol,ModuleMemberHighlight::Typedefs);
writeModuleMemberIndexFiltered(ol,ModuleMemberHighlight::Enums);
writeModuleMemberIndexFiltered(ol,ModuleMemberHighlight::EnumValues);
if (index.numDocumentedModuleMembers(ModuleMemberHighlight::All)>0 && addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
//----------------------------------------------------------------------------
static void writeExampleIndex(OutputList &ol)
{
if (Doxygen::exampleLinkedMap->empty()) return;
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Examples);
QCString title = lne ? lne->title() : theTranslator->trExamples();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"examples",QCString(),title,HighlightedItem::Examples);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"examples",QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
ol.startTextBlock();
ol.parseText(lne ? lne->intro() : theTranslator->trExamplesDescription());
ol.endTextBlock();
ol.startItemList();
for (const auto &pd : *Doxygen::exampleLinkedMap)
{
ol.startItemListItem();
QCString n=pd->getOutputFileBase();
if (!pd->title().isEmpty())
{
ol.writeObjectLink(QCString(),n,QCString(),pd->title());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,filterTitle(pd->title()),pd->getReference(),n,QCString(),FALSE,TRUE);
}
}
else
{
ol.writeObjectLink(QCString(),n,QCString(),pd->name());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(FALSE,pd->name(),pd->getReference(),n,QCString(),FALSE,TRUE);
}
}
ol.endItemListItem();
//ol.writeString("\n");
}
ol.endItemList();
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
endFile(ol);
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static void countRelatedPages(int &docPages,int &indexPages)
{
docPages=indexPages=0;
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (pd->visibleInIndex() && !pd->hasParentPage())
{
indexPages++;
}
if (pd->documentedPage())
{
docPages++;
}
}
}
//----------------------------------------------------------------------------
static bool mainPageHasOwnTitle()
{
QCString projectName = Config_getString(PROJECT_NAME);
QCString title;
if (Doxygen::mainPage)
{
title = filterTitle(Doxygen::mainPage->title());
}
return !projectName.isEmpty() && mainPageHasTitle() && qstricmp(title,projectName)!=0;
}
static void writePages(PageDef *pd,FTVHelp *ftv)
{
//printf("writePages()=%s pd=%p mainpage=%p\n",qPrint(pd->name()),(void*)pd,(void*)Doxygen::mainPage.get());
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Pages);
bool addToIndex = lne==nullptr || lne->visible();
if (!addToIndex) return;
bool hasSubPages = pd->hasSubPages();
bool hasSections = pd->hasSections();
if (pd->visibleInIndex())
{
QCString pageTitle;
if (pd->title().isEmpty())
pageTitle=pd->name();
else
pageTitle=filterTitle(pd->title());
if (ftv)
{
//printf("*** adding %s hasSubPages=%d hasSections=%d\n",qPrint(pageTitle),hasSubPages,hasSections);
ftv->addContentsItem(
hasSubPages,pageTitle,
pd->getReference(),pd->getOutputFileBase(),
QCString(),hasSubPages,TRUE,pd);
}
if (addToIndex && pd!=Doxygen::mainPage.get())
{
Doxygen::indexList->addContentsItem(
hasSubPages || hasSections,pageTitle,
pd->getReference(),pd->getOutputFileBase(),
QCString(),hasSubPages,TRUE,pd);
}
}
if (hasSubPages && ftv) ftv->incContentsDepth();
bool doIndent = (hasSections || hasSubPages) &&
(pd!=Doxygen::mainPage.get() || mainPageHasOwnTitle());
if (doIndent)
{
Doxygen::indexList->incContentsDepth();
}
if (hasSections)
{
pd->addSectionsToIndex();
}
for (const auto &subPage : pd->getSubPages())
{
writePages(subPage,ftv);
}
if (hasSubPages && ftv) ftv->decContentsDepth();
if (doIndent)
{
Doxygen::indexList->decContentsDepth();
}
//printf("end writePages()=%s\n",qPrint(pd->title()));
}
//----------------------------------------------------------------------------
static void writePageIndex(OutputList &ol)
{
if (Index::instance().numIndexedPages()==0) return;
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Pages);
QCString title = lne ? lne->title() : theTranslator->trRelatedPages();
startFile(ol,"pages",QCString(),title,HighlightedItem::Pages);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.parseText(lne ? lne->intro() : theTranslator->trRelatedPagesDescription());
ol.endTextBlock();
{
FTVHelp ftv(false);
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if ((pd->getOuterScope()==nullptr ||
pd->getOuterScope()->definitionType()!=Definition::TypePage) && // not a sub page
pd->visibleInIndex()
)
{
writePages(pd.get(),&ftv);
}
}
TextStream t;
ftv.generateTreeViewInline(t);
ol.writeString(t.str().c_str());
}
// ol.popGeneratorState();
// ------
endFile(ol);
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
static int countGroups()
{
int count=0;
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (!gd->isReference())
{
//gd->visited=FALSE;
count++;
}
}
return count;
}
//----------------------------------------------------------------------------
static int countDirs()
{
int count=0;
for (const auto &dd : *Doxygen::dirLinkedMap)
{
if (dd->isLinkableInProject())
{
count++;
}
}
return count;
}
//----------------------------------------------------------------------------
void writeGraphInfo(OutputList &ol)
{
if (!Config_getBool(HAVE_DOT) || !Config_getBool(GENERATE_HTML)) return;
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
DotLegendGraph gd;
gd.writeGraph(Config_getString(HTML_OUTPUT));
bool oldStripCommentsState = Config_getBool(STRIP_CODE_COMMENTS);
bool oldCreateSubdirs = Config_getBool(CREATE_SUBDIRS);
// temporarily disable the stripping of comments for our own code example!
Config_updateBool(STRIP_CODE_COMMENTS,FALSE);
// temporarily disable create subdirs for linking to our example
Config_updateBool(CREATE_SUBDIRS,FALSE);
startFile(ol,"graph_legend",QCString(),theTranslator->trLegendTitle());
startTitle(ol,QCString());
ol.parseText(theTranslator->trLegendTitle());
endTitle(ol,QCString(),QCString());
ol.startContents();
QCString legendDocs = theTranslator->trLegendDocs();
int s = legendDocs.find("<center>");
int e = legendDocs.find("</center>");
QCString imgExt = getDotImageExtension();
if (imgExt=="svg" && s!=-1 && e!=-1)
{
legendDocs = legendDocs.left(s+8) + "[!-- " + "SVG 0 --]" + legendDocs.mid(e);
//printf("legendDocs=%s\n",qPrint(legendDocs));
}
{
auto fd = createFileDef("","graph_legend.dox");
ol.generateDoc("graph_legend",1,fd.get(),nullptr,legendDocs,FALSE,FALSE,
QCString(),FALSE,FALSE,FALSE);
}
// restore config settings
Config_updateBool(STRIP_CODE_COMMENTS,oldStripCommentsState);
Config_updateBool(CREATE_SUBDIRS,oldCreateSubdirs);
endFile(ol);
ol.popGeneratorState();
}
//----------------------------------------------------------------------------
/*!
* write groups as hierarchical trees
*/
static void writeGroupTreeNode(OutputList &ol, const GroupDef *gd, int level, FTVHelp* ftv, bool addToIndex)
{
//bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
//bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
if (level>20)
{
warn(gd->getDefFileName(),gd->getDefLine(),
"maximum nesting level exceeded for group %s: check for possible recursive group relation!",qPrint(gd->name())
);
return;
}
/* Some groups should appear twice under different parent-groups.
* That is why we should not check if it was visited
*/
if ((!gd->isASubGroup() || level>0) && gd->isVisible() && gd->isVisibleInHierarchy())
{
//printf("gd->name()=%s #members=%d\n",qPrint(gd->name()),gd->countMembers());
// write group info
bool hasSubGroups = !gd->getSubGroups().empty();
bool hasSubPages = !gd->getPages().empty();
size_t numSubItems = 0;
for (const auto &ml : gd->getMemberLists())
{
if (ml->listType().isDocumentation())
{
numSubItems += ml->size();
}
}
numSubItems += gd->getNamespaces().size();
numSubItems += gd->getClasses().size();
numSubItems += gd->getFiles().size();
numSubItems += gd->getConcepts().size();
numSubItems += gd->getDirs().size();
numSubItems += gd->getPages().size();
bool isDir = hasSubGroups || hasSubPages || numSubItems>0;
//printf("gd='%s': pageDict=%d\n",qPrint(gd->name()),gd->pageDict->count());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(isDir,gd->groupTitle(),gd->getReference(),gd->getOutputFileBase(),QCString(),isDir,TRUE);
Doxygen::indexList->incContentsDepth();
}
if (ftv)
{
ftv->addContentsItem(hasSubGroups,gd->groupTitle(),
gd->getReference(),gd->getOutputFileBase(),QCString(),
FALSE,FALSE,gd);
ftv->incContentsDepth();
}
//ol.writeListItem();
//ol.startTextLink(gd->getOutputFileBase(),0);
//parseText(ol,gd->groupTitle());
//ol.endTextLink();
ol.startIndexListItem();
ol.startIndexItem(gd->getReference(),gd->getOutputFileBase());
ol.parseText(gd->groupTitle());
ol.endIndexItem(gd->getReference(),gd->getOutputFileBase());
if (gd->isReference())
{
ol.startTypewriter();
ol.docify(" [external]");
ol.endTypewriter();
}
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Group))
{
if (lde->kind()==LayoutDocEntry::MemberDef && addToIndex)
{
const LayoutDocEntryMemberDef *lmd = dynamic_cast<const LayoutDocEntryMemberDef*>(lde.get());
if (lmd)
{
MemberList *ml = gd->getMemberList(lmd->type);
if (ml)
{
for (const auto &md : *ml)
{
const MemberVector &enumList = md->enumFieldList();
isDir = !enumList.empty() && md->isEnumerate();
if (md->isVisible() && !md->isAnonymous())
{
Doxygen::indexList->addContentsItem(isDir,
md->qualifiedName(),md->getReference(),
md->getOutputFileBase(),md->anchor(),FALSE,addToIndex);
}
if (isDir)
{
Doxygen::indexList->incContentsDepth();
for (const auto &emd : enumList)
{
if (emd->isVisible())
{
Doxygen::indexList->addContentsItem(FALSE,
emd->qualifiedName(),emd->getReference(),emd->getOutputFileBase(),
emd->anchor(),FALSE,addToIndex);
}
}
Doxygen::indexList->decContentsDepth();
}
}
}
}
}
else if (lde->kind()==LayoutDocEntry::GroupClasses && addToIndex)
{
for (const auto &cd : gd->getClasses())
{
//bool nestedClassInSameGroup =
// cd->getOuterScope() && cd->getOuterScope()->definitionType()==Definition::TypeClass &&
// cd->getOuterScope()->partOfGroups().empty() && cd->getOuterScope()->partOfGroups()->contains(gd);
//printf("===== GroupClasses: %s visible=%d nestedClassInSameGroup=%d\n",qPrint(cd->name()),cd->isVisible(),nestedClassInSameGroup);
if (cd->isVisible() /*&& !nestedClassInSameGroup*/)
{
addMembersToIndex(cd,
LayoutDocManager::Class,
cd->displayName(),
cd->anchor(),
addToIndex,
TRUE);
}
}
}
else if (lde->kind()==LayoutDocEntry::GroupNamespaces && addToIndex && Config_getBool(SHOW_NAMESPACES))
{
for (const auto &nd : gd->getNamespaces())
{
if (nd->isVisible())
{
Doxygen::indexList->addContentsItem(FALSE,
nd->displayName(),nd->getReference(),
nd->getOutputFileBase(),QCString(),FALSE,Config_getBool(SHOW_NAMESPACES));
}
}
}
else if (lde->kind()==LayoutDocEntry::GroupConcepts && addToIndex)
{
for (const auto &cd : gd->getConcepts())
{
if (cd->isVisible())
{
Doxygen::indexList->addContentsItem(FALSE,
cd->displayName(),cd->getReference(),
cd->getOutputFileBase(),QCString(),FALSE,addToIndex);
}
}
}
else if (lde->kind()==LayoutDocEntry::GroupFiles && addToIndex)
{
for (const auto &fd : gd->getFiles())
{
if (fd->isVisible())
{
Doxygen::indexList->addContentsItem(FALSE,
fd->displayName(),fd->getReference(),
fd->getOutputFileBase(),QCString(),FALSE,fd->isLinkableViaGroup());
}
}
}
else if (lde->kind()==LayoutDocEntry::GroupDirs && addToIndex)
{
for (const auto &dd : gd->getDirs())
{
if (dd->isVisible())
{
Doxygen::indexList->addContentsItem(FALSE,
dd->shortName(),dd->getReference(),
dd->getOutputFileBase(),QCString(),FALSE,FALSE);
}
}
}
else if (lde->kind()==LayoutDocEntry::GroupPageDocs && addToIndex)
{
for (const auto &pd : gd->getPages())
{
const SectionInfo *si=nullptr;
if (!pd->name().isEmpty()) si=SectionManager::instance().find(pd->name());
hasSubPages = pd->hasSubPages();
bool hasSections = pd->hasSections();
Doxygen::indexList->addContentsItem(
hasSubPages || hasSections,
pd->title(),
gd->getReference(),
gd->getOutputFileBase(),
si ? si->label() : QCString(),
hasSubPages || hasSections,
TRUE); // addToNavIndex
if (hasSections || hasSubPages)
{
Doxygen::indexList->incContentsDepth();
}
if (hasSections)
{
pd->addSectionsToIndex();
}
writePages(pd,nullptr);
if (hasSections || hasSubPages)
{
Doxygen::indexList->decContentsDepth();
}
}
}
else if (lde->kind()==LayoutDocEntry::GroupNestedGroups)
{
if (!gd->getSubGroups().empty())
{
startIndexHierarchy(ol,level+1);
for (const auto &subgd : gd->getSubGroups())
{
writeGroupTreeNode(ol,subgd,level+1,ftv,addToIndex);
}
endIndexHierarchy(ol,level+1);
}
}
}
ol.endIndexListItem();
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
if (ftv)
{
ftv->decContentsDepth();
}
//gd->visited=TRUE;
}
}
static void writeGroupHierarchy(OutputList &ol, FTVHelp* ftv,bool addToIndex)
{
if (ftv)
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
}
startIndexHierarchy(ol,0);
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (gd->isVisibleInHierarchy())
{
writeGroupTreeNode(ol,gd.get(),0,ftv,addToIndex);
}
}
endIndexHierarchy(ol,0);
if (ftv)
{
ol.popGeneratorState();
}
}
//----------------------------------------------------------------------------
static void writeTopicIndex(OutputList &ol)
{
if (Index::instance().numDocumentedGroups()==0) return;
ol.pushGeneratorState();
// 1.{
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Topics);
QCString title = lne ? lne->title() : theTranslator->trTopics();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"topics",QCString(),title,HighlightedItem::Topics);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.parseText(lne ? lne->intro() : theTranslator->trTopicListDescription());
ol.endTextBlock();
// ---------------
// Normal group index for Latex/RTF
// ---------------
// 2.{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
Doxygen::indexList->disable();
writeGroupHierarchy(ol,nullptr,FALSE);
Doxygen::indexList->enable();
ol.popGeneratorState();
// 2.}
// ---------------
// interactive group index for HTML
// ---------------
// 2.{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"topics",QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
FTVHelp ftv(false);
writeGroupHierarchy(ol,&ftv,addToIndex);
TextStream t;
ftv.generateTreeViewInline(t);
ol.disableAllBut(OutputType::Html);
ol.writeString(t.str().c_str());
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
ol.popGeneratorState();
// 2.}
endFile(ol);
ol.popGeneratorState();
// 1.}
}
//----------------------------------------------------------------------------
static void writeModuleTreeNode(OutputList &ol, const ModuleDef *mod,
FTVHelp* ftv, bool addToIndex)
{
int visibleMembers = mod->countVisibleMembers();
bool isDir=visibleMembers>0;
if (addToIndex)
{
Doxygen::indexList->addContentsItem(isDir,mod->name(),
mod->getReference(),mod->getOutputFileBase(),QCString(),isDir,TRUE);
}
if (ftv)
{
ftv->addContentsItem(false,mod->name(),
mod->getReference(),mod->getOutputFileBase(),QCString(),
false,false,mod);
}
ol.startIndexListItem();
ol.startIndexItem(mod->getReference(),mod->getOutputFileBase());
ol.parseText(mod->qualifiedName());
ol.endIndexItem(mod->getReference(),mod->getOutputFileBase());
if (mod->isReference())
{
ol.startTypewriter();
ol.docify(" [external]");
ol.endTypewriter();
}
if (addToIndex && isDir)
{
Doxygen::indexList->incContentsDepth();
}
if (isDir)
{
//ftv->incContentsDepth();
writeClassTree(mod->getClasses(),nullptr,addToIndex,FALSE,ClassDef::Class);
writeConceptList(mod->getConcepts(),nullptr,addToIndex);
writeModuleMembers(mod,addToIndex);
//ftv->decContentsDepth();
}
if (addToIndex && isDir)
{
Doxygen::indexList->decContentsDepth();
}
ol.endIndexListItem();
}
//----------------------------------------------------------------------------
static void writeModuleList(OutputList &ol, FTVHelp *ftv,bool addToIndex)
{
if (ftv)
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
}
startIndexHierarchy(ol,0);
for (const auto &mod : ModuleManager::instance().modules())
{
if (mod->isPrimaryInterface())
{
writeModuleTreeNode(ol,mod.get(),ftv,addToIndex);
}
}
endIndexHierarchy(ol,0);
if (ftv)
{
ol.popGeneratorState();
}
}
//----------------------------------------------------------------------------
static void writeModuleIndex(OutputList &ol)
{
if (ModuleManager::instance().numDocumentedModules()==0) return;
ol.pushGeneratorState();
// 1.{
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ModuleList);
if (lne==nullptr) lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Modules); // fall back
QCString title = lne ? lne->title() : theTranslator->trModules();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"modules",QCString(),title,HighlightedItem::Modules);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.parseText(lne ? lne->intro() : theTranslator->trModulesListDescription(Config_getBool(EXTRACT_ALL)));
ol.endTextBlock();
// ---------------
// Normal group index for Latex/RTF
// ---------------
// 2.{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
Doxygen::indexList->disable();
writeModuleList(ol,nullptr,FALSE);
Doxygen::indexList->enable();
ol.popGeneratorState();
// 2.}
// ---------------
// interactive group index for HTML
// ---------------
// 2.{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"modules",QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
FTVHelp ftv(false);
writeModuleList(ol,&ftv,addToIndex);
TextStream t;
ftv.generateTreeViewInline(t);
ol.writeString(t.str().c_str());
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
ol.popGeneratorState();
// 2.}
endFile(ol);
ol.popGeneratorState();
// 1.}
}
//----------------------------------------------------------------------------
static void writeConceptList(const ConceptLinkedRefMap &concepts, FTVHelp *ftv,bool addToIndex)
{
for (const auto &cd : concepts)
{
if (cd->isLinkableInProject())
{
if (ftv)
{
ftv->addContentsItem(false,cd->displayName(FALSE),cd->getReference(),
cd->getOutputFileBase(),QCString(),false,cd->partOfGroups().empty(),cd);
}
if (addToIndex)
{
Doxygen::indexList->addContentsItem(false,cd->displayName(FALSE),cd->getReference(),
cd->getOutputFileBase(),QCString(),false,cd->partOfGroups().empty());
}
}
}
}
static void writeConceptTreeInsideNamespaceElement(const NamespaceDef *nd,FTVHelp *ftv,
bool rootOnly, bool addToIndex);
static void writeConceptTreeInsideNamespace(const NamespaceLinkedRefMap &nsLinkedMap,FTVHelp *ftv,
bool rootOnly, bool addToIndex)
{
for (const auto &nd : nsLinkedMap)
{
writeConceptTreeInsideNamespaceElement(nd,ftv,rootOnly,addToIndex);
}
}
static void writeConceptTreeInsideNamespaceElement(const NamespaceDef *nd,FTVHelp *ftv,
bool rootOnly, bool addToIndex)
{
if (!nd->isAnonymous() &&
(!rootOnly || nd->getOuterScope()==Doxygen::globalScope))
{
bool isDir = namespaceHasNestedConcept(nd);
bool isLinkable = nd->isLinkableInProject();
//printf("writeConceptTreeInsideNamespaceElement namespace %s isLinkable=%d isDir=%d\n",qPrint(nd->name()),isLinkable,isDir);
QCString ref;
QCString file;
if (isLinkable)
{
ref = nd->getReference();
file = nd->getOutputFileBase();
}
if (isDir)
{
ftv->addContentsItem(isDir,nd->localName(),ref,file,QCString(),FALSE,TRUE,nd);
if (addToIndex)
{
// the namespace entry is already shown under the namespace list so don't
// add it to the nav index and don't create a separate index file for it otherwise
// it will overwrite the one written for the namespace list.
Doxygen::indexList->addContentsItem(isDir,nd->localName(),ref,file,QCString(),
false, // separateIndex
false // addToNavIndex
);
}
if (addToIndex)
{
Doxygen::indexList->incContentsDepth();
}
ftv->incContentsDepth();
writeConceptTreeInsideNamespace(nd->getNamespaces(),ftv,FALSE,addToIndex);
writeConceptList(nd->getConcepts(),ftv,addToIndex);
ftv->decContentsDepth();
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
}
}
static void writeConceptRootList(FTVHelp *ftv,bool addToIndex)
{
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if ((cd->getOuterScope()==nullptr ||
cd->getOuterScope()==Doxygen::globalScope) && cd->isLinkableInProject()
)
{
//printf("*** adding %s hasSubPages=%d hasSections=%d\n",qPrint(pageTitle),hasSubPages,hasSections);
ftv->addContentsItem(
false,cd->localName(),cd->getReference(),cd->getOutputFileBase(),
QCString(),false,cd->partOfGroups().empty(),cd.get());
if (addToIndex)
{
Doxygen::indexList->addContentsItem(
false,cd->localName(),cd->getReference(),cd->getOutputFileBase(),
QCString(),false,cd->partOfGroups().empty(),cd.get());
}
}
}
}
static void writeConceptIndex(OutputList &ol)
{
if (Index::instance().numDocumentedConcepts()==0) return;
ol.pushGeneratorState();
// 1.{
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Concepts);
QCString title = lne ? lne->title() : theTranslator->trConceptList();
bool addToIndex = lne==nullptr || lne->visible();
startFile(ol,"concepts",QCString(),title,HighlightedItem::Concepts);
startTitle(ol,QCString());
ol.parseText(title);
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startTextBlock();
ol.parseText(lne ? lne->intro() : theTranslator->trConceptListDescription(Config_getBool(EXTRACT_ALL)));
ol.endTextBlock();
// ---------------
// Normal group index for Latex/RTF
// ---------------
// 2.{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
bool first=TRUE;
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject())
{
if (first)
{
ol.startIndexList();
first=FALSE;
}
//ol.writeStartAnnoItem("namespace",nd->getOutputFileBase(),0,nd->name());
ol.startIndexKey();
ol.writeObjectLink(QCString(),cd->getOutputFileBase(),QCString(),cd->displayName());
ol.endIndexKey();
bool hasBrief = !cd->briefDescription().isEmpty();
ol.startIndexValue(hasBrief);
if (hasBrief)
{
//ol.docify(" (");
ol.generateDoc(
cd->briefFile(),cd->briefLine(),
cd.get(),nullptr,
cd->briefDescription(TRUE),
FALSE, // index words
FALSE, // isExample
QCString(), // example name
TRUE, // single line
TRUE, // link from index
Config_getBool(MARKDOWN_SUPPORT)
);
//ol.docify(")");
}
ol.endIndexValue(cd->getOutputFileBase(),hasBrief);
}
}
if (!first) ol.endIndexList();
ol.popGeneratorState();
// 2.}
// ---------------
// interactive group index for HTML
// ---------------
// 2.{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{
if (addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,title,QCString(),"concepts",QCString(),TRUE,TRUE);
Doxygen::indexList->incContentsDepth();
}
FTVHelp ftv(false);
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
writeConceptTreeInsideNamespaceElement(nd.get(),&ftv,true,addToIndex);
}
writeConceptRootList(&ftv,addToIndex);
TextStream t;
ftv.generateTreeViewInline(t);
ol.writeString(t.str().c_str());
if (addToIndex)
{
Doxygen::indexList->decContentsDepth();
}
}
ol.popGeneratorState();
// 2.}
endFile(ol);
ol.popGeneratorState();
// 1.}
}
//----------------------------------------------------------------------------
static void writeUserGroupStubPage(OutputList &ol,LayoutNavEntry *lne)
{
if (lne->baseFile().startsWith("usergroup"))
{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
startFile(ol,lne->baseFile(),QCString(),lne->title(),HighlightedItem::UserGroup);
startTitle(ol,QCString());
ol.parseText(lne->title());
endTitle(ol,QCString(),QCString());
ol.startContents();
int count=0;
for (const auto &entry: lne->children())
{
if (entry->visible()) count++;
}
if (count>0)
{
ol.writeString("<ul>\n");
for (const auto &entry: lne->children())
{
if (entry->visible())
{
ol.writeString("<li><a href=\""+entry->url()+"\"><span>"+
fixSpaces(entry->title())+"</span></a></li>\n");
}
}
ol.writeString("</ul>\n");
}
endFile(ol);
ol.popGeneratorState();
}
}
//----------------------------------------------------------------------------
static void writeIndex(OutputList &ol)
{
bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
QCString projectName = Config_getString(PROJECT_NAME);
// save old generator state
ol.pushGeneratorState();
QCString projPrefix;
if (!projectName.isEmpty())
{
projPrefix=projectName+" ";
}
//--------------------------------------------------------------------
// write HTML index
//--------------------------------------------------------------------
ol.disableAllBut(OutputType::Html);
QCString defFileName =
Doxygen::mainPage ? Doxygen::mainPage->docFile() : QCString("[generated]");
int defLine =
Doxygen::mainPage ? Doxygen::mainPage->docLine() : -1;
QCString title;
if (!mainPageHasTitle())
{
title = theTranslator->trMainPage();
}
else if (Doxygen::mainPage)
{
title = filterTitle(Doxygen::mainPage->title());
}
QCString indexName="index";
ol.startFile(indexName,QCString(),title);
if (Doxygen::mainPage)
{
bool hasSubs = Doxygen::mainPage->hasSubPages() || Doxygen::mainPage->hasSections();
bool hasTitle = !projectName.isEmpty() && mainPageHasTitle() && qstricmp(title,projectName)!=0;
//printf("** mainPage title=%s hasTitle=%d hasSubs=%d\n",qPrint(title),hasTitle,hasSubs);
if (hasTitle) // to avoid duplicate entries in the treeview
{
Doxygen::indexList->addContentsItem(hasSubs,
title,
QCString(),
indexName,
QCString(),
hasSubs,
TRUE);
}
if (hasSubs)
{
writePages(Doxygen::mainPage.get(),nullptr);
}
}
ol.startQuickIndices();
if (!Config_getBool(DISABLE_INDEX))
{
ol.writeQuickLinks(HighlightedItem::Main,QCString());
}
ol.endQuickIndices();
ol.writeSplitBar(indexName);
ol.writeSearchInfo();
bool headerWritten=FALSE;
if (Doxygen::mainPage)
{
if (!Doxygen::mainPage->title().isEmpty())
{
if (Doxygen::mainPage->title().lower() != "notitle")
ol.startPageDoc(Doxygen::mainPage->title());
else
ol.startPageDoc("");
}
else
ol.startPageDoc(projectName);
}
if (Doxygen::mainPage && !Doxygen::mainPage->title().isEmpty())
{
if (Doxygen::mainPage->title().lower()!="notitle")
{
ol.startHeaderSection();
ol.startTitleHead(QCString());
ol.generateDoc(Doxygen::mainPage->docFile(),Doxygen::mainPage->getStartBodyLine(),
Doxygen::mainPage.get(),nullptr,Doxygen::mainPage->title(),false,false,
QCString(),true,false,Config_getBool(MARKDOWN_SUPPORT));
headerWritten = TRUE;
}
}
else
{
if (!projectName.isEmpty())
{
ol.startHeaderSection();
ol.startTitleHead(QCString());
ol.parseText(theTranslator->trDocumentation(projectName));
headerWritten = TRUE;
}
}
if (headerWritten)
{
ol.endTitleHead(QCString(),QCString());
ol.endHeaderSection();
}
ol.startContents();
if (Config_getBool(DISABLE_INDEX) && Doxygen::mainPage==nullptr)
{
ol.writeQuickLinks(HighlightedItem::Main,QCString());
}
if (Doxygen::mainPage)
{
if (Doxygen::mainPage->localToc().isHtmlEnabled() && Doxygen::mainPage->hasSections())
{
Doxygen::mainPage->writeToc(ol,Doxygen::mainPage->localToc());
}
ol.startTextBlock();
ol.generateDoc(defFileName,defLine,Doxygen::mainPage.get(),nullptr,
Doxygen::mainPage->documentation(),true,false,
QCString(),false,false,Config_getBool(MARKDOWN_SUPPORT));
ol.endTextBlock();
ol.endPageDoc();
}
QCString fn = Crawlmap::crawlFileName;
addHtmlExtensionIfMissing(fn);
ol.writeString("<a href=\"" + fn + "\"></a>\n");
Doxygen::indexList->addIndexFile(fn);
endFile(ol);
ol.disable(OutputType::Html);
//--------------------------------------------------------------------
// write LaTeX/RTF index
//--------------------------------------------------------------------
ol.enable(OutputType::Latex);
ol.enable(OutputType::Docbook);
ol.enable(OutputType::RTF);
if (Doxygen::mainPage)
{
msg("Generating main page...\n");
Doxygen::mainPage->writeDocumentation(ol);
}
ol.startFile("refman",QCString(),QCString());
ol.startIndexSection(IndexSection::isTitlePageStart);
ol.disable(OutputType::Latex);
ol.disable(OutputType::Docbook);
if (projPrefix.isEmpty())
{
ol.parseText(theTranslator->trReferenceManual());
}
else
{
ol.parseText(projPrefix);
}
if (!Config_getString(PROJECT_NUMBER).isEmpty())
{
ol.startProjectNumber();
ol.generateDoc(defFileName,defLine,Doxygen::mainPage.get(),nullptr,Config_getString(PROJECT_NUMBER),false,false,
QCString(),false,false,Config_getBool(MARKDOWN_SUPPORT));
ol.endProjectNumber();
}
ol.endIndexSection(IndexSection::isTitlePageStart);
ol.startIndexSection(IndexSection::isTitlePageAuthor);
ol.parseText(theTranslator->trGeneratedBy());
ol.endIndexSection(IndexSection::isTitlePageAuthor);
ol.enable(OutputType::Latex);
ol.enable(OutputType::Docbook);
ol.lastIndexPage();
if (Doxygen::mainPage)
{
ol.startIndexSection(IndexSection::isMainPage);
ol.endIndexSection(IndexSection::isMainPage);
}
const auto &index = Index::instance();
if (index.numDocumentedPages()>0)
{
ol.startIndexSection(IndexSection::isPageDocumentation);
ol.endIndexSection(IndexSection::isPageDocumentation);
}
ol.disable(OutputType::Docbook);
if (!Config_getBool(LATEX_HIDE_INDICES))
{
//if (indexedPages>0)
//{
// ol.startIndexSection(isPageIndex);
// ol.parseText(/*projPrefix+*/ theTranslator->trPageIndex());
// ol.endIndexSection(isPageIndex);
//}
if (index.numDocumentedModules()>0)
{
ol.startIndexSection(IndexSection::isModuleIndex);
ol.parseText(/*projPrefix+*/ theTranslator->trModuleIndex());
ol.endIndexSection(IndexSection::isModuleIndex);
}
if (index.numDocumentedGroups()>0)
{
ol.startIndexSection(IndexSection::isTopicIndex);
ol.parseText(/*projPrefix+*/ theTranslator->trTopicIndex());
ol.endIndexSection(IndexSection::isTopicIndex);
}
if (Config_getBool(SHOW_NAMESPACES) && (index.numDocumentedNamespaces()>0))
{
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Namespaces);
if (lne)
{
ol.startIndexSection(IndexSection::isNamespaceIndex);
ol.parseText(/*projPrefix+*/(fortranOpt?theTranslator->trModulesIndex():theTranslator->trNamespaceIndex()));
ol.endIndexSection(IndexSection::isNamespaceIndex);
}
}
if (index.numDocumentedConcepts()>0)
{
ol.startIndexSection(IndexSection::isConceptIndex);
ol.parseText(/*projPrefix+*/theTranslator->trConceptIndex());
ol.endIndexSection(IndexSection::isConceptIndex);
}
if (index.numHierarchyInterfaces()>0)
{
ol.startIndexSection(IndexSection::isClassHierarchyIndex);
ol.parseText(/*projPrefix+*/theTranslator->trHierarchicalIndex());
ol.endIndexSection(IndexSection::isClassHierarchyIndex);
}
if (index.numHierarchyClasses()>0)
{
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::ClassHierarchy);
if (lne)
{
ol.startIndexSection(IndexSection::isClassHierarchyIndex);
ol.parseText(/*projPrefix+*/
(fortranOpt ? theTranslator->trCompoundIndexFortran() :
vhdlOpt ? theTranslator->trHierarchicalIndex() :
theTranslator->trHierarchicalIndex()
));
ol.endIndexSection(IndexSection::isClassHierarchyIndex);
}
}
if (index.numHierarchyExceptions()>0)
{
ol.startIndexSection(IndexSection::isClassHierarchyIndex);
ol.parseText(/*projPrefix+*/theTranslator->trHierarchicalIndex());
ol.endIndexSection(IndexSection::isClassHierarchyIndex);
}
if (index.numAnnotatedInterfacesPrinted()>0)
{
ol.startIndexSection(IndexSection::isCompoundIndex);
ol.parseText(/*projPrefix+*/theTranslator->trInterfaceIndex());
ol.endIndexSection(IndexSection::isCompoundIndex);
}
if (index.numAnnotatedClassesPrinted()>0)
{
ol.startIndexSection(IndexSection::isCompoundIndex);
ol.parseText(/*projPrefix+*/
(fortranOpt ? theTranslator->trCompoundIndexFortran() :
vhdlOpt ? theTranslator->trDesignUnitIndex() :
theTranslator->trCompoundIndex()
));
ol.endIndexSection(IndexSection::isCompoundIndex);
}
if (index.numAnnotatedStructsPrinted()>0)
{
ol.startIndexSection(IndexSection::isCompoundIndex);
ol.parseText(/*projPrefix+*/theTranslator->trStructIndex());
ol.endIndexSection(IndexSection::isCompoundIndex);
}
if (index.numAnnotatedExceptionsPrinted()>0)
{
ol.startIndexSection(IndexSection::isCompoundIndex);
ol.parseText(/*projPrefix+*/theTranslator->trExceptionIndex());
ol.endIndexSection(IndexSection::isCompoundIndex);
}
if (Config_getBool(SHOW_FILES) && index.numDocumentedFiles()>0)
{
ol.startIndexSection(IndexSection::isFileIndex);
ol.parseText(/*projPrefix+*/theTranslator->trFileIndex());
ol.endIndexSection(IndexSection::isFileIndex);
}
}
ol.enable(OutputType::Docbook);
if (index.numDocumentedModules()>0)
{
ol.startIndexSection(IndexSection::isModuleDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trModuleDocumentation());
ol.endIndexSection(IndexSection::isModuleDocumentation);
}
if (index.numDocumentedGroups()>0)
{
ol.startIndexSection(IndexSection::isTopicDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trTopicDocumentation());
ol.endIndexSection(IndexSection::isTopicDocumentation);
}
if (index.numDocumentedNamespaces()>0)
{
ol.startIndexSection(IndexSection::isNamespaceDocumentation);
ol.parseText(/*projPrefix+*/(fortranOpt?theTranslator->trModuleDocumentation():theTranslator->trNamespaceDocumentation()));
ol.endIndexSection(IndexSection::isNamespaceDocumentation);
}
if (index.numDocumentedConcepts()>0)
{
ol.startIndexSection(IndexSection::isConceptDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trConceptDocumentation());
ol.endIndexSection(IndexSection::isConceptDocumentation);
}
if (index.numAnnotatedInterfacesPrinted()>0)
{
ol.startIndexSection(IndexSection::isClassDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trInterfaceDocumentation());
ol.endIndexSection(IndexSection::isClassDocumentation);
}
if (index.numAnnotatedClassesPrinted()>0)
{
ol.startIndexSection(IndexSection::isClassDocumentation);
ol.parseText(/*projPrefix+*/(fortranOpt?theTranslator->trTypeDocumentation():theTranslator->trClassDocumentation()));
ol.endIndexSection(IndexSection::isClassDocumentation);
}
if (index.numAnnotatedStructsPrinted()>0)
{
ol.startIndexSection(IndexSection::isClassDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trStructDocumentation());
ol.endIndexSection(IndexSection::isClassDocumentation);
}
if (index.numAnnotatedExceptionsPrinted()>0)
{
ol.startIndexSection(IndexSection::isClassDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trExceptionDocumentation());
ol.endIndexSection(IndexSection::isClassDocumentation);
}
if (Config_getBool(SHOW_FILES) && index.numDocumentedFiles()>0)
{
ol.startIndexSection(IndexSection::isFileDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trFileDocumentation());
ol.endIndexSection(IndexSection::isFileDocumentation);
}
if (!Doxygen::exampleLinkedMap->empty())
{
ol.startIndexSection(IndexSection::isExampleDocumentation);
ol.parseText(/*projPrefix+*/theTranslator->trExamples());
ol.endIndexSection(IndexSection::isExampleDocumentation);
}
ol.endIndexSection(IndexSection::isEndIndex);
endFile(ol);
ol.popGeneratorState();
}
static std::vector<bool> indexWritten;
static void writeIndexHierarchyEntries(OutputList &ol,const LayoutNavEntryList &entries)
{
auto isRef = [](const QCString &s)
{
return s.startsWith("@ref") || s.startsWith("\\ref");
};
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
const auto &index = Index::instance();
for (const auto &lne : entries)
{
LayoutNavEntry::Kind kind = lne->kind();
size_t idx = static_cast<size_t>(kind);
if (idx>=indexWritten.size())
{
size_t oldSize = indexWritten.size();
size_t newSize = idx+1;
indexWritten.resize(newSize);
for (size_t i=oldSize; i<newSize; i++) indexWritten.at(i)=FALSE;
}
//printf("starting %s kind=%d\n",qPrint(lne->title()),lne->kind());
bool addToIndex=lne->visible();
bool needsClosing=FALSE;
if (!indexWritten.at(idx))
{
switch(kind)
{
case LayoutNavEntry::MainPage:
msg("Generating index page...\n");
writeIndex(ol);
break;
case LayoutNavEntry::Pages:
msg("Generating page index...\n");
writePageIndex(ol);
break;
case LayoutNavEntry::Topics:
msg("Generating topic index...\n");
writeTopicIndex(ol);
break;
case LayoutNavEntry::Modules:
{
if (index.numDocumentedModules()>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString());
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
}
break;
case LayoutNavEntry::ModuleList:
msg("Generating module index...\n");
writeModuleIndex(ol);
break;
case LayoutNavEntry::ModuleMembers:
msg("Generating module member index...\n");
writeModuleMemberIndex(ol);
break;
case LayoutNavEntry::Namespaces:
{
bool showNamespaces = Config_getBool(SHOW_NAMESPACES);
if (showNamespaces)
{
if (index.numDocumentedNamespaces()>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString());
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
if (LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Namespaces)!=lne.get()) // for backward compatibility with old layout file
{
msg("Generating namespace index...\n");
writeNamespaceIndex(ol);
}
}
}
break;
case LayoutNavEntry::NamespaceList:
{
bool showNamespaces = Config_getBool(SHOW_NAMESPACES);
if (showNamespaces)
{
msg("Generating namespace index...\n");
writeNamespaceIndex(ol);
}
}
break;
case LayoutNavEntry::NamespaceMembers:
msg("Generating namespace member index...\n");
writeNamespaceMemberIndex(ol);
break;
case LayoutNavEntry::Classes:
if (index.numAnnotatedClasses()>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString());
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
if (LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Classes)!=lne.get()) // for backward compatibility with old layout file
{
msg("Generating annotated compound index...\n");
writeAnnotatedIndex(ol);
}
break;
case LayoutNavEntry::Concepts:
msg("Generating concept index...\n");
writeConceptIndex(ol);
break;
case LayoutNavEntry::ClassList:
msg("Generating annotated compound index...\n");
writeAnnotatedIndex(ol);
break;
case LayoutNavEntry::ClassIndex:
msg("Generating alphabetical compound index...\n");
writeAlphabeticalIndex(ol);
break;
case LayoutNavEntry::ClassHierarchy:
msg("Generating hierarchical class index...\n");
writeHierarchicalIndex(ol);
if (Config_getBool(HAVE_DOT) && Config_getBool(GRAPHICAL_HIERARCHY))
{
msg("Generating graphical class hierarchy...\n");
writeGraphicalClassHierarchy(ol);
}
break;
case LayoutNavEntry::ClassMembers:
if (!sliceOpt)
{
msg("Generating member index...\n");
writeClassMemberIndex(ol);
}
break;
case LayoutNavEntry::Interfaces:
if (sliceOpt && index.numAnnotatedInterfaces()>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString());
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
break;
case LayoutNavEntry::InterfaceList:
if (sliceOpt)
{
msg("Generating annotated interface index...\n");
writeAnnotatedInterfaceIndex(ol);
}
break;
case LayoutNavEntry::InterfaceIndex:
if (sliceOpt)
{
msg("Generating alphabetical interface index...\n");
writeAlphabeticalInterfaceIndex(ol);
}
break;
case LayoutNavEntry::InterfaceHierarchy:
if (sliceOpt)
{
msg("Generating hierarchical interface index...\n");
writeHierarchicalInterfaceIndex(ol);
if (Config_getBool(HAVE_DOT) && Config_getBool(GRAPHICAL_HIERARCHY))
{
msg("Generating graphical interface hierarchy...\n");
writeGraphicalInterfaceHierarchy(ol);
}
}
break;
case LayoutNavEntry::Structs:
if (sliceOpt && index.numAnnotatedStructs()>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString());
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
break;
case LayoutNavEntry::StructList:
if (sliceOpt)
{
msg("Generating annotated struct index...\n");
writeAnnotatedStructIndex(ol);
}
break;
case LayoutNavEntry::StructIndex:
if (sliceOpt)
{
msg("Generating alphabetical struct index...\n");
writeAlphabeticalStructIndex(ol);
}
break;
case LayoutNavEntry::Exceptions:
if (sliceOpt && index.numAnnotatedExceptions()>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString());
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
break;
case LayoutNavEntry::ExceptionList:
if (sliceOpt)
{
msg("Generating annotated exception index...\n");
writeAnnotatedExceptionIndex(ol);
}
break;
case LayoutNavEntry::ExceptionIndex:
if (sliceOpt)
{
msg("Generating alphabetical exception index...\n");
writeAlphabeticalExceptionIndex(ol);
}
break;
case LayoutNavEntry::ExceptionHierarchy:
if (sliceOpt)
{
msg("Generating hierarchical exception index...\n");
writeHierarchicalExceptionIndex(ol);
if (Config_getBool(HAVE_DOT) && Config_getBool(GRAPHICAL_HIERARCHY))
{
msg("Generating graphical exception hierarchy...\n");
writeGraphicalExceptionHierarchy(ol);
}
}
break;
case LayoutNavEntry::Files:
{
if (Config_getBool(SHOW_FILES) && index.numDocumentedFiles()>0 && addToIndex)
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString());
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
if (LayoutDocManager::instance().rootNavEntry()->find(LayoutNavEntry::Files)!=lne.get()) // for backward compatibility with old layout file
{
msg("Generating file index...\n");
writeFileIndex(ol);
}
}
break;
case LayoutNavEntry::FileList:
msg("Generating file index...\n");
writeFileIndex(ol);
break;
case LayoutNavEntry::FileGlobals:
msg("Generating file member index...\n");
writeFileMemberIndex(ol);
break;
case LayoutNavEntry::Examples:
msg("Generating example index...\n");
writeExampleIndex(ol);
break;
case LayoutNavEntry::User:
if (addToIndex)
{
// prepend a ! or ^ marker to the URL to avoid tampering with it
QCString url = correctURL(lne->url(),"!"); // add ! to relative URL
bool isRelative=url.at(0)=='!';
if (!url.isEmpty() && !isRelative) // absolute URL
{
url.prepend("^"); // prepend ^ to absolute URL
}
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),
url,QCString(),FALSE,isRef(lne->baseFile()) || isRelative);
}
break;
case LayoutNavEntry::UserGroup:
if (addToIndex)
{
QCString url = correctURL(lne->url(),"!"); // add ! to relative URL
if (!url.isEmpty())
{
if (url=="!") // result of a "[none]" url
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),QCString(),QCString(),FALSE,FALSE);
}
else
{
bool isRelative=url.at(0)=='!';
if (!isRelative) // absolute URL
{
url.prepend("^"); // prepend ^ to absolute URL
}
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),
url,QCString(),FALSE,isRef(lne->baseFile()) || isRelative);
}
}
else
{
Doxygen::indexList->addContentsItem(TRUE,lne->title(),QCString(),lne->baseFile(),QCString(),TRUE,TRUE);
}
Doxygen::indexList->incContentsDepth();
needsClosing=TRUE;
}
writeUserGroupStubPage(ol,lne.get());
break;
case LayoutNavEntry::None:
assert(kind != LayoutNavEntry::None); // should never happen, means not properly initialized
break;
}
if (kind!=LayoutNavEntry::User && kind!=LayoutNavEntry::UserGroup) // User entry may appear multiple times
{
indexWritten.at(idx)=TRUE;
}
}
writeIndexHierarchyEntries(ol,lne->children());
if (needsClosing)
{
switch(kind)
{
case LayoutNavEntry::Modules:
case LayoutNavEntry::Namespaces:
case LayoutNavEntry::Classes:
case LayoutNavEntry::Files:
case LayoutNavEntry::UserGroup:
Doxygen::indexList->decContentsDepth();
break;
default:
break;
}
}
//printf("ending %s kind=%d\n",qPrint(lne->title()),lne->kind());
}
}
static bool quickLinkVisible(LayoutNavEntry::Kind kind)
{
const auto &index = Index::instance();
bool showNamespaces = Config_getBool(SHOW_NAMESPACES);
bool showFiles = Config_getBool(SHOW_FILES);
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
switch (kind)
{
case LayoutNavEntry::MainPage: return TRUE;
case LayoutNavEntry::User: return TRUE;
case LayoutNavEntry::UserGroup: return TRUE;
case LayoutNavEntry::Pages: return index.numIndexedPages()>0;
case LayoutNavEntry::Topics: return index.numDocumentedGroups()>0;
case LayoutNavEntry::Modules: return index.numDocumentedModules()>0;
case LayoutNavEntry::ModuleList: return index.numDocumentedModules()>0;
case LayoutNavEntry::ModuleMembers: return index.numDocumentedModuleMembers(ModuleMemberHighlight::All)>0;
case LayoutNavEntry::Namespaces: return index.numDocumentedNamespaces()>0 && showNamespaces;
case LayoutNavEntry::NamespaceList: return index.numDocumentedNamespaces()>0 && showNamespaces;
case LayoutNavEntry::NamespaceMembers: return index.numDocumentedNamespaceMembers(NamespaceMemberHighlight::All)>0;
case LayoutNavEntry::Concepts: return index.numDocumentedConcepts()>0;
case LayoutNavEntry::Classes: return index.numAnnotatedClasses()>0;
case LayoutNavEntry::ClassList: return index.numAnnotatedClasses()>0;
case LayoutNavEntry::ClassIndex: return index.numAnnotatedClasses()>0;
case LayoutNavEntry::ClassHierarchy: return index.numHierarchyClasses()>0;
case LayoutNavEntry::ClassMembers: return index.numDocumentedClassMembers(ClassMemberHighlight::All)>0 && !sliceOpt;
case LayoutNavEntry::Interfaces: return index.numAnnotatedInterfaces()>0;
case LayoutNavEntry::InterfaceList: return index.numAnnotatedInterfaces()>0;
case LayoutNavEntry::InterfaceIndex: return index.numAnnotatedInterfaces()>0;
case LayoutNavEntry::InterfaceHierarchy: return index.numHierarchyInterfaces()>0;
case LayoutNavEntry::Structs: return index.numAnnotatedStructs()>0;
case LayoutNavEntry::StructList: return index.numAnnotatedStructs()>0;
case LayoutNavEntry::StructIndex: return index.numAnnotatedStructs()>0;
case LayoutNavEntry::Exceptions: return index.numAnnotatedExceptions()>0;
case LayoutNavEntry::ExceptionList: return index.numAnnotatedExceptions()>0;
case LayoutNavEntry::ExceptionIndex: return index.numAnnotatedExceptions()>0;
case LayoutNavEntry::ExceptionHierarchy: return index.numHierarchyExceptions()>0;
case LayoutNavEntry::Files: return index.numDocumentedFiles()>0 && showFiles;
case LayoutNavEntry::FileList: return index.numDocumentedFiles()>0 && showFiles;
case LayoutNavEntry::FileGlobals: return index.numDocumentedFileMembers(FileMemberHighlight::All)>0;
case LayoutNavEntry::Examples: return !Doxygen::exampleLinkedMap->empty();
case LayoutNavEntry::None: // should never happen, means not properly initialized
assert(kind != LayoutNavEntry::None);
return FALSE;
}
return FALSE;
}
template<class T>
void renderMemberIndicesAsJs(std::ostream &t,
std::function<std::size_t(std::size_t)> numDocumented,
std::function<Index::MemberIndexMap(std::size_t)> getMemberList,
const T *(*getInfo)(size_t hl),
std::size_t total)
{
// index items per category member lists
bool firstMember=TRUE;
for (std::size_t i=0;i<total;i++)
{
if (numDocumented(i)>0)
{
t << ",";
if (firstMember)
{
t << "children:[";
firstMember=FALSE;
}
t << "\n{text:\"" << convertToJSString(getInfo(i)->title) << "\",url:\""
<< convertToJSString(getInfo(i)->fname+Doxygen::htmlFileExtension) << "\"";
// Check if we have many members, then add sub entries per letter...
// quick alphabetical index
bool quickIndex = numDocumented(i)>maxItemsBeforeQuickIndex;
if (quickIndex)
{
bool multiPageIndex=FALSE;
if (numDocumented(i)>MAX_ITEMS_BEFORE_MULTIPAGE_INDEX)
{
multiPageIndex=TRUE;
}
t << ",children:[\n";
bool firstLetter=TRUE;
for (const auto &[letter,list] : getMemberList(i))
{
if (!firstLetter) t << ",\n";
QCString ci(letter);
QCString is(letterToLabel(ci));
QCString anchor;
QCString extension=Doxygen::htmlFileExtension;
QCString fullName = getInfo(i)->fname;
if (!multiPageIndex || firstLetter)
anchor=fullName+extension+"#index_";
else // other pages of multi page index
anchor=fullName+"_"+is+extension+"#index_";
t << "{text:\"" << convertToJSString(ci) << "\",url:\""
<< convertToJSString(anchor+convertToId(is)) << "\"}";
firstLetter=FALSE;
}
t << "]";
}
t << "}";
}
}
if (!firstMember)
{
t << "]";
}
}
static bool renderQuickLinksAsJs(std::ostream &t,LayoutNavEntry *root,bool first)
{
int count=0;
for (const auto &entry : root->children())
{
if (entry->visible() && quickLinkVisible(entry->kind())) count++;
}
if (count>0) // at least one item is visible
{
bool firstChild = TRUE;
if (!first) t << ",";
t << "children:[\n";
for (const auto &entry : root->children())
{
if (entry->visible() && quickLinkVisible(entry->kind()))
{
if (!firstChild) t << ",\n";
firstChild=FALSE;
QCString url = entry->url();
if (isURL(url)) url = "^" + url;
t << "{text:\"" << convertToJSString(entry->title()) << "\",url:\""
<< convertToJSString(url) << "\"";
bool hasChildren=FALSE;
if (entry->kind()==LayoutNavEntry::ModuleMembers)
{
auto numDoc = [](std::size_t i) {
return Index::instance().numDocumentedModuleMembers(static_cast<ModuleMemberHighlight::Enum>(i));
};
auto memList = [](std::size_t i) {
return Index::instance().isModuleIndexLetterUsed(static_cast<ModuleMemberHighlight::Enum>(i));
};
renderMemberIndicesAsJs(t,numDoc,memList,getMmhlInfo,static_cast<std::size_t>(ModuleMemberHighlight::Total));
}
if (entry->kind()==LayoutNavEntry::NamespaceMembers)
{
auto numDoc = [](std::size_t i) {
return Index::instance().numDocumentedNamespaceMembers(static_cast<NamespaceMemberHighlight::Enum>(i));
};
auto memList = [](std::size_t i) {
return Index::instance().isNamespaceIndexLetterUsed(static_cast<NamespaceMemberHighlight::Enum>(i));
};
renderMemberIndicesAsJs(t,numDoc,memList,getNmhlInfo,static_cast<std::size_t>(NamespaceMemberHighlight::Total));
}
else if (entry->kind()==LayoutNavEntry::ClassMembers)
{
auto numDoc = [](std::size_t i) {
return Index::instance().numDocumentedClassMembers(static_cast<ClassMemberHighlight::Enum>(i));
};
auto memList = [](std::size_t i) {
return Index::instance().isClassIndexLetterUsed(static_cast<ClassMemberHighlight::Enum>(i));
};
renderMemberIndicesAsJs(t,numDoc,memList,getCmhlInfo,static_cast<std::size_t>(ClassMemberHighlight::Total));
}
else if (entry->kind()==LayoutNavEntry::FileGlobals)
{
auto numDoc = [](std::size_t i) {
return Index::instance().numDocumentedFileMembers(static_cast<FileMemberHighlight::Enum>(i));
};
auto memList = [](std::size_t i) {
return Index::instance().isFileIndexLetterUsed(static_cast<FileMemberHighlight::Enum>(i));
};
renderMemberIndicesAsJs(t,numDoc,memList,getFmhlInfo,static_cast<std::size_t>(FileMemberHighlight::Total));
}
else // recursive into child list
{
hasChildren = renderQuickLinksAsJs(t,entry.get(),FALSE);
}
if (hasChildren) t << "]";
t << "}";
}
}
}
return count>0;
}
static void writeMenuData()
{
if (!Config_getBool(GENERATE_HTML) || Config_getBool(DISABLE_INDEX)) return;
QCString outputDir = Config_getBool(HTML_OUTPUT);
LayoutNavEntry *root = LayoutDocManager::instance().rootNavEntry();
std::ofstream t = Portable::openOutputStream(outputDir+"/menudata.js");
if (t.is_open())
{
t << JAVASCRIPT_LICENSE_TEXT;
t << "var menudata={";
bool hasChildren = renderQuickLinksAsJs(t,root,TRUE);
if (hasChildren) t << "]";
t << "}\n";
}
}
void writeIndexHierarchy(OutputList &ol)
{
writeMenuData();
LayoutNavEntry *lne = LayoutDocManager::instance().rootNavEntry();
if (lne)
{
writeIndexHierarchyEntries(ol,lne->children());
}
}
| 181,549
|
C++
|
.cpp
| 5,093
| 29.338504
| 158
| 0.631949
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,410
|
util.cpp
|
doxygen_doxygen/src/util.cpp
|
/*****************************************************************************
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include <stdlib.h>
#include <errno.h>
#include <math.h>
#include <limits.h>
#include <string.h>
#include <assert.h>
#include <mutex>
#include <unordered_set>
#include <codecvt>
#include <algorithm>
#include <ctime>
#include <cctype>
#include <cinttypes>
#include <sstream>
#include "md5.h"
#include "regex.h"
#include "util.h"
#include "message.h"
#include "classdef.h"
#include "filedef.h"
#include "doxygen.h"
#include "outputlist.h"
#include "defargs.h"
#include "language.h"
#include "config.h"
#include "htmlhelp.h"
#include "example.h"
#include "version.h"
#include "groupdef.h"
#include "reflist.h"
#include "pagedef.h"
#include "debug.h"
#include "searchindex.h"
#include "doxygen.h"
#include "textdocvisitor.h"
#include "latexdocvisitor.h"
#include "portable.h"
#include "parserintf.h"
#include "image.h"
#include "growbuf.h"
#include "entry.h"
#include "arguments.h"
#include "memberlist.h"
#include "classlist.h"
#include "namespacedef.h"
#include "membername.h"
#include "filename.h"
#include "membergroup.h"
#include "dirdef.h"
#include "htmlentity.h"
#include "symbolresolver.h"
#include "fileinfo.h"
#include "dir.h"
#include "utf8.h"
#include "textstream.h"
#include "indexlist.h"
#include "datetime.h"
#include "moduledef.h"
#include "trace.h"
#include "stringutil.h"
#define ENABLE_TRACINGSUPPORT 0
#if defined(__APPLE__) && ENABLE_TRACINGSUPPORT
#define TRACINGSUPPORT
#endif
#ifdef TRACINGSUPPORT
#include <execinfo.h>
#include <unistd.h>
#endif
//------------------------------------------------------------------------
#define REL_PATH_TO_ROOT "../../"
static const char *hex = "0123456789ABCDEF";
//------------------------------------------------------------------------
// TextGeneratorOLImpl implementation
//------------------------------------------------------------------------
TextGeneratorOLImpl::TextGeneratorOLImpl(OutputList &ol) : m_ol(ol)
{
}
void TextGeneratorOLImpl::writeString(std::string_view s,bool keepSpaces) const
{
if (s.empty()) return;
//printf("TextGeneratorOlImpl::writeString('%s',%d)\n",s,keepSpaces);
if (keepSpaces)
{
char cs[2];
cs[1]='\0';
for (size_t i=0;i<s.length();i++)
{
char c = s[i];
if (c==' ')
{
m_ol.writeNonBreakableSpace(1);
}
else
{
cs[0]=c;
m_ol.docify(cs);
}
}
}
else
{
m_ol.docify(QCString(s));
}
}
void TextGeneratorOLImpl::writeBreak(int indent) const
{
m_ol.lineBreak("typebreak");
for (int i=0;i<indent;i++)
{
m_ol.writeNonBreakableSpace(3);
}
}
void TextGeneratorOLImpl::writeLink(const QCString &extRef,const QCString &file,
const QCString &anchor,std::string_view text
) const
{
//printf("TextGeneratorOlImpl::writeLink('%s')\n",text);
m_ol.writeObjectLink(extRef,file,anchor,QCString(text));
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
// an inheritance tree of depth of 100000 should be enough for everyone :-)
const int maxInheritanceDepth = 100000;
/*!
Removes all anonymous scopes from string s
Possible examples:
\verbatim
"bla::@10::blep" => "bla::blep"
"bla::@10::@11::blep" => "bla::blep"
"@10::blep" => "blep"
" @10::blep" => "blep"
"@9::@10::blep" => "blep"
"bla::@1" => "bla"
"bla::@1::@2" => "bla"
"bla @1" => "bla"
\endverbatim
*/
QCString removeAnonymousScopes(const QCString &str)
{
std::string result;
if (str.isEmpty()) return QCString(result);
// helper to check if the found delimiter starts with a colon
auto startsWithColon = [](const std::string &del)
{
for (size_t i=0;i<del.size();i++)
{
if (del[i]=='@') return false;
else if (del[i]==':') return true;
}
return false;
};
// helper to check if the found delimiter ends with a colon
auto endsWithColon = [](const std::string &del)
{
for (int i=static_cast<int>(del.size())-1;i>=0;i--)
{
if (del[i]=='@') return false;
else if (del[i]==':') return true;
}
return false;
};
static const reg::Ex re(R"([\s:]*@\d+[\s:]*)");
std::string s = str.str();
reg::Iterator iter(s,re);
reg::Iterator end;
size_t p=0;
size_t sl=s.length();
bool needsSeparator=false;
for ( ; iter!=end ; ++iter)
{
const auto &match = *iter;
size_t i = match.position();
if (i>p) // add non-matching prefix
{
if (needsSeparator) result+="::";
needsSeparator=false;
result+=s.substr(p,i-p);
}
std::string delim = match.str();
needsSeparator = needsSeparator || (startsWithColon(delim) && endsWithColon(delim));
p = match.position()+match.length();
}
if (p<sl) // add trailing remainder
{
if (needsSeparator) result+="::";
result+=s.substr(p);
}
return result;
}
// replace anonymous scopes with __anonymous__ or replacement if provided
QCString replaceAnonymousScopes(const QCString &s,const QCString &replacement)
{
if (s.isEmpty()) return s;
static const reg::Ex marker(R"(@\d+)");
std::string result = reg::replace(s.str(),marker,
!replacement.isEmpty() ? replacement.data() : "__anonymous__");
//printf("replaceAnonymousScopes('%s')='%s'\n",qPrint(s),qPrint(result));
return QCString(result);
}
// strip anonymous left hand side part of the scope
QCString stripAnonymousNamespaceScope(const QCString &s)
{
int i=0,p=0,l=0;
QCString newScope;
int sl = static_cast<int>(s.length());
while ((i=getScopeFragment(s,p,&l))!=-1)
{
//printf("Scope fragment %s\n",qPrint(s.mid(i,l)));
if (Doxygen::namespaceLinkedMap->find(s.left(i+l))!=nullptr)
{
if (s.at(i)!='@')
{
if (!newScope.isEmpty()) newScope+="::";
newScope+=s.mid(i,l);
}
}
else if (i<sl)
{
if (!newScope.isEmpty()) newScope+="::";
newScope+=s.right(sl-i);
goto done;
}
p=i+l;
}
done:
//printf("stripAnonymousNamespaceScope('%s')='%s'\n",qPrint(s),qPrint(newScope));
return newScope;
}
void writePageRef(OutputList &ol,const QCString &cn,const QCString &mn)
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
if (Config_getBool(PDF_HYPERLINKS)) ol.disable(OutputType::Latex);
if (Config_getBool(RTF_HYPERLINKS)) ol.disable(OutputType::RTF);
ol.startPageRef();
ol.docify(theTranslator->trPageAbbreviation());
ol.endPageRef(cn,mn);
ol.popGeneratorState();
}
/*! Generate a place holder for a position in a list. Used for
* translators to be able to specify different elements orders
* depending on whether text flows from left to right or visa versa.
*/
QCString generateMarker(int id)
{
const int maxMarkerStrLen = 20;
char result[maxMarkerStrLen];
qsnprintf(result,maxMarkerStrLen,"@%d",id);
return result;
}
QCString removeLongPathMarker(QCString path)
{
#if defined(_WIN32)
if (path.startsWith("//?/")) // strip leading "\\?\" part from path
{
path=path.mid(4);
}
#endif
return path;
}
static QCString stripFromPath(const QCString &p,const StringVector &l)
{
// look at all the strings in the list and strip the longest match
QCString potential;
QCString path=removeLongPathMarker(p);
size_t length = 0;
for (const auto &s : l)
{
QCString prefix = s.c_str();
if (prefix.length() > length &&
qstricmp(path.left(prefix.length()),prefix)==0) // case insensitive compare
{
length = prefix.length();
potential = path.right(path.length()-prefix.length());
}
}
if (length>0) return potential;
return path;
}
/*! strip part of \a path if it matches
* one of the paths in the Config_getList(STRIP_FROM_PATH) list
*/
QCString stripFromPath(const QCString &path)
{
return stripFromPath(path,Config_getList(STRIP_FROM_PATH));
}
/*! strip part of \a path if it matches
* one of the paths in the Config_getList(INCLUDE_PATH) list
*/
QCString stripFromIncludePath(const QCString &path)
{
return stripFromPath(path,Config_getList(STRIP_FROM_INC_PATH));
}
/*! try to determine if \a name is a source or a header file name by looking
* at the extension. A number of variations is allowed in both upper and
* lower case) If anyone knows or uses another extension please let me know :-)
*/
EntryType guessSection(const QCString &name)
{
QCString n=name.lower();
static const std::unordered_set<std::string> sourceExt = {
"c","cc","cxx","cpp","c++","cppm","ccm","cxxm","c++m", // C/C++
"java", // Java
"cs", // C#
"m","mm", // Objective-C
"ii","ixx","ipp","i++","inl", // C/C++ inline
"xml","lex","sql" // others
};
static const std::unordered_set<std::string> headerExt = {
"h", "hh", "hxx", "hpp", "h++", "ixx", // C/C++ header
"idl", "ddl", "pidl", "ice" // IDL like
};
int lastDot = n.findRev('.');
if (lastDot!=-1)
{
QCString extension = n.mid(lastDot+1); // part after the last dot
if (sourceExt.find(extension.str())!=sourceExt.end())
{
return EntryType::makeSource();
}
if (headerExt.find(extension.str())!=headerExt.end())
{
return EntryType::makeHeader();
}
}
else
{
if (getLanguageFromFileName(name,SrcLangExt::Unknown) == SrcLangExt::Cpp) return EntryType::makeHeader();
}
return EntryType::makeEmpty();
}
QCString resolveTypeDef(const Definition *context,const QCString &qualifiedName,
const Definition **typedefContext)
{
AUTO_TRACE("context='{}' qualifiedName='{}'",context?context->name():"",qualifiedName);
QCString result;
if (qualifiedName.isEmpty())
{
AUTO_TRACE_EXIT("empty name");
return result;
}
const Definition *mContext=context;
if (typedefContext) *typedefContext=context;
// see if the qualified name has a scope part
if (qualifiedName.find('<')!=-1)
{
AUTO_TRACE_EXIT("template");
return result;
}
int scopeIndex = qualifiedName.findRev("::");
QCString resName=qualifiedName;
if (scopeIndex!=-1) // strip scope part for the name
{
resName=qualifiedName.right(qualifiedName.length()-scopeIndex-2);
if (resName.isEmpty())
{
AUTO_TRACE_EXIT("invalid format");
return result;
}
}
const MemberDef *md=nullptr;
while (mContext && md==nullptr)
{
// step 1: get the right scope
const Definition *resScope=mContext;
if (scopeIndex!=-1)
{
// split-off scope part
QCString resScopeName = qualifiedName.left(scopeIndex);
//printf("resScopeName='%s'\n",qPrint(resScopeName));
// look-up scope in context
int is=0,ps=0,l=0;
while ((is=getScopeFragment(resScopeName,ps,&l))!=-1)
{
QCString qualScopePart = resScopeName.mid(is,l);
QCString tmp = resolveTypeDef(mContext,qualScopePart);
if (!tmp.isEmpty()) qualScopePart=tmp;
resScope = resScope->findInnerCompound(qualScopePart);
//printf("qualScopePart='%s' resScope=%p\n",qPrint(qualScopePart),resScope);
if (resScope==nullptr) break;
ps=is+l;
}
}
AUTO_TRACE_ADD("resScope='{}' resName='{}'",resScope?resScope->name():"",resName);
// step 2: get the member
if (resScope) // no scope or scope found in the current context
{
//printf("scope found: %s, look for typedef %s\n",
// qPrint(resScope->qualifiedName()),qPrint(resName));
MemberNameLinkedMap *mnd=nullptr;
bool searchRelated=false;
bool mustBeRelated=false;
if (resScope->definitionType()==Definition::TypeClass)
{
mnd=Doxygen::memberNameLinkedMap;
}
else
{
mnd=Doxygen::functionNameLinkedMap;
searchRelated=true;
}
MemberName *mn=mnd->find(resName);
if (mn==0 && searchRelated)
{
mn=Doxygen::memberNameLinkedMap->find(resName);
mustBeRelated=true;
}
if (mn)
{
int minDist=-1;
for (const auto &tmd_p : *mn)
{
const MemberDef *tmd = tmd_p.get();
AUTO_TRACE_ADD("found candidate member '{}' isTypeDef={}' isRelated={} mustBeRelated={}",
tmd->name(),tmd->isTypedef(),tmd->isRelated(),mustBeRelated);
//printf("Found member %s resScope=%s outerScope=%s mContext=%p\n",
// qPrint(tmd->name()),qPrint( resScope->name()),
// qPrint(tmd->getOuterScope()->name()), mContext);
if (tmd->isTypedef())
{
if (resScope==Doxygen::globalScope && tmd->isRelated() && mustBeRelated)
{
md = tmd;
}
else
{
SymbolResolver resolver;
int dist=resolver.isAccessibleFrom(resScope,tmd);
if (dist!=-1 && (md==nullptr || dist<minDist))
{
md = tmd;
minDist = dist;
}
}
}
}
}
}
mContext=mContext->getOuterScope();
}
AUTO_TRACE_ADD("md='{}'",md?md->name():"");
// step 3: get the member's type
if (md)
{
//printf(">>resolveTypeDef: Found typedef name '%s' in scope '%s' value='%s' args='%s'\n",
// qPrint(qualifiedName),qPrint(context->name()),qPrint(md->typeString()),qPrint(md->argsString())
// );
result=md->typeString();
QCString args = md->argsString();
if (args.find(")(")!=-1) // typedef of a function/member pointer
{
result+=args;
}
else if (args.find('[')!=-1) // typedef of an array
{
result+=args;
}
if (typedefContext) *typedefContext=md->getOuterScope();
}
else
{
//printf(">>resolveTypeDef: Typedef '%s' not found in scope '%s'!\n",
// qPrint(qualifiedName),context ? qPrint(context->name()) : "<global>");
}
AUTO_TRACE_EXIT("result='{}'",result);
return result;
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
static const char constScope[] = { 'c', 'o', 'n', 's', 't', ':' };
static const char volatileScope[] = { 'v', 'o', 'l', 'a', 't', 'i', 'l', 'e', ':' };
static const char virtualScope[] = { 'v', 'i', 'r', 't', 'u', 'a', 'l', ':' };
static const char operatorScope[] = { 'o', 'p', 'e', 'r', 'a', 't', 'o', 'r', '?', '?', '?' };
struct CharAroundSpace
{
CharAroundSpace()
{
charMap[static_cast<int>('(')].before=FALSE;
charMap[static_cast<int>('=')].before=FALSE;
charMap[static_cast<int>('&')].before=FALSE;
charMap[static_cast<int>('*')].before=FALSE;
charMap[static_cast<int>('[')].before=FALSE;
charMap[static_cast<int>('|')].before=FALSE;
charMap[static_cast<int>('+')].before=FALSE;
charMap[static_cast<int>(';')].before=FALSE;
charMap[static_cast<int>(':')].before=FALSE;
charMap[static_cast<int>('/')].before=FALSE;
charMap[static_cast<int>('=')].after=FALSE;
charMap[static_cast<int>(' ')].after=FALSE;
charMap[static_cast<int>('[')].after=FALSE;
charMap[static_cast<int>(']')].after=FALSE;
charMap[static_cast<int>('\t')].after=FALSE;
charMap[static_cast<int>('\n')].after=FALSE;
charMap[static_cast<int>(')')].after=FALSE;
charMap[static_cast<int>(',')].after=FALSE;
charMap[static_cast<int>('<')].after=FALSE;
charMap[static_cast<int>('|')].after=FALSE;
charMap[static_cast<int>('+')].after=FALSE;
charMap[static_cast<int>('(')].after=FALSE;
charMap[static_cast<int>('/')].after=FALSE;
}
struct CharElem
{
CharElem() : before(TRUE), after(TRUE) {}
bool before;
bool after;
};
CharElem charMap[256];
};
static CharAroundSpace g_charAroundSpace;
// Note: this function is not reentrant due to the use of static buffer!
QCString removeRedundantWhiteSpace(const QCString &s)
{
bool cliSupport = Config_getBool(CPP_CLI_SUPPORT);
bool vhdl = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
if (s.isEmpty() || vhdl) return s;
// We use a static character array to
// improve the performance of this function
// and thread_local is needed to make it multi-thread safe
static THREAD_LOCAL char *growBuf = nullptr;
static THREAD_LOCAL size_t growBufLen = 0;
if (s.length()*3>growBufLen) // For input character we produce at most 3 output characters,
{
growBufLen = s.length()*3;
growBuf = static_cast<char *>(realloc(growBuf,growBufLen+1)); // add 1 for 0-terminator
}
if (growBuf==nullptr) return s; // should not happen, only we run out of memory
const char *src=s.data();
char *dst=growBuf;
size_t i=0;
size_t l=s.length();
size_t csp=0;
size_t vosp=0;
size_t vsp=0;
size_t osp=0;
char pc=0;
// skip leading whitespace
while (i<l && isspace(static_cast<uint8_t>(src[i])))
{
i++;
}
for (;i<l;i++)
{
char c=src[i];
char nc=i+1<l ? src[i+1] : ' ';
auto searchForKeyword = [&](const char *kw,size_t &matchLen,size_t totalLen)
{
if (matchLen<=totalLen && c==kw[matchLen] && // character matches substring kw
(matchLen>0 || // inside search string
i==0 || // if it is the first character
!isId(pc) // the previous may not be a digit
)
)
matchLen++;
else // reset counter
matchLen=0;
};
searchForKeyword(constScope, csp, 5); // keyword: const
searchForKeyword(volatileScope, vosp, 8); // keyword: volatile
searchForKeyword(virtualScope, vsp, 7); // keyword: virtual
// search for "operator"
if (osp<11 && (osp>=8 || c==operatorScope[osp]) && // character matches substring "operator" followed by 3 arbitrary characters
(osp>0 || // inside search string
i==0 || // if it is the first character
!isId(pc) // the previous may not be a digit
)
)
osp++;
else // reset counter
osp=0;
switch(c)
{
case '"': // quoted string
{
*dst++=c;
i++;
for (;i<l;i++) // find end of string
{
c = src[i];
*dst++=c;
if (c=='\\' && i+1<l)
{
i++;
c = src[i];
*dst++=c;
}
else if (c=='"')
{
break;
}
}
}
break;
case '<': // current char is a <
*dst++=c;
if (i+1<l &&
(isId(nc)) && // next char is an id char
(osp<8) // string in front is not "operator"
)
{
*dst++=' '; // add extra space
}
break;
case '>': // current char is a >
if (i>0 && !isspace(static_cast<uint8_t>(pc)) &&
(isId(pc) || pc=='*' || pc=='&' || pc=='.' || pc=='>') && // prev char is an id char or space or *&.
(osp<8 || (osp==8 && pc!='-')) // string in front is not "operator>" or "operator->"
)
{
*dst++=' '; // add extra space in front
}
*dst++=c;
if (i+1<l && (nc=='-' || nc=='&')) // '>-' -> '> -'
{
*dst++=' '; // add extra space after
}
break;
case ',': // current char is a ,
*dst++=c;
if (i>0 && !isspace(static_cast<uint8_t>(pc)) &&
((i+1<l && (isId(nc) || nc=='[')) || // the [ is for attributes (see bug702170)
(i+2<l && nc=='$' && isId(src[i+2])) || // for PHP: ',$name' -> ', $name'
(i+3<l && nc=='&' && src[i+2]=='$' && isId(src[i+3])) // for PHP: ',&$name' -> ', &$name'
)
)
{
*dst++=' '; // add extra space after
}
break;
case '^': // CLI 'Type^name' -> 'Type^ name'
case '%': // CLI 'Type%name' -> 'Type% name'
*dst++=c;
if (cliSupport && i+1<l && (isId(nc) || nc=='-'))
{
*dst++=' '; // add extra space after
}
break;
case ')': // current char is a ) -> ')name' -> ') name'
*dst++=c;
if (i+1<l && (isId(nc) || nc=='-'))
{
*dst++=' '; // add extra space after
}
break;
case '*':
if (i>0 && pc!=' ' && pc!='\t' && pc!=':' &&
pc!='*' && pc!='&' && pc!='(' && pc!='/' &&
pc!='.' && osp<9
)
// avoid splitting &&, **, .*, operator*, operator->*
{
*dst++=' ';
}
*dst++=c;
break;
case '&':
if (i>0 && isId(pc) && osp<9)
{
if (nc != '=')
// avoid splitting operator&=
{
*dst++=' ';
}
}
*dst++=c;
break;
case '$': // '$name' -> ' $name'
// 'name$name' -> 'name$name'
if (isId(pc))
{
*dst++=c;
break;
}
// else fallthrough
case '@': // '@name' -> ' @name'
case '\'': // ''name' -> '' name'
if (i>0 && i+1<l && pc!='=' && pc!=':' && !isspace(static_cast<uint8_t>(pc)) &&
isId(nc) && osp<8) // ")id" -> ") id"
{
*dst++=' ';
}
*dst++=c;
break;
case ':': // current char is a :
if (csp==6) // replace const::A by const ::A
{
*dst++=' ';
csp=0;
}
else if (vosp==9) // replace volatile::A by volatile ::A
{
*dst++=' ';
vosp=0;
}
else if (vsp==8) // replace virtual::A by virtual ::A
{
*dst++=' ';
vsp=0;
}
*dst++=c;
break;
case ' ': // fallthrough
case '\n': // fallthrough
case '\t':
{
if (g_charAroundSpace.charMap[static_cast<uint8_t>(pc)].before &&
g_charAroundSpace.charMap[static_cast<uint8_t>(nc)].after &&
!(pc==',' && nc=='.') &&
(osp<8 || (osp>=8 && isId(pc) && isId(nc)))
// e.g. 'operator >>' -> 'operator>>',
// 'operator "" _x' -> 'operator""_x',
// but not 'operator int' -> 'operatorint'
)
{ // keep space
*dst++=' ';
}
else if ((pc=='*' || pc=='&' || pc=='.') && nc=='>')
{
*dst++=' ';
}
}
break;
default:
*dst++=c;
auto correctKeywordAllowedInsideScope = [&](char cc,size_t &matchLen,size_t totalLen) {
if (c==cc && matchLen==totalLen)
{
if ((i+2<l && src[i+1] == ':' && src[i+2] == ':') || // keyword::
((i>matchLen && src[i-matchLen] == ':' && src[i-matchLen-1] == ':')) // ::keyword
) matchLen = 0;
};
};
correctKeywordAllowedInsideScope('t',csp, 5); // keyword: const
correctKeywordAllowedInsideScope('e',vosp,8); // keyword: volatile
correctKeywordAllowedInsideScope('l',vsp, 7); // keyword: virtual
auto correctKeywordNotPartOfScope = [&](char cc,size_t &matchLen,size_t totalLen)
{
if (c==cc && matchLen==totalLen && i+1<l && // found matching keyword
!(isId(nc) || nc==')' || nc==',' || qisspace(nc))
) // prevent keyword ::A from being converted to keyword::A
{
*dst++=' ';
matchLen=0;
}
};
correctKeywordNotPartOfScope('t',csp, 5); // keyword: const
correctKeywordNotPartOfScope('e',vosp,8); // keyword: volatile
correctKeywordNotPartOfScope('l',vsp, 7); // keyword: virtual
break;
}
pc=c;
}
*dst++='\0';
//printf("removeRedundantWhitespace(%s)->%s\n",qPrint(s),growBuf);
return growBuf;
}
/**
* Returns the position in the string where a function parameter list
* begins, or -1 if one is not found.
*/
int findParameterList(const QCString &name)
{
int pos=-1;
int templateDepth=0;
do
{
if (templateDepth > 0)
{
int nextOpenPos=name.findRev('>', pos);
int nextClosePos=name.findRev('<', pos);
if (nextOpenPos!=-1 && nextOpenPos>nextClosePos)
{
++templateDepth;
pos=nextOpenPos-1;
}
else if (nextClosePos!=-1)
{
--templateDepth;
pos=nextClosePos-1;
}
else // more >'s than <'s, see bug701295
{
return -1;
}
}
else
{
int lastAnglePos=name.findRev('>', pos);
int bracePos=name.findRev('(', pos);
if (lastAnglePos!=-1 && lastAnglePos>bracePos)
{
++templateDepth;
pos=lastAnglePos-1;
}
else
{
int bp = bracePos>0 ? name.findRev('(',bracePos-1) : -1;
// bp test is to allow foo(int(&)[10]), but we need to make an exception for operator()
return bp==-1 || (bp>=8 && name.mid(bp-8,10)=="operator()") ? bracePos : bp;
}
}
} while (pos!=-1);
return -1;
}
bool rightScopeMatch(const QCString &scope, const QCString &name)
{
size_t sl=scope.length();
size_t nl=name.length();
return (name==scope || // equal
(scope.right(nl)==name && // substring
sl>1+nl && scope.at(sl-nl-1)==':' && scope.at(sl-nl-2)==':' // scope
)
);
}
bool leftScopeMatch(const QCString &scope, const QCString &name)
{
size_t sl=scope.length();
size_t nl=name.length();
return (name==scope || // equal
(name.left(sl)==scope && // substring
nl>sl+1 && name.at(sl)==':' && name.at(sl+1)==':' // scope
)
);
}
void linkifyText(const TextGeneratorIntf &out, const Definition *scope,
const FileDef *fileScope,const Definition *self,
const QCString &text, bool autoBreak,bool external,
bool keepSpaces,int indentLevel)
{
if (text.isEmpty()) return;
//printf("linkify='%s'\n",qPrint(text));
std::string_view txtStr=text.view();
size_t strLen = txtStr.length();
if (strLen==0) return;
static const reg::Ex regExp(R"((::)?\a[\w~!\\.:$"]*)");
reg::Iterator it(txtStr,regExp);
reg::Iterator end;
//printf("linkifyText scope=%s fileScope=%s strtxt=%s strlen=%zu external=%d\n",
// scope ? qPrint(scope->name()):"<none>",
// fileScope ? qPrint(fileScope->name()) : "<none>",
// qPrint(txtStr),strLen,external);
size_t index=0;
size_t skipIndex=0;
size_t floatingIndex=0;
for (; it!=end ; ++it) // for each word from the text string
{
const auto &match = *it;
size_t newIndex = match.position();
size_t matchLen = match.length();
floatingIndex+=newIndex-skipIndex+matchLen;
if (newIndex>0 && txtStr.at(newIndex-1)=='0') // ignore hex numbers (match x00 in 0x00)
{
std::string_view part = txtStr.substr(skipIndex,newIndex+matchLen-skipIndex);
out.writeString(part,keepSpaces);
skipIndex=index=newIndex+matchLen;
continue;
}
// add non-word part to the result
bool insideString=FALSE;
for (size_t i=index;i<newIndex;i++)
{
if (txtStr.at(i)=='"') insideString=!insideString;
if (txtStr.at(i)=='\\') i++; // skip next character it is escaped
}
//printf("floatingIndex=%d strlen=%d autoBreak=%d\n",floatingIndex,strLen,autoBreak);
if (strLen>35 && floatingIndex>30 && autoBreak) // try to insert a split point
{
std::string_view splitText = txtStr.substr(skipIndex,newIndex-skipIndex);
size_t splitLength = splitText.length();
size_t offset=1;
size_t i = splitText.find(',');
if (i==std::string::npos) { i=splitText.find('<'); if (i!=std::string::npos) offset=0; }
if (i==std::string::npos) i=splitText.find('>');
if (i==std::string::npos) i=splitText.find(' ');
//printf("splitText=[%s] len=%d i=%d offset=%d\n",qPrint(splitText),splitLength,i,offset);
if (i!=std::string::npos) // add a link-break at i in case of Html output
{
std::string_view part1 = splitText.substr(0,i+offset);
out.writeString(part1,keepSpaces);
out.writeBreak(indentLevel==0 ? 0 : indentLevel+1);
std::string_view part2 = splitText.substr(i+offset);
out.writeString(part2,keepSpaces);
floatingIndex=splitLength-i-offset+matchLen;
}
else
{
out.writeString(splitText,keepSpaces);
}
}
else
{
//ol.docify(txtStr.mid(skipIndex,newIndex-skipIndex));
std::string_view part = txtStr.substr(skipIndex,newIndex-skipIndex);
out.writeString(part,keepSpaces);
}
// get word from string
std::string_view word=txtStr.substr(newIndex,matchLen);
QCString matchWord = substitute(substitute(QCString(word),"\\","::"),".","::");
//printf("linkifyText word=%s matchWord=%s scope=%s\n",
// qPrint(word),qPrint(matchWord),scope ? qPrint(scope->name()) : "<none>");
bool found=FALSE;
if (!insideString)
{
const ClassDef *cd=nullptr;
const ConceptDef *cnd=nullptr;
//printf("** Match word '%s'\n",qPrint(matchWord));
SymbolResolver resolver(fileScope);
cd=resolver.resolveClass(scope,matchWord);
const MemberDef *typeDef = resolver.getTypedef();
if (typeDef) // First look at typedef then class, see bug 584184.
{
if (external ? typeDef->isLinkable() : typeDef->isLinkableInProject())
{
if (typeDef->getOuterScope()!=self)
{
//printf("Found typedef %s word='%s'\n",qPrint(typeDef->name()),qPrint(word));
out.writeLink(typeDef->getReference(),
typeDef->getOutputFileBase(),
typeDef->anchor(),
word);
found=TRUE;
}
}
}
auto writeCompoundName = [&](const auto *cd_) {
if (external ? cd_->isLinkable() : cd_->isLinkableInProject())
{
if (self==nullptr || cd_->qualifiedName()!=self->qualifiedName())
{
//printf("Found compound %s word='%s'\n",qPrint(cd->name()),qPrint(word));
out.writeLink(cd_->getReference(),cd_->getOutputFileBase(),cd_->anchor(),word);
found=TRUE;
}
}
};
if (!found && (cd || (cd=getClass(matchWord))))
{
writeCompoundName(cd);
}
else if ((cd=getClass(matchWord+"-p"))) // search for Obj-C protocols as well
{
writeCompoundName(cd);
}
else if ((cnd=getConcept(matchWord))) // search for concepts
{
writeCompoundName(cnd);
}
else
{
//printf(" -> nothing\n");
}
int m = matchWord.findRev("::");
QCString scopeName;
if (scope &&
(scope->definitionType()==Definition::TypeClass ||
scope->definitionType()==Definition::TypeNamespace
)
)
{
scopeName=scope->name();
}
else if (m!=-1)
{
scopeName = matchWord.left(m);
matchWord = matchWord.mid(m+2);
}
//printf("ScopeName=%s\n",qPrint(scopeName));
//if (!found) printf("Trying to link '%s' in '%s'\n",qPrint(word),qPrint(scopeName));
if (!found)
{
GetDefInput input(scopeName,matchWord,QCString());
GetDefResult result = getDefs(input);
if (result.found &&
(external ? result.md->isLinkable() : result.md->isLinkableInProject())
)
{
//printf("Found ref scope=%s\n",d ? qPrint(d->name()) : "<global>");
//ol.writeObjectLink(d->getReference(),d->getOutputFileBase(),
// md->anchor(),word);
if (result.md!=self && (self==nullptr || result.md->name()!=self->name()))
// name check is needed for overloaded members, where getDefs just returns one
{
/* in case of Fortran scope and the variable is a non Fortran variable: don't link,
* see also getLink in fortrancode.l
*/
if (!(scope &&
(scope->getLanguage() == SrcLangExt::Fortran) &&
result.md->isVariable() &&
(result.md->getLanguage() != SrcLangExt::Fortran)
)
)
{
//printf("found symbol %s word='%s'\n",qPrint(result.md->name()),qPrint(word));
out.writeLink(result.md->getReference(),result.md->getOutputFileBase(),
result.md->anchor(),word);
found=TRUE;
}
}
}
}
}
if (!found) // add word to the result
{
out.writeString(word,keepSpaces);
}
// set next start point in the string
//printf("index=%d/%d\n",index,txtStr.length());
skipIndex=index=newIndex+matchLen;
}
// add last part of the string to the result.
//ol.docify(txtStr.right(txtStr.length()-skipIndex));
std::string_view lastPart = txtStr.substr(skipIndex);
out.writeString(lastPart,keepSpaces);
}
void writeMarkerList(OutputList &ol,const std::string &markerText,size_t numMarkers,
std::function<void(size_t)> replaceFunc)
{
static const reg::Ex marker(R"(@(\d+))");
reg::Iterator it(markerText,marker);
reg::Iterator end;
size_t index=0;
// now replace all markers in inheritLine with links to the classes
for ( ; it!=end ; ++it)
{
const auto &match = *it;
size_t newIndex = match.position();
size_t matchLen = match.length();
ol.parseText(markerText.substr(index,newIndex-index));
unsigned long entryIndex = std::stoul(match[1].str());
if (entryIndex<static_cast<unsigned long>(numMarkers))
{
replaceFunc(entryIndex);
}
index=newIndex+matchLen;
}
ol.parseText(markerText.substr(index));
}
void writeExamples(OutputList &ol,const ExampleList &list)
{
auto replaceFunc = [&list,&ol](size_t entryIndex)
{
const auto &e = list[entryIndex];
ol.pushGeneratorState();
ol.disable(OutputType::Latex);
ol.disable(OutputType::RTF);
ol.disable(OutputType::Docbook);
// link for Html / man
//printf("writeObjectLink(file=%s)\n",qPrint(e->file));
ol.writeObjectLink(QCString(),e.file,e.anchor,e.name);
ol.popGeneratorState();
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.disable(OutputType::Html);
// link for Latex / pdf with anchor because the sources
// are not hyperlinked (not possible with a verbatim environment).
ol.writeObjectLink(QCString(),e.file,QCString(),e.name);
ol.popGeneratorState();
};
writeMarkerList(ol, theTranslator->trWriteList(static_cast<int>(list.size())).str(), list.size(), replaceFunc);
ol.writeString(".");
}
QCString inlineArgListToDoc(const ArgumentList &al)
{
QCString paramDocs;
if (al.hasDocumentation())
{
for (const Argument &a : al)
{
if (a.hasDocumentation())
{
QCString docsWithoutDir = a.docs;
QCString direction = extractDirection(docsWithoutDir);
paramDocs+=" \\ilinebr @param"+direction+" "+a.name+" "+docsWithoutDir;
}
}
}
return paramDocs;
}
QCString argListToString(const ArgumentList &al,bool useCanonicalType,bool showDefVals)
{
QCString result;
if (!al.hasParameters()) return result;
result+="(";
for (auto it = al.begin() ; it!=al.end() ;)
{
Argument a = *it;
QCString type1 = useCanonicalType && !a.canType.isEmpty() ? a.canType : a.type;
QCString type2;
int i=type1.find(")("); // hack to deal with function pointers
if (i!=-1)
{
type2=type1.mid(i);
type1=type1.left(i);
}
if (!a.attrib.isEmpty())
{
result+=a.attrib+" ";
}
if (!a.name.isEmpty() || !a.array.isEmpty())
{
result+= type1+" "+a.name+type2+a.array;
}
else
{
result+= type1+type2;
}
if (!a.defval.isEmpty() && showDefVals)
{
result+="="+a.defval;
}
++it;
if (it!=al.end()) result+=", ";
}
result+=")";
if (al.constSpecifier()) result+=" const";
if (al.volatileSpecifier()) result+=" volatile";
if (al.refQualifier()==RefQualifierType::LValue) result+=" &";
else if (al.refQualifier()==RefQualifierType::RValue) result+=" &&";
if (!al.trailingReturnType().isEmpty()) result+=al.trailingReturnType();
if (al.pureSpecifier()) result+=" =0";
return removeRedundantWhiteSpace(result);
}
QCString tempArgListToString(const ArgumentList &al,SrcLangExt lang,bool includeDefault)
{
QCString result;
if (al.empty()) return result;
result="<";
bool first=true;
for (const auto &a : al)
{
if (a.defval.isEmpty() || includeDefault)
{
if (!first) result+=", ";
if (!a.name.isEmpty()) // add template argument name
{
if (lang==SrcLangExt::Java || lang==SrcLangExt::CSharp)
{
result+=a.type+" ";
}
result+=a.name;
}
else // extract name from type
{
int i = static_cast<int>(a.type.length())-1;
while (i>=0 && isId(a.type.at(i))) i--;
if (i>0)
{
result+=a.type.right(a.type.length()-i-1);
if (a.type.find("...")!=-1)
{
result+="...";
}
}
else // nothing found -> take whole name
{
result+=a.type;
}
}
if (!a.typeConstraint.isEmpty() && lang==SrcLangExt::Java)
{
result+=" extends "; // TODO: now Java specific, C# has where...
result+=a.typeConstraint;
}
first=false;
}
}
result+=">";
return removeRedundantWhiteSpace(result);
}
//----------------------------------------------------------------------------
/*! takes the \a buf of the given length \a len and converts CR LF (DOS)
* or CR (MAC) line ending to LF (Unix). Returns the length of the
* converted content (i.e. the same as \a len (Unix, MAC) or
* smaller (DOS).
*/
static void filterCRLF(std::string &contents)
{
size_t src = 0; // source index
size_t dest = 0; // destination index
size_t len = contents.length();
while (src<len)
{
char c = contents[src++]; // Remember the processed character.
if (c == '\r') // CR to be solved (MAC, DOS)
{
c = '\n'; // each CR to LF
if (src<len && contents[src] == '\n')
{
++src; // skip LF just after CR (DOS)
}
}
else if ( c == '\0' && src<len-1) // filter out internal \0 characters, as it will confuse the parser
{
c = ' '; // turn into a space
}
contents[dest++] = c; // copy the (modified) character to dest
}
contents.resize(dest);
}
static QCString getFilterFromList(const QCString &name,const StringVector &filterList,bool &found)
{
found=FALSE;
// compare the file name to the filter pattern list
for (const auto &filterStr : filterList)
{
QCString fs = filterStr.c_str();
int i_equals=fs.find('=');
if (i_equals!=-1)
{
QCString filterPattern = fs.left(i_equals);
QCString input = name;
if (!Portable::fileSystemIsCaseSensitive())
{
filterPattern = filterPattern.lower();
input = input.lower();
}
reg::Ex re(filterPattern.str(),reg::Ex::Mode::Wildcard);
if (re.isValid() && reg::match(input.str(),re))
{
// found a match!
QCString filterName = fs.mid(i_equals+1);
if (filterName.find(' ')!=-1)
{ // add quotes if the name has spaces
filterName="\""+filterName+"\"";
}
found=TRUE;
return filterName;
}
}
}
// no match
return "";
}
/*! looks for a filter for the file \a name. Returns the name of the filter
* if there is a match for the file name, otherwise an empty string.
* In case \a inSourceCode is TRUE then first the source filter list is
* considered.
*/
QCString getFileFilter(const QCString &name,bool isSourceCode)
{
// sanity check
if (name.isEmpty()) return "";
const StringVector& filterSrcList = Config_getList(FILTER_SOURCE_PATTERNS);
const StringVector& filterList = Config_getList(FILTER_PATTERNS);
QCString filterName;
bool found=FALSE;
if (isSourceCode && !filterSrcList.empty())
{ // first look for source filter pattern list
filterName = getFilterFromList(name,filterSrcList,found);
}
if (!found && filterName.isEmpty())
{ // then look for filter pattern list
filterName = getFilterFromList(name,filterList,found);
}
if (!found)
{ // then use the generic input filter
return Config_getString(INPUT_FILTER);
}
else
{
/* remove surrounding double quotes */
if (filterName.length()>=2 && filterName[0]=='"' && filterName[static_cast<int>(filterName.length())-1]=='"')
{
filterName = filterName.mid(1,filterName.length()-2);
}
return filterName;
}
}
bool transcodeCharacterStringToUTF8(std::string &input, const char *inputEncoding)
{
const char *outputEncoding = "UTF-8";
if (inputEncoding==nullptr || qstricmp(inputEncoding,outputEncoding)==0) return true;
size_t inputSize=input.length();
size_t outputSize=inputSize*4;
QCString output(outputSize, QCString::ExplicitSize);
void *cd = portable_iconv_open(outputEncoding,inputEncoding);
if (cd==reinterpret_cast<void *>(-1))
{
return false;
}
bool ok=true;
size_t iLeft=inputSize;
size_t oLeft=outputSize;
const char *inputPtr = input.data();
char *outputPtr = output.rawData();
if (!portable_iconv(cd, &inputPtr, &iLeft, &outputPtr, &oLeft))
{
outputSize-=static_cast<int>(oLeft);
output.resize(outputSize);
output.at(outputSize)='\0';
// replace input
input=output.str();
//printf("iconv: input size=%d output size=%d\n[%s]\n",size,newSize,qPrint(srcBuf));
}
else
{
ok=false;
}
portable_iconv_close(cd);
return ok;
}
/*! reads a file with name \a name and returns it as a string. If \a filter
* is TRUE the file will be filtered by any user specified input filter.
* If \a name is "-" the string will be read from standard input.
*/
QCString fileToString(const QCString &name,bool filter,bool isSourceCode)
{
if (name.isEmpty()) return QCString();
bool fileOpened=false;
if (name[0]=='-' && name[1]==0) // read from stdin
{
std::string contents;
std::string line;
while (getline(std::cin,line))
{
contents+=line+'\n';
}
return QCString(contents);
}
else // read from file
{
FileInfo fi(name.str());
if (!fi.exists() || !fi.isFile())
{
err("file '%s' not found\n",qPrint(name));
return "";
}
std::string buf;
fileOpened=readInputFile(name,buf,filter,isSourceCode);
if (fileOpened)
{
addTerminalCharIfMissing(buf,'\n');
return buf;
}
}
if (!fileOpened)
{
err("cannot open file '%s' for reading\n",qPrint(name));
}
return "";
}
void trimBaseClassScope(const BaseClassList &bcl,QCString &s,int level=0)
{
//printf("trimBaseClassScope level=%d '%s'\n",level,qPrint(s));
for (const auto &bcd : bcl)
{
ClassDef *cd=bcd.classDef;
//printf("Trying class %s\n",qPrint(cd->name()));
int spos=s.find(cd->name()+"::");
if (spos!=-1)
{
s = s.left(spos)+s.right(
s.length()-spos-cd->name().length()-2
);
}
//printf("base class '%s'\n",qPrint(cd->name()));
if (!cd->baseClasses().empty())
{
trimBaseClassScope(cd->baseClasses(),s,level+1);
}
}
}
static void stripIrrelevantString(QCString &target,const QCString &str)
{
if (target==str) { target.clear(); return; }
int i=0,p=0;
int l=static_cast<int>(str.length());
bool changed=FALSE;
while ((i=target.find(str,p))!=-1)
{
bool isMatch = (i==0 || !isId(target.at(i-1))) && // not a character before str
(i+l==static_cast<int>(target.length()) || !isId(target.at(i+l))); // not a character after str
if (isMatch)
{
int i1=target.find('*',i+l);
int i2=target.find('&',i+l);
if (i1==-1 && i2==-1)
{
// strip str from target at index i
target=target.left(i)+target.right(target.length()-i-l);
changed=TRUE;
i-=l;
}
else if ((i1!=-1 && i<i1) || (i2!=-1 && i<i2)) // str before * or &
{
// move str to front
target=str+" "+target.left(i)+target.right(target.length()-i-l);
changed=TRUE;
i++;
}
}
p = i+l;
}
if (changed) target=target.stripWhiteSpace();
}
/*! According to the C++ spec and Ivan Vecerina:
Parameter declarations that differ only in the presence or absence
of const and/or volatile are equivalent.
So the following example, show what is stripped by this routine
for const. The same is done for volatile.
For Java code we also strip the "final" keyword, see bug 765070.
\code
const T param -> T param // not relevant
const T& param -> const T& param // const needed
T* const param -> T* param // not relevant
const T* param -> const T* param // const needed
\endcode
*/
void stripIrrelevantConstVolatile(QCString &s)
{
//printf("stripIrrelevantConstVolatile(%s)=",qPrint(s));
stripIrrelevantString(s,"const");
stripIrrelevantString(s,"volatile");
stripIrrelevantString(s,"final");
//printf("%s\n",qPrint(s));
}
static QCString stripDeclKeywords(const QCString &s)
{
int i=s.find(" class ");
if (i!=-1) return s.left(i)+s.mid(i+6);
i=s.find(" typename ");
if (i!=-1) return s.left(i)+s.mid(i+9);
i=s.find(" union ");
if (i!=-1) return s.left(i)+s.mid(i+6);
i=s.find(" struct ");
if (i!=-1) return s.left(i)+s.mid(i+7);
return s;
}
// forward decl for circular dependencies
static QCString extractCanonicalType(const Definition *d,const FileDef *fs,QCString type,SrcLangExt lang);
static QCString getCanonicalTemplateSpec(const Definition *d,const FileDef *fs,const QCString& spec,SrcLangExt lang)
{
QCString templSpec = spec.stripWhiteSpace();
// this part had been commented out before... but it is needed to match for instance
// std::list<std::string> against list<string> so it is now back again!
if (!templSpec.isEmpty() && templSpec.at(0) == '<')
{
templSpec = "< " + extractCanonicalType(d,fs,templSpec.right(templSpec.length()-1).stripWhiteSpace(),lang);
}
QCString resolvedType = lang==SrcLangExt::Java ? templSpec : resolveTypeDef(d,templSpec);
if (!resolvedType.isEmpty()) // not known as a typedef either
{
templSpec = resolvedType;
}
//printf("getCanonicalTemplateSpec(%s)=%s\n",qPrint(spec),qPrint(templSpec));
return templSpec;
}
static QCString getCanonicalTypeForIdentifier(
const Definition *d,const FileDef *fs,const QCString &word,SrcLangExt lang,
QCString *tSpec,int count=0)
{
if (count>10) return word; // oops recursion
QCString symName,result,templSpec,tmpName;
if (tSpec && !tSpec->isEmpty())
templSpec = stripDeclKeywords(getCanonicalTemplateSpec(d,fs,*tSpec,lang));
AUTO_TRACE("d='{}' fs='{}' word='{}' templSpec='{}'",d?d->name():"",fs?fs->name():"",word,templSpec);
if (word.findRev("::")!=-1 && !(tmpName=stripScope(word)).isEmpty())
{
symName=tmpName; // name without scope
}
else
{
symName=word;
}
// lookup class / class template instance
SymbolResolver resolver(fs);
const ClassDef *cd = resolver.resolveClass(d,word+templSpec,true,true);
const MemberDef *mType = resolver.getTypedef();
QCString ts = resolver.getTemplateSpec();
QCString resolvedType = resolver.getResolvedType();
bool isTemplInst = cd && !templSpec.isEmpty();
if (!cd && !templSpec.isEmpty())
{
// class template specialization not known, look up class template
cd = resolver.resolveClass(d,word,true,true);
mType = resolver.getTypedef();
ts = resolver.getTemplateSpec();
resolvedType = resolver.getResolvedType();
}
if (cd && cd->isUsedOnly()) cd=nullptr; // ignore types introduced by usage relations
AUTO_TRACE_ADD("cd='{}' mType='{}' ts='{}' resolvedType='{}'",
cd?cd->name():"",mType?mType->name():"",ts,resolvedType);
//printf("cd=%p mtype=%p\n",cd,mType);
//printf(" getCanonicalTypeForIdentifier: symbol=%s word=%s cd=%s d=%s fs=%s cd->isTemplate=%d\n",
// qPrint(symName),
// qPrint(word),
// cd ? qPrint(cd->name()) : "<none>",
// d ? qPrint( d->name()) : "<none>",
// fs ? qPrint(fs->name()) : "<none>",
// cd ? cd->isTemplate():-1
// );
//printf(" >>>> word '%s' => '%s' templSpec=%s ts=%s tSpec=%s isTemplate=%d resolvedType=%s\n",
// qPrint((word+templSpec)),
// cd ? qPrint(cd->qualifiedName()) : "<none>",
// qPrint(templSpec), qPrint(ts),
// tSpec ? qPrint(tSpec) : "<null>",
// cd ? cd->isTemplate():FALSE,
// qPrint(resolvedType));
//printf(" mtype=%s\n",mType ? qPrint(mType->name()) : "<none>");
if (cd) // resolves to a known class type
{
if (cd==d && tSpec) *tSpec="";
if (mType && mType->isTypedef()) // but via a typedef
{
result = resolvedType+ts; // the +ts was added for bug 685125
}
else
{
if (isTemplInst)
{
// spec is already part of class type
templSpec="";
if (tSpec) *tSpec="";
}
else if (!ts.isEmpty() && templSpec.isEmpty())
{
// use formal template args for spec
templSpec = stripDeclKeywords(getCanonicalTemplateSpec(d,fs,ts,lang));
}
result = removeRedundantWhiteSpace(cd->qualifiedName() + templSpec);
if (cd->isTemplate() && tSpec) //
{
if (!templSpec.isEmpty()) // specific instance
{
result=cd->name()+templSpec;
}
else // use template type
{
result=cd->qualifiedNameWithTemplateParameters();
}
// template class, so remove the template part (it is part of the class name)
*tSpec="";
}
else if (ts.isEmpty() && !templSpec.isEmpty() && cd && !cd->isTemplate() && tSpec)
{
// obscure case, where a class is used as a template, but doxygen think it is
// not (could happen when loading the class from a tag file).
*tSpec="";
}
}
}
else if (mType && mType->isEnumerate()) // an enum
{
result = mType->qualifiedName();
}
else if (mType && mType->isTypedef()) // a typedef
{
//result = mType->qualifiedName(); // changed after 1.7.2
//result = mType->typeString();
//printf("word=%s typeString=%s\n",qPrint(word),mType->typeString());
if (word!=mType->typeString())
{
QCString type = mType->typeString();
if (type.startsWith("typename "))
{
type.stripPrefix("typename ");
type = stripTemplateSpecifiersFromScope(type,FALSE);
}
if (!type.isEmpty()) // see issue #11065
{
result = getCanonicalTypeForIdentifier(d,fs,type,mType->getLanguage(),tSpec,count+1);
}
else
{
result = word;
}
}
else
{
result = mType->typeString();
}
}
else // fallback
{
resolvedType = lang==SrcLangExt::Java ? word : resolveTypeDef(d,word);
AUTO_TRACE_ADD("fallback resolvedType='{}'",resolvedType);
if (resolvedType.isEmpty()) // not known as a typedef either
{
result = word;
}
else
{
result = resolvedType;
}
}
AUTO_TRACE_EXIT("result='{}'",result);
return result;
}
static QCString extractCanonicalType(const Definition *d,const FileDef *fs,QCString type,SrcLangExt lang)
{
AUTO_TRACE("d={} fs={} type='{}'",d?d->name():"",fs?fs->name():"",type);
type = type.stripWhiteSpace();
// strip const and volatile keywords that are not relevant for the type
stripIrrelevantConstVolatile(type);
// strip leading keywords
type.stripPrefix("class ");
type.stripPrefix("struct ");
type.stripPrefix("union ");
type.stripPrefix("enum ");
type.stripPrefix("typename ");
type = removeRedundantWhiteSpace(type);
//printf("extractCanonicalType(type=%s) start: def=%s file=%s\n",qPrint(type),
// d ? qPrint(d->name()) : "<null>", fs ? qPrint(fs->name()) : "<null>");
QCString canType;
QCString templSpec,word;
int i=0,p=0,pp=0;
while ((i=extractClassNameFromType(type,p,word,templSpec))!=-1)
// foreach identifier in the type
{
//printf(" i=%d p=%d\n",i,p);
if (i>pp) canType += type.mid(pp,i-pp);
QCString ct = getCanonicalTypeForIdentifier(d,fs,word,lang,&templSpec);
// in case the ct is empty it means that "word" represents scope "d"
// and this does not need to be added to the canonical
// type (it is redundant), so/ we skip it. This solves problem 589616.
if (ct.isEmpty() && type.mid(p,2)=="::")
{
p+=2;
}
else
{
canType += ct;
}
//printf(" word=%s templSpec=%s canType=%s ct=%s\n",
// qPrint(word), qPrint(templSpec), qPrint(canType), qPrint(ct));
if (!templSpec.isEmpty()) // if we didn't use up the templSpec already
// (i.e. type is not a template specialization)
// then resolve any identifiers inside.
{
std::string ts = templSpec.str();
static const reg::Ex re(R"(\a\w*)");
reg::Iterator it(ts,re);
reg::Iterator end;
size_t tp=0;
// for each identifier template specifier
//printf("adding resolved %s to %s\n",qPrint(templSpec),qPrint(canType));
for (; it!=end ; ++it)
{
const auto &match = *it;
size_t ti = match.position();
size_t tl = match.length();
std::string matchStr = match.str();
canType += ts.substr(tp,ti-tp);
canType += getCanonicalTypeForIdentifier(d,fs,matchStr.c_str(),lang,nullptr);
tp=ti+tl;
}
canType+=ts.substr(tp);
}
pp=p;
}
canType += type.right(type.length()-pp);
AUTO_TRACE_EXIT("canType='{}'",canType);
return removeRedundantWhiteSpace(canType);
}
static QCString extractCanonicalArgType(const Definition *d,const FileDef *fs,const Argument &arg,SrcLangExt lang)
{
QCString type = arg.type.stripWhiteSpace();
QCString name = arg.name;
//printf("----- extractCanonicalArgType(type=%s,name=%s)\n",qPrint(type),qPrint(name));
if ((type=="const" || type=="volatile") && !name.isEmpty())
{ // name is part of type => correct
type+=" ";
type+=name;
}
if (name=="const" || name=="volatile")
{ // name is part of type => correct
if (!type.isEmpty()) type+=" ";
type+=name;
}
if (!arg.array.isEmpty())
{
type+=arg.array;
}
return extractCanonicalType(d,fs,type,lang);
}
static std::mutex g_matchArgsMutex;
// a bit of debug support for matchArguments
#define MATCH
#define NOMATCH
//#define MATCH printf("Match at line %d\n",__LINE__);
//#define NOMATCH printf("Nomatch at line %d\n",__LINE__);
//#define MATCH AUTO_TRACE_EXIT("match at line {}",__LINE__);
//#define NOMATCH AUTO_TRACE_EXIT("no match at line {}",__LINE__);
static bool matchCanonicalTypes(
const Definition *srcScope,const FileDef *srcFileScope,const QCString &srcType,
const Definition *dstScope,const FileDef *dstFileScope,const QCString &dstType,
SrcLangExt lang)
{
AUTO_TRACE("srcType='{}' dstType='{}'",srcType,dstType);
if (srcType==dstType) return true;
// check if the types are function pointers
int i1=srcType.find(")(");
if (i1==-1) return false;
int i2=dstType.find(")(");
if (i1!=i2) return false;
// check if the result part of the function pointer types matches
int j1=srcType.find("(");
if (j1==-1 || j1>i1) return false;
int j2=dstType.find("(");
if (j2!=j1) return false;
if (srcType.left(j1)!=dstType.left(j2)) return false; // different return types
// if srcType and dstType are both function pointers with the same return type,
// then match against the parameter lists.
// This way srcType='void (*fptr)(int x)' will match against `void (*fptr)(int y)' because
// 'int x' matches 'int y'. A simple literal string match would treat these as different.
auto srcAl = stringToArgumentList(lang,srcType.mid(i1+1));
auto dstAl = stringToArgumentList(lang,dstType.mid(i2+1));
return matchArguments2(srcScope,srcFileScope,srcAl.get(),
dstScope,dstFileScope,dstAl.get(),
true,lang);
}
static bool matchArgument2(
const Definition *srcScope,const FileDef *srcFileScope,Argument &srcA,
const Definition *dstScope,const FileDef *dstFileScope,Argument &dstA,
SrcLangExt lang
)
{
AUTO_TRACE("src: scope={} type={} name={} canType={}, dst: scope={} type={} name={} canType={}",
srcScope?srcScope->name():"",srcA.type,srcA.name,srcA.canType,
dstScope?dstScope->name():"",dstA.type,dstA.name,dstA.canType);
//printf(">> match argument: %s::'%s|%s' (%s) <-> %s::'%s|%s' (%s)\n",
// srcScope ? qPrint(srcScope->name()) : "",
// qPrint(srcA.type), qPrint(srcA.name), qPrint(srcA.canType),
// dstScope ? qPrint(dstScope->name()) : "",
// qPrint(dstA.type), qPrint(dstA.name), qPrint(dstA.canType));
QCString sSrcName = " "+srcA.name;
QCString sDstName = " "+dstA.name;
QCString srcType = srcA.type;
QCString dstType = dstA.type;
stripIrrelevantConstVolatile(srcType);
stripIrrelevantConstVolatile(dstType);
//printf("'%s'<->'%s'\n",qPrint(sSrcName),qPrint(dstType.right(sSrcName.length())));
//printf("'%s'<->'%s'\n",qPrint(sDstName),qPrint(srcType.right(sDstName.length())));
if (sSrcName==dstType.right(sSrcName.length()))
{ // case "unsigned int" <-> "unsigned int i"
srcA.type+=sSrcName;
srcA.name="";
srcA.canType=""; // invalidate cached type value
}
else if (sDstName==srcType.right(sDstName.length()))
{ // case "unsigned int i" <-> "unsigned int"
dstA.type+=sDstName;
dstA.name="";
dstA.canType=""; // invalidate cached type value
}
{
std::lock_guard lock(g_matchArgsMutex);
if (srcA.canType.isEmpty() || dstA.canType.isEmpty())
{
// need to re-evaluate both see issue #8370
srcA.canType = extractCanonicalArgType(srcScope,srcFileScope,srcA,lang);
dstA.canType = extractCanonicalArgType(dstScope,dstFileScope,dstA,lang);
}
}
if (matchCanonicalTypes(srcScope,srcFileScope,srcA.canType,
dstScope,dstFileScope,dstA.canType,
lang))
{
MATCH
AUTO_TRACE_EXIT("true");
return TRUE;
}
else
{
//printf(" Canonical types do not match [%s]<->[%s]\n",
// qPrint(srcA->canType),qPrint(dstA->canType));
NOMATCH
AUTO_TRACE_EXIT("false");
return FALSE;
}
}
// new algorithm for argument matching
bool matchArguments2(const Definition *srcScope,const FileDef *srcFileScope,const ArgumentList *srcAl,
const Definition *dstScope,const FileDef *dstFileScope,const ArgumentList *dstAl,
bool checkCV,SrcLangExt lang)
{
ASSERT(srcScope!=nullptr && dstScope!=nullptr);
AUTO_TRACE("srcScope='{}' dstScope='{}' srcArgs='{}' dstArgs='{}' checkCV={} lang={}",
srcScope->name(),dstScope->name(),srcAl?argListToString(*srcAl):"",dstAl?argListToString(*dstAl):"",checkCV,lang);
if (srcAl==nullptr || dstAl==nullptr)
{
bool match = srcAl==dstAl;
if (match)
{
MATCH
return TRUE;
}
else
{
NOMATCH
return FALSE;
}
}
// handle special case with void argument
if ( srcAl->empty() && dstAl->size()==1 && dstAl->front().type=="void" )
{ // special case for finding match between func() and func(void)
Argument a;
a.type = "void";
const_cast<ArgumentList*>(srcAl)->push_back(a);
MATCH
return TRUE;
}
if ( dstAl->empty() && srcAl->size()==1 && srcAl->front().type=="void" )
{ // special case for finding match between func(void) and func()
Argument a;
a.type = "void";
const_cast<ArgumentList*>(dstAl)->push_back(a);
MATCH
return TRUE;
}
if (srcAl->size() != dstAl->size())
{
NOMATCH
return FALSE; // different number of arguments -> no match
}
if (checkCV)
{
if (srcAl->constSpecifier() != dstAl->constSpecifier())
{
NOMATCH
return FALSE; // one member is const, the other not -> no match
}
if (srcAl->volatileSpecifier() != dstAl->volatileSpecifier())
{
NOMATCH
return FALSE; // one member is volatile, the other not -> no match
}
}
if (srcAl->refQualifier() != dstAl->refQualifier())
{
NOMATCH
return FALSE; // one member is has a different ref-qualifier than the other
}
// so far the argument list could match, so we need to compare the types of
// all arguments.
auto srcIt = srcAl->begin();
auto dstIt = dstAl->begin();
for (;srcIt!=srcAl->end() && dstIt!=dstAl->end();++srcIt,++dstIt)
{
Argument &srcA = const_cast<Argument&>(*srcIt);
Argument &dstA = const_cast<Argument&>(*dstIt);
if (!matchArgument2(srcScope,srcFileScope,srcA,
dstScope,dstFileScope,dstA,
lang)
)
{
NOMATCH
return FALSE;
}
}
MATCH
return TRUE; // all arguments match
}
#undef MATCH
#undef NOMATCH
// merges the initializer of two argument lists
// pre: the types of the arguments in the list should match.
void mergeArguments(ArgumentList &srcAl,ArgumentList &dstAl,bool forceNameOverwrite)
{
AUTO_TRACE("srcAl='{}',dstAl='{}',forceNameOverwrite={}",
qPrint(argListToString(srcAl)),qPrint(argListToString(dstAl)),forceNameOverwrite);
if (srcAl.size()!=dstAl.size())
{
return; // invalid argument lists -> do not merge
}
auto srcIt=srcAl.begin();
auto dstIt=dstAl.begin();
while (srcIt!=srcAl.end() && dstIt!=dstAl.end())
{
Argument &srcA = *srcIt;
Argument &dstA = *dstIt;
AUTO_TRACE_ADD("before merge: src=[type='{}',name='{}',def='{}'] dst=[type='{}',name='{}',def='{}']",
srcA.type,srcA.name,srcA.defval,
dstA.type,dstA.name,dstA.defval);
if (srcA.defval.isEmpty() && !dstA.defval.isEmpty())
{
//printf("Defval changing '%s'->'%s'\n",qPrint(srcA.defval),qPrint(dstA.defval));
srcA.defval=dstA.defval;
}
else if (!srcA.defval.isEmpty() && dstA.defval.isEmpty())
{
//printf("Defval changing '%s'->'%s'\n",qPrint(dstA.defval),qPrint(srcA.defval));
dstA.defval=srcA.defval;
}
// fix wrongly detected const or volatile specifiers before merging.
// example: "const A *const" is detected as type="const A *" name="const"
if (srcA.name=="const" || srcA.name=="volatile")
{
srcA.type+=" "+srcA.name;
srcA.name.clear();
}
if (dstA.name=="const" || dstA.name=="volatile")
{
dstA.type+=" "+dstA.name;
dstA.name.clear();
}
if (srcA.type==dstA.type)
{
//printf("1. merging %s:%s <-> %s:%s\n",qPrint(srcA.type),qPrint(srcA.name),qPrint(dstA.type),qPrint(dstA.name));
if (srcA.name.isEmpty() && !dstA.name.isEmpty())
{
//printf("type: '%s':='%s'\n",qPrint(srcA.type),qPrint(dstA.type));
//printf("name: '%s':='%s'\n",qPrint(srcA.name),qPrint(dstA.name));
srcA.type = dstA.type;
srcA.name = dstA.name;
}
else if (!srcA.name.isEmpty() && dstA.name.isEmpty())
{
//printf("type: '%s':='%s'\n",qPrint(dstA.type),qPrint(srcA.type));
//printf("name: '%s':='%s'\n",qPrint(dstA.name),qPrint(srcA.name));
dstA.type = srcA.type;
dstA.name = srcA.name;
}
else if (!srcA.name.isEmpty() && !dstA.name.isEmpty())
{
//printf("srcA.name=%s dstA.name=%s\n",qPrint(srcA.name),qPrint(dstA.name));
if (forceNameOverwrite)
{
srcA.name = dstA.name;
}
else
{
if (srcA.docs.isEmpty() && !dstA.docs.isEmpty())
{
srcA.name = dstA.name;
}
else if (!srcA.docs.isEmpty() && dstA.docs.isEmpty())
{
dstA.name = srcA.name;
}
}
}
}
else
{
//printf("2. merging '%s':'%s' <-> '%s':'%s'\n",qPrint(srcA.type),qPrint(srcA.name),qPrint(dstA.type),qPrint(dstA.name));
srcA.type=srcA.type.stripWhiteSpace();
dstA.type=dstA.type.stripWhiteSpace();
if (srcA.type+" "+srcA.name==dstA.type) // "unsigned long:int" <-> "unsigned long int:bla"
{
srcA.type+=" "+srcA.name;
srcA.name=dstA.name;
}
else if (dstA.type+" "+dstA.name==srcA.type) // "unsigned long int bla" <-> "unsigned long int"
{
dstA.type+=" "+dstA.name;
dstA.name=srcA.name;
}
else if (srcA.name.isEmpty() && !dstA.name.isEmpty())
{
srcA.name = dstA.name;
}
else if (dstA.name.isEmpty() && !srcA.name.isEmpty())
{
dstA.name = srcA.name;
}
}
int i1=srcA.type.find("::"),
i2=dstA.type.find("::"),
j1=static_cast<int>(srcA.type.length())-i1-2,
j2=static_cast<int>(dstA.type.length())-i2-2;
if (i1!=-1 && i2==-1 && srcA.type.right(j1)==dstA.type)
{
//printf("type: '%s':='%s'\n",qPrint(dstA.type),qPrint(srcA.type));
//printf("name: '%s':='%s'\n",qPrint(dstA.name),qPrint(srcA.name));
dstA.type = srcA.type.left(i1+2)+dstA.type;
dstA.name = srcA.name;
}
else if (i1==-1 && i2!=-1 && dstA.type.right(j2)==srcA.type)
{
//printf("type: '%s':='%s'\n",qPrint(srcA.type),qPrint(dstA.type));
//printf("name: '%s':='%s'\n",qPrint(dstA.name),qPrint(srcA.name));
srcA.type = dstA.type.left(i2+2)+srcA.type;
srcA.name = dstA.name;
}
if (srcA.docs.isEmpty() && !dstA.docs.isEmpty())
{
srcA.docs = dstA.docs;
}
else if (dstA.docs.isEmpty() && !srcA.docs.isEmpty())
{
dstA.docs = srcA.docs;
}
//printf("Merge argument '%s|%s' '%s|%s'\n",
// qPrint(srcA.type), qPrint(srcA.name),
// qPrint(dstA.type), qPrint(dstA.name));
++srcIt;
++dstIt;
AUTO_TRACE_ADD("after merge: src=[type='{}',name='{}',def='{}'] dst=[type='{}',name='{}',def='{}']",
srcA.type,srcA.name,srcA.defval,
dstA.type,dstA.name,dstA.defval);
}
}
//---------------------------------------------------------------------------------------
static void findMembersWithSpecificName(const MemberName *mn,
const QCString &args,
bool checkStatics,
const FileDef *currentFile,
bool checkCV,
std::vector<const MemberDef *> &members)
{
//printf(" Function with global scope name '%s' args='%s'\n",
// mn->memberName(),args);
for (const auto &md_p : *mn)
{
const MemberDef *md = md_p.get();
const FileDef *fd=md->getFileDef();
const GroupDef *gd=md->getGroupDef();
//printf(" md->name()='%s' md->args='%s' fd=%p gd=%p current=%p ref=%s\n",
// qPrint(md->name()),args,fd,gd,currentFile,qPrint(md->getReference()));
if (
((gd && gd->isLinkable()) || (fd && fd->isLinkable()) || md->isReference()) &&
md->getNamespaceDef()==nullptr && md->isLinkable() &&
(!checkStatics || (!md->isStatic() && !md->isDefine()) ||
currentFile==nullptr || fd==currentFile) // statics must appear in the same file
)
{
bool match=TRUE;
if (!args.isEmpty() && !md->isDefine() && args!="()")
{
const ArgumentList &mdAl = md->argumentList();
auto argList_p = stringToArgumentList(md->getLanguage(),args);
match=matchArguments2(
md->getOuterScope(),fd,&mdAl,
Doxygen::globalScope,fd,argList_p.get(),
checkCV,md->getLanguage());
}
if (match)
{
//printf("Found match!\n");
members.push_back(md);
}
}
}
}
//---------------------------------------------------------------------------------------
GetDefResult getDefsNew(const GetDefInput &input)
{
GetDefResult result;
if (input.memberName.isEmpty()) return result;
//printf("@@ --- getDefsNew(%s,%s)-----------\n",qPrint(scName),qPrint(mbName));
const Definition *scope = Doxygen::globalScope;
SymbolResolver resolver;
if (input.currentFile) resolver.setFileScope(input.currentFile);
if (!input.scopeName.isEmpty())
{
scope = resolver.resolveSymbol(scope,input.scopeName);
}
if (scope==Doxygen::globalScope)
{
scope = input.currentFile;
}
//printf("@@ -> found scope scope=%s member=%s out=%s\n",qPrint(input.scopeName),qPrint(input.memberName),qPrint(scope?scope->name():""));
//
const Definition *symbol = resolver.resolveSymbol(scope,input.memberName,input.args,input.checkCV,input.insideCode);
//printf("@@ -> found symbol in=%s out=%s\n",qPrint(input.memberName),qPrint(symbol?symbol->qualifiedName():QCString()));
if (symbol && symbol->definitionType()==Definition::TypeMember)
{
result.md = toMemberDef(symbol);
result.cd = result.md->getClassDef();
if (result.cd==nullptr) result.nd = result.md->getNamespaceDef();
if (result.cd==nullptr && result.nd==nullptr) result.fd = result.md->getFileDef();
result.gd = result.md->getGroupDef();
result.found = true;
}
return result;
}
/*!
* Searches for a member definition given its name 'memberName' as a string.
* memberName may also include a (partial) scope to indicate the scope
* in which the member is located.
*
* The parameter 'scName' is a string representing the name of the scope in
* which the link was found.
*
* In case of a function args contains a string representation of the
* argument list. Passing 0 means the member has no arguments.
* Passing "()" means any argument list will do, but "()" is preferred.
*
* The function returns TRUE if the member is known and documented or
* FALSE if it is not.
* If TRUE is returned parameter 'md' contains a pointer to the member
* definition. Furthermore exactly one of the parameter 'cd', 'nd', or 'fd'
* will be non-zero:
* - if 'cd' is non zero, the member was found in a class pointed to by cd.
* - if 'nd' is non zero, the member was found in a namespace pointed to by nd.
* - if 'fd' is non zero, the member was found in the global namespace of
* file fd.
*/
GetDefResult getDefsOld(const GetDefInput &input)
{
GetDefResult result;
QCString scopeName;
QCString memberName;
QCString mName;
QCString mScope;
MemberName *mn = nullptr;
int is=0,im=0,pm=0;
if (input.memberName.isEmpty()) goto exit; /* empty name => nothing to link */
scopeName = input.scopeName;
scopeName = substitute(scopeName,"\\","::"); // for PHP
memberName = input.memberName;
memberName = substitute(memberName,"\\","::"); // for PHP
//printf("Search for name=%s args=%s in scope=%s forceEmpty=%d\n",
// qPrint(memberName),qPrint(args),qPrint(scopeName),forceEmptyScope);
// strip common part of the scope from the scopeName
while ((is=scopeName.findRev("::"))!=-1 &&
(im=memberName.find("::",pm))!=-1 &&
(scopeName.right(scopeName.length()-is-2)==memberName.mid(pm,im-pm))
)
{
scopeName=scopeName.left(is);
pm=im+2;
}
//printf("result after scope corrections scope=%s name=%s\n",
// qPrint(scopeName), qPrint(memberName));
mName=memberName;
if (!memberName.startsWith("operator ") && // treat operator conversion methods
// as a special case
(im=memberName.findRev("::"))!=-1 &&
im<static_cast<int>(memberName.length())-2 // not A::
)
{
mScope=memberName.left(im);
mName=memberName.right(memberName.length()-im-2);
}
// handle special the case where both scope name and member scope are equal
if (mScope==scopeName) scopeName.clear();
//printf("mScope='%s' mName='%s'\n",qPrint(mScope),qPrint(mName));
mn = Doxygen::memberNameLinkedMap->find(mName);
//printf("mName=%s mn=%p\n",qPrint(mName),mn);
if ((!input.forceEmptyScope || input.scopeName.isEmpty()) && // this was changed for bug638856, forceEmptyScope => empty scopeName
mn && !(input.scopeName.isEmpty() && mScope.isEmpty()))
{
//printf(" >member name '%s' found\n",qPrint(mName));
int scopeOffset = static_cast<int>(scopeName.length());
do
{
QCString className = scopeName.left(scopeOffset);
if (!className.isEmpty() && !mScope.isEmpty())
{
className+="::"+mScope;
}
else if (!mScope.isEmpty())
{
className=mScope;
}
SymbolResolver resolver;
const ClassDef *fcd=resolver.resolveClass(Doxygen::globalScope,className);
const MemberDef *tmd=resolver.getTypedef();
if (fcd==nullptr && className.find('<')!=-1) // try without template specifiers as well
{
QCString nameWithoutTemplates = stripTemplateSpecifiersFromScope(className,FALSE);
fcd=resolver.resolveClass(Doxygen::globalScope,nameWithoutTemplates);
tmd=resolver.getTypedef();
}
//printf("Trying class scope %s: fcd=%p tmd=%p\n",qPrint(className),fcd,tmd);
// todo: fill in correct fileScope!
if (fcd && // is it a documented class
fcd->isLinkable()
)
{
//printf(" Found fcd=%p\n",fcd);
int mdist=maxInheritanceDepth;
std::unique_ptr<ArgumentList> argList;
if (!input.args.isEmpty())
{
argList = stringToArgumentList(fcd->getLanguage(),input.args);
}
for (const auto &mmd_p : *mn)
{
MemberDef *mmd = mmd_p.get();
if (!mmd->isStrongEnumValue())
{
const ArgumentList &mmdAl = mmd->argumentList();
bool match = input.args.isEmpty() ||
matchArguments2(mmd->getOuterScope(),mmd->getFileDef(),&mmdAl,
fcd, fcd->getFileDef(),argList.get(),
input.checkCV,mmd->getLanguage());
//printf("match=%d\n",match);
if (match)
{
const ClassDef *mcd=mmd->getClassDef();
if (mcd)
{
int m=minClassDistance(fcd,mcd);
if (m<mdist && mcd->isLinkable())
{
mdist=m;
result.cd=mcd;
result.md=mmd;
}
}
}
}
}
if (mdist==maxInheritanceDepth && input.args=="()")
// no exact match found, but if args="()" an arbitrary member will do
{
//printf(" >Searching for arbitrary member\n");
for (const auto &mmd_p : *mn)
{
MemberDef *mmd = mmd_p.get();
//if (mmd->isLinkable())
//{
const ClassDef *mcd=mmd->getClassDef();
//printf(" >Class %s found\n",qPrint(mcd->name()));
if (mcd)
{
int m=minClassDistance(fcd,mcd);
if (m<mdist /* && mcd->isLinkable()*/ )
{
//printf("Class distance %d\n",m);
mdist = m;
result.cd = mcd;
result.md = mmd;
}
}
//}
}
}
//printf(" >Success=%d\n",mdist<maxInheritanceDepth);
if (mdist<maxInheritanceDepth)
{
if (!result.md->isLinkable() || result.md->isStrongEnumValue())
{
result.md = nullptr; // avoid returning things we cannot link to
result.cd = nullptr;
result.found = false; // match found, but was not linkable
goto exit;
}
else
{
result.gd = result.md->getGroupDef();
if (result.gd) result.cd=nullptr;
result.found=true; /* found match */
goto exit;
}
}
}
if (tmd && tmd->isEnumerate() && tmd->isStrong()) // scoped enum
{
//printf("Found scoped enum!\n");
for (const auto &emd : tmd->enumFieldList())
{
if (emd->localName()==mName)
{
if (emd->isLinkable())
{
result.cd = tmd->getClassDef();
result.md = emd;
result.found = true;
goto exit;
}
else
{
result.cd = nullptr;
result.md = nullptr;
result.found = false;
goto exit;
}
}
}
}
/* go to the parent scope */
if (scopeOffset==0)
{
scopeOffset=-1;
}
else if ((scopeOffset=scopeName.findRev("::",scopeOffset-1))==-1)
{
scopeOffset=0;
}
} while (scopeOffset>=0);
}
if (mn && input.scopeName.isEmpty() && mScope.isEmpty()) // Maybe a related function?
{
//printf("Global symbol\n");
const MemberDef *fuzzy_mmd = nullptr;
std::unique_ptr<ArgumentList> argList;
bool hasEmptyArgs = input.args=="()";
if (!input.args.isEmpty())
{
argList = stringToArgumentList(SrcLangExt::Cpp, input.args);
}
for (const auto &mmd_p : *mn)
{
const MemberDef *mmd = mmd_p.get();
if (!mmd->isLinkable() || (!mmd->isRelated() && !mmd->isForeign()) ||
!mmd->getClassDef())
{
continue;
}
if (input.args.isEmpty())
{
fuzzy_mmd = mmd;
break;
}
const ArgumentList &mmdAl = mmd->argumentList();
if (matchArguments2(mmd->getOuterScope(),mmd->getFileDef(),&mmdAl,
Doxygen::globalScope,mmd->getFileDef(),argList.get(),
input.checkCV,mmd->getLanguage())
)
{
fuzzy_mmd = mmd;
break;
}
if (!fuzzy_mmd && hasEmptyArgs)
{
fuzzy_mmd = mmd;
}
}
if (fuzzy_mmd && !fuzzy_mmd->isStrongEnumValue())
{
result.md = fuzzy_mmd;
result.cd = fuzzy_mmd->getClassDef();
result.found = true;
goto exit;
}
}
// maybe an namespace, file or group member ?
//printf("Testing for global symbol scopeName='%s' mScope='%s' :: mName='%s'\n",
// qPrint(scopeName), qPrint(mScope), qPrint(mName));
if ((mn=Doxygen::functionNameLinkedMap->find(mName))) // name is known
{
//printf(" >symbol name found\n");
NamespaceDef *fnd=nullptr;
int scopeOffset = static_cast<int>(scopeName.length());
do
{
QCString namespaceName = scopeName.left(scopeOffset);
if (!namespaceName.isEmpty() && !mScope.isEmpty())
{
namespaceName+="::"+mScope;
}
else if (!mScope.isEmpty())
{
namespaceName=mScope;
}
//printf("Trying namespace %s\n",qPrint(namespaceName));
if (!namespaceName.isEmpty() &&
(fnd=Doxygen::namespaceLinkedMap->find(namespaceName)) &&
fnd->isLinkable()
)
{
//printf("Symbol inside existing namespace '%s' count=%d\n",
// qPrint(namespaceName),mn->count());
bool found=FALSE;
for (const auto &mmd_p : *mn)
{
const MemberDef *mmd = mmd_p.get();
//printf("mmd->getNamespaceDef()=%p fnd=%p\n",
// mmd->getNamespaceDef(),fnd);
const MemberDef *emd = mmd->getEnumScope();
if (emd && emd->isStrong())
{
//printf("yes match %s<->%s!\n",qPrint(mScope),qPrint(emd->localName()));
if (emd->getNamespaceDef()==fnd &&
rightScopeMatch(mScope,emd->localName()))
{
//printf("found it!\n");
result.nd=fnd;
result.md=mmd;
found=TRUE;
break;
}
else
{
result.md=nullptr;
result.cd=nullptr;
result.found=false;
goto exit;
}
}
else if (mmd->getOuterScope()==fnd /* && mmd->isLinkable() */ )
{ // namespace is found
bool match=TRUE;
if (!input.args.isEmpty() && input.args!="()")
{
const ArgumentList &mmdAl = mmd->argumentList();
auto argList_p = stringToArgumentList(mmd->getLanguage(),input.args);
match=matchArguments2(
mmd->getOuterScope(),mmd->getFileDef(),&mmdAl,
fnd,mmd->getFileDef(),argList_p.get(),
input.checkCV,mmd->getLanguage());
}
if (match)
{
result.nd=fnd;
result.md=mmd;
found=TRUE;
break;
}
}
}
if (!found && input.args=="()")
// no exact match found, but if args="()" an arbitrary
// member will do
{
for (const auto &mmd_p : *mn)
{
const MemberDef *mmd = mmd_p.get();
if (mmd->getNamespaceDef()==fnd /*&& mmd->isLinkable() */ )
{
result.nd=fnd;
result.md=mmd;
found=TRUE;
break;
}
}
}
if (found)
{
if (!result.md->isLinkable())
{
result.md=nullptr; // avoid returning things we cannot link to
result.nd=nullptr;
result.found=false; // match found but not linkable
goto exit;
}
else
{
result.gd=result.md->resolveAlias()->getGroupDef();
if (result.gd && result.gd->isLinkable()) result.nd=nullptr; else result.gd=nullptr;
result.found = true;
goto exit;
}
}
}
else
{
//printf("not a namespace\n");
for (const auto &mmd_p : *mn)
{
const MemberDef *mmd = mmd_p.get();
const MemberDef *tmd = mmd->getEnumScope();
//printf("try member %s tmd=%s\n",qPrint(mmd->name()),tmd ? qPrint(tmd->name()) : "<none>");
int ni=namespaceName.findRev("::");
//printf("namespaceName=%s ni=%d\n",qPrint(namespaceName),ni);
bool notInNS = tmd && ni==-1 && tmd->getNamespaceDef()==nullptr && (mScope.isEmpty() || mScope==tmd->name());
bool sameNS = tmd && ni>=0 && tmd->getNamespaceDef() && namespaceName.left(ni)==tmd->getNamespaceDef()->name() && namespaceName.mid(ni+2)==tmd->name();
//printf("notInNS=%d sameNS=%d\n",notInNS,sameNS);
if (tmd && tmd->isStrong() && // C++11 enum class
(notInNS || sameNS) &&
namespaceName.length()>0 // enum is part of namespace so this should not be empty
)
{
result.md=mmd;
result.fd=mmd->getFileDef();
result.gd=mmd->getGroupDef();
if (result.gd && result.gd->isLinkable()) result.fd=nullptr; else result.gd=nullptr;
//printf("Found scoped enum %s fd=%p gd=%p\n",
// qPrint(mmd->name()),result.fd,result.gd);
result.found = true;
goto exit;
}
}
}
if (scopeOffset==0)
{
scopeOffset=-1;
}
else if ((scopeOffset=scopeName.findRev("::",scopeOffset-1))==-1)
{
scopeOffset=0;
}
} while (scopeOffset>=0);
//else // no scope => global function
{
std::vector<const MemberDef *> members;
// search for matches with strict static checking
findMembersWithSpecificName(mn,input.args,true,input.currentFile,input.checkCV,members);
if (members.empty()) // nothing found
{
// search again without strict static checking
findMembersWithSpecificName(mn,input.args,false,input.currentFile,input.checkCV,members);
}
//printf("found %d members\n",members.count());
if (members.size()!=1 && input.args=="()")
{
// no exact match found, but if args="()" an arbitrary
// member will do
//MemberNameIterator mni(*mn);
//for (mni.toLast();(md=mni.current());--mni)
for (auto it = mn->rbegin(); it!=mn->rend(); ++it)
{
const auto &mmd_p = *it;
const MemberDef *mmd = mmd_p.get();
//printf("Found member '%s'\n",qPrint(mmd->name()));
//printf("member is linkable mmd->name()='%s'\n",qPrint(mmd->name()));
result.fd = mmd->getFileDef();
result.gd = mmd->getGroupDef();
const MemberDef *tmd = mmd->getEnumScope();
if (
(result.gd && result.gd->isLinkable()) || (result.fd && result.fd->isLinkable()) ||
(tmd && tmd->isStrong())
)
{
members.push_back(mmd);
}
}
}
//printf("found %d candidate members\n",members.count());
if (!members.empty()) // at least one match
{
if (input.currentFile)
{
//printf("multiple results; pick one from file:%s\n",qPrint( currentFile->name()));
for (const auto &rmd : members)
{
if (rmd->getFileDef() && rmd->getFileDef()->name() == input.currentFile->name())
{
result.md = rmd;
break; // found match in the current file
}
}
if (!result.md) // member not in the current file
{
result.md = members.back();
}
}
else
{
result.md = members.back();
}
}
if (result.md && (result.md->getEnumScope()==nullptr || !result.md->getEnumScope()->isStrong()))
// found a matching global member, that is not a scoped enum value (or uniquely matches)
{
result.fd = result.md->getFileDef();
result.gd = result.md->getGroupDef();
//printf("fd=%p gd=%p gd->isLinkable()=%d\n",fd,gd,gd->isLinkable());
if (result.gd && result.gd->isLinkable()) result.fd=nullptr; else result.gd=nullptr;
result.found = true;
goto exit;
}
}
}
exit:
return result;
}
GetDefResult getDefs(const GetDefInput &input)
{
if (false) // set this to true to try the old and new routine side-by-side and compare the results
{
printf("@@ ------ getDefsOld start\n");
GetDefResult result = getDefsOld(input);
printf("@@ ------ getDefsOld end\n");
printf("@@ ------ getDefsNew start\n");
GetDefResult newResult = getDefsNew(input);
printf("@@ ------ getDefsNew end\n");
if (result.found!=newResult.found ||
result.md!=newResult.md ||
result.cd!=newResult.cd ||
result.fd!=newResult.fd ||
result.nd!=newResult.nd ||
result.gd!=newResult.gd
)
{
printf("@@ getDefsOld(scName=%s, mbName=%s, args=%s, forceEmptyScope=%d "
"currentFile=%s checkCV=%d)=%d md=%s (%p) cd=%s fd=%s nd=%s gd=%s\n",
qPrint(input.scopeName), qPrint(input.memberName), qPrint(input.args),
input.forceEmptyScope, qPrint(input.currentFile?input.currentFile->name():QCString()),
input.checkCV,
result.found,
qPrint(result.md ? result.md->name() : QCString()),
(void*)result.md,
qPrint(result.cd ? result.cd->name() : QCString()),
qPrint(result.fd ? result.fd->name() : QCString()),
qPrint(result.nd ? result.nd->name() : QCString()),
qPrint(result.gd ? result.gd->name() : QCString())
);
printf("@@ ------ getDefsOld start\n");
printf("@@ getDefsNew(scName=%s, mbName=%s, args=%s, forceEmptyScope=%d "
"currentFile=%s checkCV=%d)=%d md=%s (%p) cd=%s fd=%s nd=%s gd=%s\n",
qPrint(input.scopeName), qPrint(input.memberName), qPrint(input.args),
input.forceEmptyScope, qPrint(input.currentFile?input.currentFile->name():QCString()),
input.checkCV,
newResult.found,
qPrint(newResult.md ? newResult.md->name() : QCString()),
(void*)newResult.md,
qPrint(newResult.cd ? newResult.cd->name() : QCString()),
qPrint(newResult.fd ? newResult.fd->name() : QCString()),
qPrint(newResult.nd ? newResult.nd->name() : QCString()),
qPrint(newResult.gd ? newResult.gd->name() : QCString())
);
}
return result; // use return newResult to use the result of the new routine
}
else // do one of the two getDefs routines (comment out the other one)
{
return getDefsNew(input);
}
}
/*!
* Searches for a scope definition given its name as a string via parameter
* `scope`.
*
* The parameter `docScope` is a string representing the name of the scope in
* which the `scope` string was found.
*
* The function returns TRUE if the scope is known and documented or
* FALSE if it is not.
* If TRUE is returned exactly one of the parameter `cd`, `nd`
* will be non-zero:
* - if `cd` is non zero, the scope was a class pointed to by cd.
* - if `nd` is non zero, the scope was a namespace pointed to by nd.
*/
static bool getScopeDefs(const QCString &docScope,const QCString &scope,
ClassDef *&cd, ConceptDef *&cnd, NamespaceDef *&nd)
{
cd=nullptr;nd=nullptr;
QCString scopeName=scope;
//printf("getScopeDefs: docScope='%s' scope='%s'\n",qPrint(docScope),qPrint(scope));
if (scopeName.isEmpty()) return FALSE;
bool explicitGlobalScope=FALSE;
if (scopeName.at(0)==':' && scopeName.at(1)==':')
{
scopeName=scopeName.right(scopeName.length()-2);
explicitGlobalScope=TRUE;
}
if (scopeName.isEmpty())
{
return FALSE;
}
QCString docScopeName=docScope;
int scopeOffset=explicitGlobalScope ? 0 : static_cast<int>(docScopeName.length());
do // for each possible docScope (from largest to and including empty)
{
QCString fullName=scopeName;
if (scopeOffset>0) fullName.prepend(docScopeName.left(scopeOffset)+"::");
if (((cd=getClass(fullName)) || // normal class
(cd=getClass(fullName+"-p")) // ObjC protocol
) && cd->isLinkable())
{
return TRUE; // class link written => quit
}
else if ((nd=Doxygen::namespaceLinkedMap->find(fullName)) && nd->isLinkable())
{
return TRUE; // namespace link written => quit
}
else if ((cnd=Doxygen::conceptLinkedMap->find(fullName)) && cnd->isLinkable())
{
return TRUE; // concept link written => quit
}
if (scopeOffset==0)
{
scopeOffset=-1;
}
else if ((scopeOffset=docScopeName.findRev("::",scopeOffset-1))==-1)
{
scopeOffset=0;
}
} while (scopeOffset>=0);
return FALSE;
}
static bool isLowerCase(QCString &s)
{
if (s.isEmpty()) return true;
const char *p=s.data();
int c=0;
while ((c=static_cast<uint8_t>(*p++))) if (!islower(c)) return false;
return true;
}
/*! Returns an object to reference to given its name and context
* @post return value TRUE implies *resContext!=0 or *resMember!=0
*/
bool resolveRef(/* in */ const QCString &scName,
/* in */ const QCString &name,
/* in */ bool inSeeBlock,
/* out */ const Definition **resContext,
/* out */ const MemberDef **resMember,
bool lookForSpecialization,
const FileDef *currentFile,
bool checkScope
)
{
AUTO_TRACE("scope={} name={} inSeeBlock={}",scName,name,inSeeBlock);
//printf("resolveRef(scope=%s,name=%s,inSeeBlock=%d)\n",qPrint(scName),qPrint(name),inSeeBlock);
QCString tsName = name;
//bool memberScopeFirst = tsName.find('#')!=-1;
QCString fullName = substitute(tsName,"#","::");
if (fullName.find("anonymous_namespace{")==-1)
{
fullName = removeRedundantWhiteSpace(substitute(fullName,".","::",3));
}
else
{
fullName = removeRedundantWhiteSpace(fullName);
}
int bracePos=findParameterList(fullName);
int endNamePos=bracePos!=-1 ? bracePos : static_cast<int>(fullName.length());
int scopePos=fullName.findRev("::",endNamePos);
bool explicitScope = fullName.startsWith("::") && // ::scope or #scope
(scopePos>2 || // ::N::A
tsName.startsWith("::") || // ::foo in local scope
scName==nullptr // #foo in global scope
);
bool allowTypeOnly=false;
// default result values
*resContext=nullptr;
*resMember=nullptr;
if (bracePos==-1) // simple name
{
// the following if() was commented out for releases in the range
// 1.5.2 to 1.6.1, but has been restored as a result of bug report 594787.
if (!inSeeBlock && scopePos==-1 && isLowerCase(tsName))
{ // link to lower case only name => do not try to autolink
AUTO_TRACE_ADD("false");
return FALSE;
}
ClassDef *cd=nullptr;
NamespaceDef *nd=nullptr;
ConceptDef *cnd=nullptr;
//printf("scName=%s fullName=%s\n",qPrint(scName),qPrint(fullName));
// check if this is a class or namespace reference
if (scName!=fullName && getScopeDefs(scName,fullName,cd,cnd,nd))
{
//printf("found scopeDef\n");
if (cd) // scope matches that of a class
{
*resContext = cd;
}
else if (cnd)
{
*resContext = cnd;
}
else // scope matches that of a namespace
{
ASSERT(nd!=nullptr);
*resContext = nd;
}
AUTO_TRACE_ADD("true");
return TRUE;
}
else if (scName==fullName || (!inSeeBlock && scopePos==-1))
// nothing to link => output plain text
{
//printf("found scName=%s fullName=%s scName==fullName=%d "
// "inSeeBlock=%d scopePos=%d!\n",
// qPrint(scName),qPrint(fullName),scName==fullName,inSeeBlock,scopePos);
// at this point we have a bare word that is not a class or namespace
// we should also allow typedefs or enums to be linked, but not for instance member
// functions, otherwise 'Foo' would always link to the 'Foo()' constructor instead of the
// 'Foo' class. So we use this flag as a filter.
allowTypeOnly=true;
}
// continue search...
}
// extract userscope+name
QCString nameStr=fullName.left(endNamePos);
if (explicitScope) nameStr=nameStr.mid(2);
// extract arguments
QCString argsStr;
if (bracePos!=-1) argsStr=fullName.right(fullName.length()-bracePos);
// strip template specifier
// TODO: match against the correct partial template instantiation
int templPos=nameStr.find('<');
bool tryUnspecializedVersion = FALSE;
if (templPos!=-1 && nameStr.find("operator")==-1)
{
int endTemplPos=nameStr.findRev('>');
if (endTemplPos!=-1)
{
if (!lookForSpecialization)
{
nameStr=nameStr.left(templPos)+nameStr.right(nameStr.length()-endTemplPos-1);
}
else
{
tryUnspecializedVersion = TRUE;
}
}
}
QCString scopeStr=scName;
if (nameStr.length()>scopeStr.length() && leftScopeMatch(scopeStr,nameStr))
{
nameStr=nameStr.mid(scopeStr.length()+2);
}
const GroupDef *gd = nullptr;
const ConceptDef *cnd = nullptr;
// check if nameStr is a member or global.
//printf("getDefs(scope=%s,name=%s,args=%s checkScope=%d)\n",
// qPrint(scopeStr), qPrint(nameStr), qPrint(argsStr),checkScope);
GetDefInput input(scopeStr,nameStr,argsStr);
input.forceEmptyScope = explicitScope;
input.currentFile = currentFile;
input.checkCV = true;
GetDefResult result = getDefs(input);
if (result.found)
{
//printf("after getDefs checkScope=%d nameStr=%s\n",checkScope,qPrint(nameStr));
if (checkScope && result.md && result.md->getOuterScope()==Doxygen::globalScope &&
!result.md->isStrongEnumValue() &&
(!scopeStr.isEmpty() || nameStr.find("::")>0))
{
// we did find a member, but it is a global one while we were explicitly
// looking for a scoped variable. See bug 616387 for an example why this check is needed.
// note we do need to support autolinking to "::symbol" hence the >0
//printf("not global member!\n");
*resContext=nullptr;
*resMember=nullptr;
AUTO_TRACE_ADD("false");
return FALSE;
}
//printf("after getDefs md=%p cd=%p fd=%p nd=%p gd=%p\n",md,cd,fd,nd,gd);
if (result.md) {
if (!allowTypeOnly || result.md->isTypedef() || result.md->isEnumerate())
{
*resMember=result.md;
*resContext=result.md;
}
else // md is not a type, but we explicitly expect one
{
*resContext=nullptr;
*resMember=nullptr;
AUTO_TRACE_ADD("false");
return FALSE;
}
}
else if (result.cd) *resContext=result.cd;
else if (result.nd) *resContext=result.nd;
else if (result.fd) *resContext=result.fd;
else if (result.gd) *resContext=result.gd;
else { *resContext=nullptr; *resMember=nullptr; return FALSE; }
//printf("member=%s (md=%p) anchor=%s linkable()=%d context=%s\n",
// qPrint(md->name()), md, qPrint(md->anchor()), md->isLinkable(), qPrint((*resContext)->name()));
AUTO_TRACE_ADD("true");
return TRUE;
}
else if (inSeeBlock && !nameStr.isEmpty() && (gd=Doxygen::groupLinkedMap->find(nameStr)))
{ // group link
*resContext=gd;
AUTO_TRACE_ADD("true");
return TRUE;
}
else if ((cnd=Doxygen::conceptLinkedMap->find(nameStr)))
{
*resContext=cnd;
AUTO_TRACE_ADD("true");
return TRUE;
}
else if (tsName.find('.')!=-1) // maybe a link to a file
{
bool ambig = false;
const FileDef *fd=findFileDef(Doxygen::inputNameLinkedMap,tsName,ambig);
if (fd && !ambig)
{
*resContext=fd;
AUTO_TRACE_ADD("true");
return TRUE;
}
}
if (tryUnspecializedVersion)
{
bool b = resolveRef(scName,name,inSeeBlock,resContext,resMember,FALSE,nullptr,checkScope);
AUTO_TRACE_ADD("{}",b);
return b;
}
if (bracePos!=-1) // Try without parameters as well, could be a constructor invocation
{
*resContext=getClass(fullName.left(bracePos));
if (*resContext)
{
AUTO_TRACE_ADD("true");
return TRUE;
}
}
//printf("resolveRef: %s not found!\n",qPrint(name));
AUTO_TRACE_ADD("false");
return FALSE;
}
QCString linkToText(SrcLangExt lang,const QCString &link,bool isFileName)
{
//bool optimizeOutputJava = Config_getBool(OPTIMIZE_OUTPUT_JAVA);
QCString result=link;
if (!result.isEmpty())
{
// replace # by ::
result=substitute(result,"#","::");
// replace . by ::
if (!isFileName && result.find('<')==-1) result=substitute(result,".","::",3);
// strip leading :: prefix if present
if (result.at(0)==':' && result.at(1)==':')
{
result=result.right(result.length()-2);
}
QCString sep = getLanguageSpecificSeparator(lang);
if (sep!="::")
{
result=substitute(result,"::",sep);
}
}
//printf("linkToText(%s,lang=%d)=%s\n",qPrint(link),lang,qPrint(result));
return result;
}
bool resolveLink(/* in */ const QCString &scName,
/* in */ const QCString &lr,
/* in */ bool /*inSeeBlock*/,
/* out */ const Definition **resContext,
/* out */ QCString &resAnchor,
/* in */ const QCString &prefix
)
{
*resContext=nullptr;
QCString linkRef=lr;
QCString linkRefWithoutTemplates = stripTemplateSpecifiersFromScope(linkRef,FALSE);
//printf("ResolveLink linkRef=%s\n",qPrint(lr));
const FileDef *fd = nullptr;
const GroupDef *gd = nullptr;
const PageDef *pd = nullptr;
const ClassDef *cd = nullptr;
const DirDef *dir = nullptr;
const ConceptDef *cnd = nullptr;
const NamespaceDef *nd = nullptr;
const SectionInfo *si = nullptr;
bool ambig = false;
if (linkRef.isEmpty()) // no reference name!
{
return FALSE;
}
else if ((pd=Doxygen::pageLinkedMap->find(linkRef))) // link to a page
{
gd = pd->getGroupDef();
if (gd)
{
if (!pd->name().isEmpty()) si=SectionManager::instance().find(pd->name());
*resContext=gd;
if (si) resAnchor = si->label();
}
else
{
*resContext=pd;
}
return TRUE;
}
else if ((si=SectionManager::instance().find(prefix+linkRef)))
{
*resContext=si->definition();
resAnchor = si->label();
return TRUE;
}
else if ((pd=Doxygen::exampleLinkedMap->find(linkRef))) // link to an example
{
*resContext=pd;
return TRUE;
}
else if ((gd=Doxygen::groupLinkedMap->find(linkRef))) // link to a group
{
*resContext=gd;
return TRUE;
}
else if ((fd=findFileDef(Doxygen::inputNameLinkedMap,linkRef,ambig)) // file link
&& fd->isLinkable())
{
*resContext=fd;
return TRUE;
}
else if ((cd=getClass(linkRef))) // class link
{
*resContext=cd;
resAnchor=cd->anchor();
return TRUE;
}
else if ((cd=getClass(linkRefWithoutTemplates))) // C#/Java generic class link
{
*resContext=cd;
resAnchor=cd->anchor();
return TRUE;
}
else if ((cd=getClass(linkRef+"-p"))) // Obj-C protocol link
{
*resContext=cd;
resAnchor=cd->anchor();
return TRUE;
}
else if ((cnd=getConcept(linkRef))) // C++20 concept definition
{
*resContext=cnd;
resAnchor=cnd->anchor();
return TRUE;
}
else if ((nd=Doxygen::namespaceLinkedMap->find(linkRef)))
{
*resContext=nd;
return TRUE;
}
else if ((dir=Doxygen::dirLinkedMap->find(FileInfo(linkRef.str()).absFilePath()+"/"))
&& dir->isLinkable()) // TODO: make this location independent like filedefs
{
*resContext=dir;
return TRUE;
}
else // probably a member reference
{
const MemberDef *md = nullptr;
bool res = resolveRef(scName,lr,TRUE,resContext,&md);
if (md) resAnchor=md->anchor();
return res;
}
}
void generateFileRef(OutputList &ol,const QCString &name,const QCString &text)
{
//printf("generateFileRef(%s,%s)\n",name,text);
QCString linkText = text.isEmpty() ? text : name;
//FileInfo *fi;
bool ambig = false;
FileDef *fd = findFileDef(Doxygen::inputNameLinkedMap,name,ambig);
if (fd && fd->isLinkable())
// link to documented input file
ol.writeObjectLink(fd->getReference(),fd->getOutputFileBase(),QCString(),linkText);
else
ol.docify(linkText);
}
//----------------------------------------------------------------------
/** Cache element for the file name to FileDef mapping cache. */
struct FindFileCacheElem
{
FindFileCacheElem(FileDef *fd,bool ambig) : fileDef(fd), isAmbig(ambig) {}
FileDef *fileDef;
bool isAmbig;
};
static Cache<std::string,FindFileCacheElem> g_findFileDefCache(5000);
static std::mutex g_findFileDefMutex;
FileDef *findFileDef(const FileNameLinkedMap *fnMap,const QCString &n,bool &ambig)
{
ambig=FALSE;
if (n.isEmpty()) return nullptr;
const int maxAddrSize = 20;
char addr[maxAddrSize];
qsnprintf(addr,maxAddrSize,"%p:",reinterpret_cast<const void*>(fnMap));
QCString key = addr;
key+=n;
std::lock_guard<std::mutex> lock(g_findFileDefMutex);
FindFileCacheElem *cachedResult = g_findFileDefCache.find(key.str());
//printf("key=%s cachedResult=%p\n",qPrint(key),cachedResult);
if (cachedResult)
{
ambig = cachedResult->isAmbig;
//printf("cached: fileDef=%p\n",cachedResult->fileDef);
return cachedResult->fileDef;
}
else
{
cachedResult = g_findFileDefCache.insert(key.str(),FindFileCacheElem(nullptr,FALSE));
}
QCString name=Dir::cleanDirPath(n.str());
QCString path;
if (name.isEmpty()) return nullptr;
int slashPos=std::max(name.findRev('/'),name.findRev('\\'));
if (slashPos!=-1)
{
path=removeLongPathMarker(name.left(slashPos+1));
name=name.right(name.length()-slashPos-1);
}
if (name.isEmpty()) return nullptr;
const FileName *fn = fnMap->find(name);
if (fn)
{
//printf("fn->size()=%zu\n",fn->size());
if (fn->size()==1)
{
const std::unique_ptr<FileDef> &fd = fn->front();
bool isSamePath = Portable::fileSystemIsCaseSensitive() ?
fd->getPath().right(path.length())==path :
fd->getPath().right(path.length()).lower()==path.lower();
if (path.isEmpty() || isSamePath)
{
cachedResult->fileDef = fd.get();
return fd.get();
}
}
else // file name alone is ambiguous
{
int count=0;
FileDef *lastMatch=nullptr;
QCString pathStripped = stripFromIncludePath(path);
for (const auto &fd_p : *fn)
{
FileDef *fd = fd_p.get();
QCString fdStripPath = stripFromIncludePath(fd->getPath());
if (path.isEmpty() || fdStripPath.right(pathStripped.length())==pathStripped)
{
count++;
lastMatch=fd;
}
}
ambig=(count>1);
cachedResult->isAmbig = ambig;
cachedResult->fileDef = lastMatch;
return lastMatch;
}
}
else
{
//printf("not found!\n");
}
return nullptr;
}
//----------------------------------------------------------------------
QCString findFilePath(const QCString &file,bool &ambig)
{
ambig=false;
QCString result;
bool found=false;
if (!found)
{
FileInfo fi(file.str());
if (fi.exists())
{
result=fi.absFilePath();
found=true;
}
}
if (!found)
{
const StringVector &examplePathList = Config_getList(EXAMPLE_PATH);
for (const auto &s : examplePathList)
{
std::string absFileName = s+(Portable::pathSeparator()+file).str();
FileInfo fi(absFileName);
if (fi.exists())
{
result=fi.absFilePath();
found=true;
}
}
}
if (!found)
{
// as a fallback we also look in the exampleNameDict
FileDef *fd = findFileDef(Doxygen::exampleNameLinkedMap,file,ambig);
if (fd && !ambig)
{
result=fd->absFilePath();
}
}
return result;
}
//----------------------------------------------------------------------
QCString showFileDefMatches(const FileNameLinkedMap *fnMap,const QCString &n)
{
QCString result;
QCString name=n;
QCString path;
int slashPos=std::max(name.findRev('/'),name.findRev('\\'));
if (slashPos!=-1)
{
path=name.left(slashPos+1);
name=name.right(name.length()-slashPos-1);
}
const FileName *fn=fnMap->find(name);
if (fn)
{
bool first = true;
for (const auto &fd : *fn)
{
if (path.isEmpty() || fd->getPath().right(path.length())==path)
{
if (!first) result += "\n";
else first = false;
result+=" "+fd->absFilePath();
}
}
}
return result;
}
//----------------------------------------------------------------------
QCString substituteKeywords(const QCString &s,const KeywordSubstitutionList &keywords)
{
std::string substRes;
const char *p = s.data();
if (p)
{
// reserve some room for expansion
substRes.reserve(s.length()+1024);
char c = 0;
while ((c=*p))
{
bool found = false;
if (c=='$')
{
for (const auto &kw : keywords)
{
size_t keyLen = qstrlen(kw.keyword);
if (qstrncmp(p,kw.keyword,keyLen)==0)
{
const char *startArg = p+keyLen;
bool expectParam = std::holds_alternative<KeywordSubstitution::GetValueWithParam>(kw.getValueVariant);
//printf("%s: expectParam=%d *startArg=%c\n",kw.keyword,expectParam,*startArg);
if (expectParam && *startArg=='(') // $key(value)
{
size_t j=1;
const char *endArg = nullptr;
while ((c=*(startArg+j)) && c!=')' && c!='\n' && c!=0) j++;
if (c==')') endArg=startArg+j;
if (endArg)
{
QCString value = QCString(startArg+1).left(endArg-startArg-1);
auto &&getValue = std::get<KeywordSubstitution::GetValueWithParam>(kw.getValueVariant);
substRes+=getValue(value).str();
p=endArg+1;
//printf("found '%s'->'%s'\n",kw.keyword,qPrint(getValue(value)));
}
else
{
//printf("missing argument\n");
p+=keyLen;
}
}
else if (!expectParam) // $key
{
auto &&getValue = std::get<KeywordSubstitution::GetValue>(kw.getValueVariant);
substRes+=getValue().str();
//printf("found '%s'->'%s'\n",kw.keyword,qPrint(getValue()));
p+=keyLen;
}
found = true;
break;
}
}
}
if (!found) // copy
{
substRes+=c;
p++;
}
}
}
return substRes;
}
static QCString showDate(const QCString &fmt)
{
// get the current date and time
std::tm dat{};
int specFormat=0;
QCString specDate = "";
QCString err = dateTimeFromString(specDate,dat,specFormat);
// do the conversion
int usedFormat=0;
return formatDateTime(fmt,dat,usedFormat);
}
QCString projectLogoFile()
{
QCString projectLogo = Config_getString(PROJECT_LOGO);
if (!projectLogo.isEmpty())
{
// check for optional width= and height= specifier
int wi = projectLogo.find(" width=");
if (wi!=-1) // and strip them
{
projectLogo = projectLogo.left(wi);
}
int hi = projectLogo.find(" height=");
if (hi!=-1)
{
projectLogo = projectLogo.left(hi);
}
}
//printf("projectlogo='%s'\n",qPrint(projectLogo));
return projectLogo;
}
static QCString projectLogoSize()
{
QCString sizeVal;
QCString projectLogo = Config_getString(PROJECT_LOGO);
if (!projectLogo.isEmpty())
{
auto extractDimension = [&projectLogo](const char *startMarker,size_t startPos,size_t endPos) -> QCString
{
QCString result = projectLogo.mid(startPos,endPos-startPos).stripWhiteSpace().quoted();
if (result.length()>=2 && result.at(0)!='"' && result.at(result.length()-1)!='"')
{
result="\""+result+"\"";
}
result.prepend(startMarker);
return result;
};
// check for optional width= and height= specifier
int wi = projectLogo.find(" width=");
int hi = projectLogo.find(" height=");
if (wi!=-1 && hi!=-1)
{
if (wi<hi) // "... width=x height=y..."
{
sizeVal = extractDimension(" width=", wi+7, hi) + " "
+ extractDimension(" height=", hi+8, projectLogo.length());
}
else // "... height=y width=x..."
{
sizeVal = extractDimension(" height=", hi+8, wi) + " "
+ extractDimension(" width=", wi+7, projectLogo.length());
}
}
else if (wi!=-1) // ... width=x..."
{
sizeVal = extractDimension(" width=", wi+7, projectLogo.length());
}
else if (hi!=-1) // ... height=x..."
{
sizeVal = extractDimension(" height=", hi+8, projectLogo.length());
}
}
//printf("projectsize='%s'\n",qPrint(sizeVal));
return sizeVal;
}
QCString substituteKeywords(const QCString &s,const QCString &title,
const QCString &projName,const QCString &projNum,const QCString &projBrief)
{
return substituteKeywords(s,
{
// keyword value getter
{ "$title", [&]() { return !title.isEmpty() ? title : projName; } },
{ "$datetime", [&]() { return dateToString(DateTimeType::DateTime); } },
{ "$date", [&]() { return dateToString(DateTimeType::Date); } },
{ "$time", [&]() { return dateToString(DateTimeType::Time); } },
{ "$year", [&]() { return yearToString(); } },
{ "$doxygenversion", [&]() { return getDoxygenVersion(); } },
{ "$projectname", [&]() { return projName; } },
{ "$projectnumber", [&]() { return projNum; } },
{ "$projectbrief", [&]() { return projBrief; } },
{ "$projectlogo", [&]() { return stripPath(projectLogoFile()); } },
{ "$logosize", [&]() { return projectLogoSize(); } },
{ "$projecticon", [&]() { return stripPath(Config_getString(PROJECT_ICON)); } },
{ "$langISO", [&]() { return theTranslator->trISOLang(); } },
{ "$showdate", [&](const QCString &fmt) { return showDate(fmt); } }
});
}
//----------------------------------------------------------------------
/*! Returns the character index within \a name of the first prefix
* in Config_getList(IGNORE_PREFIX) that matches \a name at the left hand side,
* or zero if no match was found
*/
int getPrefixIndex(const QCString &name)
{
if (name.isEmpty()) return 0;
const StringVector &sl = Config_getList(IGNORE_PREFIX);
for (const auto &s : sl)
{
const char *ps=s.c_str();
const char *pd=name.data();
int i=0;
while (*ps!=0 && *pd!=0 && *ps==*pd) ps++,pd++,i++;
if (*ps==0 && *pd!=0)
{
return i;
}
}
return 0;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------
#if 0
// copies the next UTF8 character from input stream into buffer ids
// returns the size of the character in bytes (or 0 if it is invalid)
// the character itself will be copied as a UTF-8 encoded string to ids.
int getUtf8Char(const char *input,char ids[MAX_UTF8_CHAR_SIZE],CaseModifier modifier)
{
int inputLen=1;
const unsigned char uc = (unsigned char)*input;
bool validUTF8Char = false;
if (uc <= 0xf7)
{
const char* pt = input+1;
int l = 0;
if ((uc&0x80)==0x00)
{
switch (modifier)
{
case CaseModifier::None: ids[0]=*input; break;
case CaseModifier::ToUpper: ids[0]=(char)toupper(*input); break;
case CaseModifier::ToLower: ids[0]=(char)tolower(*input); break;
}
l=1; // 0xxx.xxxx => normal single byte ascii character
}
else
{
ids[ 0 ] = *input;
if ((uc&0xE0)==0xC0)
{
l=2; // 110x.xxxx: >=2 byte character
}
if ((uc&0xF0)==0xE0)
{
l=3; // 1110.xxxx: >=3 byte character
}
if ((uc&0xF8)==0xF0)
{
l=4; // 1111.0xxx: >=4 byte character
}
}
validUTF8Char = l>0;
for (int m=1; m<l && validUTF8Char; ++m)
{
unsigned char ct = (unsigned char)*pt;
if (ct==0 || (ct&0xC0)!=0x80) // invalid unicode character
{
validUTF8Char=false;
}
else
{
ids[ m ] = *pt++;
}
}
if (validUTF8Char) // got a valid unicode character
{
ids[ l ] = 0;
inputLen=l;
}
}
return inputLen;
}
#endif
bool getCaseSenseNames()
{
auto caseSenseNames = Config_getEnum(CASE_SENSE_NAMES);
if (caseSenseNames == CASE_SENSE_NAMES_t::YES) return true;
else if (caseSenseNames == CASE_SENSE_NAMES_t::NO) return false;
else return Portable::fileSystemIsCaseSensitive();
}
// note that this function is not reentrant due to the use of static growBuf!
QCString escapeCharsInString(const QCString &name,bool allowDots,bool allowUnderscore)
{
if (name.isEmpty()) return name;
bool caseSenseNames = getCaseSenseNames();
bool allowUnicodeNames = Config_getBool(ALLOW_UNICODE_NAMES);
GrowBuf growBuf;
signed char c = 0;
const char *p=name.data();
while ((c=*p++)!=0)
{
switch(c)
{
case '_': if (allowUnderscore) growBuf.addChar('_'); else growBuf.addStr("__"); break;
case '-': growBuf.addChar('-'); break;
case ':': growBuf.addStr("_1"); break;
case '/': growBuf.addStr("_2"); break;
case '<': growBuf.addStr("_3"); break;
case '>': growBuf.addStr("_4"); break;
case '*': growBuf.addStr("_5"); break;
case '&': growBuf.addStr("_6"); break;
case '|': growBuf.addStr("_7"); break;
case '.': if (allowDots) growBuf.addChar('.'); else growBuf.addStr("_8"); break;
case '!': growBuf.addStr("_9"); break;
case ',': growBuf.addStr("_00"); break;
case ' ': growBuf.addStr("_01"); break;
case '{': growBuf.addStr("_02"); break;
case '}': growBuf.addStr("_03"); break;
case '?': growBuf.addStr("_04"); break;
case '^': growBuf.addStr("_05"); break;
case '%': growBuf.addStr("_06"); break;
case '(': growBuf.addStr("_07"); break;
case ')': growBuf.addStr("_08"); break;
case '+': growBuf.addStr("_09"); break;
case '=': growBuf.addStr("_0a"); break;
case '$': growBuf.addStr("_0b"); break;
case '\\': growBuf.addStr("_0c"); break;
case '@': growBuf.addStr("_0d"); break;
case ']': growBuf.addStr("_0e"); break;
case '[': growBuf.addStr("_0f"); break;
case '#': growBuf.addStr("_0g"); break;
case '"': growBuf.addStr("_0h"); break;
case '~': growBuf.addStr("_0i"); break;
case '\'': growBuf.addStr("_0j"); break;
case ';': growBuf.addStr("_0k"); break;
case '`': growBuf.addStr("_0l"); break;
default:
if (c<0)
{
bool doEscape = true;
if (allowUnicodeNames)
{
int charLen = getUTF8CharNumBytes(c);
if (charLen>0)
{
growBuf.addStr(p-1,charLen);
p+=charLen;
doEscape = false;
}
}
if (doEscape) // not a valid unicode char or escaping needed
{
char ids[5];
unsigned char id = static_cast<unsigned char>(c);
ids[0]='_';
ids[1]='x';
ids[2]=hex[id>>4];
ids[3]=hex[id&0xF];
ids[4]=0;
growBuf.addStr(ids);
}
}
else if (caseSenseNames || !isupper(c))
{
growBuf.addChar(c);
}
else
{
growBuf.addChar('_');
growBuf.addChar(static_cast<char>(tolower(c)));
}
break;
}
}
growBuf.addChar(0);
return growBuf.get();
}
QCString unescapeCharsInString(const QCString &s)
{
if (s.isEmpty()) return s;
bool caseSenseNames = getCaseSenseNames();
QCString result;
const char *p = s.data();
if (p)
{
char c = 0;
while ((c=*p++))
{
if (c=='_') // 2 or 3 character escape
{
switch (*p)
{
case '_': result+=c; p++; break; // __ -> '_'
case '1': result+=':'; p++; break; // _1 -> ':'
case '2': result+='/'; p++; break; // _2 -> '/'
case '3': result+='<'; p++; break; // _3 -> '<'
case '4': result+='>'; p++; break; // _4 -> '>'
case '5': result+='*'; p++; break; // _5 -> '*'
case '6': result+='&'; p++; break; // _6 -> '&'
case '7': result+='|'; p++; break; // _7 -> '|'
case '8': result+='.'; p++; break; // _8 -> '.'
case '9': result+='!'; p++; break; // _9 -> '!'
case '0': // 3 character escape
switch (*(p+1))
{
case '0': result+=','; p+=2; break; // _00 -> ','
case '1': result+=' '; p+=2; break; // _01 -> ' '
case '2': result+='{'; p+=2; break; // _02 -> '{'
case '3': result+='}'; p+=2; break; // _03 -> '}'
case '4': result+='?'; p+=2; break; // _04 -> '?'
case '5': result+='^'; p+=2; break; // _05 -> '^'
case '6': result+='%'; p+=2; break; // _06 -> '%'
case '7': result+='('; p+=2; break; // _07 -> '('
case '8': result+=')'; p+=2; break; // _08 -> ')'
case '9': result+='+'; p+=2; break; // _09 -> '+'
case 'a': result+='='; p+=2; break; // _0a -> '='
case 'b': result+='$'; p+=2; break; // _0b -> '$'
case 'c': result+='\\'; p+=2; break;// _0c -> '\'
case 'd': result+='@'; p+=2; break; // _0d -> '@'
case 'e': result+=']'; p+=2; break; // _0e -> ']'
case 'f': result+='['; p+=2; break; // _0f -> '['
case 'g': result+='#'; p+=2; break; // _0g -> '#'
case 'h': result+='"'; p+=2; break; // _0h -> '"'
case 'i': result+='~'; p+=2; break; // _0i -> '~'
case 'j': result+='\''; p+=2; break;// _0j -> '\'
case 'k': result+=';'; p+=2; break; // _0k -> ';'
case 'l': result+='`'; p+=2; break; // _0l -> '`'
default: // unknown escape, just pass underscore character as-is
result+=c;
break;
}
break;
default:
if (!caseSenseNames && c>='a' && c<='z') // lower to upper case escape, _a -> 'A'
{
result+=static_cast<char>(toupper(*p));
p++;
}
else // unknown escape, pass underscore character as-is
{
result+=c;
}
break;
}
}
else // normal character; pass as is
{
result+=c;
}
}
}
return result;
}
static std::unordered_map<std::string,int> g_usedNames;
static std::mutex g_usedNamesMutex;
static int g_usedNamesCount=1;
/*! This function determines the file name on disk of an item
* given its name, which could be a class name with template
* arguments, so special characters need to be escaped.
*/
QCString convertNameToFile(const QCString &name,bool allowDots,bool allowUnderscore)
{
if (name.isEmpty()) return name;
bool shortNames = Config_getBool(SHORT_NAMES);
bool createSubdirs = Config_getBool(CREATE_SUBDIRS);
QCString result;
if (shortNames) // use short names only
{
std::lock_guard<std::mutex> lock(g_usedNamesMutex);
auto kv = g_usedNames.find(name.str());
uint32_t num=0;
if (kv!=g_usedNames.end())
{
num = kv->second;
}
else
{
num = g_usedNamesCount;
g_usedNames.emplace(name.str(),g_usedNamesCount++);
}
result.sprintf("a%05d",num);
}
else // long names
{
result=escapeCharsInString(name,allowDots,allowUnderscore);
size_t resultLen = result.length();
if (resultLen>=128) // prevent names that cannot be created!
{
// third algorithm based on MD5 hash
uint8_t md5_sig[16];
char sigStr[33];
MD5Buffer(result.data(),static_cast<unsigned int>(resultLen),md5_sig);
MD5SigToString(md5_sig,sigStr);
result=result.left(128-32)+sigStr;
}
}
if (createSubdirs)
{
int l1Dir=0,l2Dir=0;
int createSubdirsLevel = Config_getInt(CREATE_SUBDIRS_LEVEL);
int createSubdirsBitmaskL2 = (1<<createSubdirsLevel)-1;
// compute md5 hash to determine sub directory to use
uint8_t md5_sig[16];
MD5Buffer(result.data(),static_cast<unsigned int>(result.length()),md5_sig);
l1Dir = md5_sig[14] & 0xf;
l2Dir = md5_sig[15] & createSubdirsBitmaskL2;
result.prepend(QCString().sprintf("d%x/d%02x/",l1Dir,l2Dir));
}
//printf("*** convertNameToFile(%s)->%s\n",qPrint(name),qPrint(result));
return result;
}
QCString generateAnonymousAnchor(const QCString &fileName,int count)
{
QCString fn = stripFromPath(fileName)+":"+QCString().setNum(count);
const int sig_size=16;
uint8_t md5_sig[sig_size];
MD5Buffer(fn.data(),static_cast<unsigned int>(fn.length()),md5_sig);
char result[sig_size*3+2];
char *p = result;
*p++='@';
for (int i=0;i<sig_size;i++)
{
static const char oct[]="01234567";
uint8_t byte = md5_sig[i];
*p++=oct[(byte>>6)&7];
*p++=oct[(byte>>3)&7];
*p++=oct[(byte>>0)&7];
}
*p='\0';
return result;
}
QCString relativePathToRoot(const QCString &name)
{
QCString result;
if (Config_getBool(CREATE_SUBDIRS))
{
if (name.isEmpty())
{
return REL_PATH_TO_ROOT;
}
else
{
int i = name.findRev('/');
if (i!=-1)
{
result=REL_PATH_TO_ROOT;
}
}
}
return result;
}
QCString determineAbsoluteIncludeName(const QCString &curFile,const QCString &incFileName)
{
bool searchIncludes = Config_getBool(SEARCH_INCLUDES);
QCString absIncFileName = incFileName;
FileInfo fi(curFile.str());
if (fi.exists())
{
QCString absName = QCString(fi.dirPath(TRUE))+"/"+incFileName;
FileInfo fi2(absName.str());
if (fi2.exists())
{
absIncFileName=fi2.absFilePath();
}
else if (searchIncludes) // search in INCLUDE_PATH as well
{
const StringVector &includePath = Config_getList(INCLUDE_PATH);
for (const auto &incPath : includePath)
{
FileInfo fi3(incPath);
if (fi3.exists() && fi3.isDir())
{
absName = QCString(fi3.absFilePath())+"/"+incFileName;
//printf("trying absName=%s\n",qPrint(absName));
FileInfo fi4(absName.str());
if (fi4.exists())
{
absIncFileName=fi4.absFilePath();
break;
}
//printf( "absIncFileName = %s\n", qPrint(absIncFileName) );
}
}
}
//printf( "absIncFileName = %s\n", qPrint(absIncFileName) );
}
return absIncFileName;
}
void createSubDirs(const Dir &d)
{
if (Config_getBool(CREATE_SUBDIRS))
{
// create up to 4096 subdirectories
int createSubdirsLevelPow2 = 1 << Config_getInt(CREATE_SUBDIRS_LEVEL);
for (int l1=0; l1<16; l1++)
{
QCString subdir;
subdir.sprintf("d%x",l1);
if (!d.exists(subdir.str()) && !d.mkdir(subdir.str()))
{
term("Failed to create output directory '%s'\n",qPrint(subdir));
}
for (int l2=0; l2<createSubdirsLevelPow2; l2++)
{
QCString subsubdir;
subsubdir.sprintf("d%x/d%02x",l1,l2);
if (!d.exists(subsubdir.str()) && !d.mkdir(subsubdir.str()))
{
term("Failed to create output directory '%s'\n",qPrint(subsubdir));
}
}
}
}
}
void clearSubDirs(const Dir &d)
{
if (Config_getBool(CREATE_SUBDIRS))
{
// remove empty subdirectories
int createSubdirsLevelPow2 = 1 << Config_getInt(CREATE_SUBDIRS_LEVEL);
for (int l1=0;l1<16;l1++)
{
QCString subdir;
subdir.sprintf("d%x",l1);
for (int l2=0; l2 < createSubdirsLevelPow2; l2++)
{
QCString subsubdir;
subsubdir.sprintf("d%x/d%02x",l1,l2);
if (d.exists(subsubdir.str()) && d.isEmpty(subsubdir.str()))
{
d.rmdir(subsubdir.str());
}
}
if (d.exists(subdir.str()) && d.isEmpty(subdir.str()))
{
d.rmdir(subdir.str());
}
}
}
}
/*! Input is a scopeName, output is the scopename split into a
* namespace part (as large as possible) and a classname part.
*/
void extractNamespaceName(const QCString &scopeName,
QCString &className,QCString &namespaceName,
bool allowEmptyClass)
{
int i=0, p=0;
QCString clName=scopeName;
NamespaceDef *nd = nullptr;
if (!clName.isEmpty() && (nd=getResolvedNamespace(clName)) && getClass(clName)==nullptr)
{ // the whole name is a namespace (and not a class)
namespaceName=nd->name();
className.clear();
goto done;
}
p=static_cast<int>(clName.length())-2;
while (p>=0 && (i=clName.findRev("::",p))!=-1)
// see if the first part is a namespace (and not a class)
{
//printf("Trying %s\n",qPrint(clName.left(i)));
if (i>0 && (nd=getResolvedNamespace(clName.left(i))) && getClass(clName.left(i))==nullptr)
{
//printf("found!\n");
namespaceName=nd->name();
className=clName.right(clName.length()-i-2);
goto done;
}
p=i-2; // try a smaller piece of the scope
}
//printf("not found!\n");
// not found, so we just have to guess.
className=scopeName;
namespaceName.clear();
done:
if (className.isEmpty() && !namespaceName.isEmpty() && !allowEmptyClass)
{
// class and namespace with the same name, correct to return the class.
className=namespaceName;
namespaceName.clear();
}
//printf("extractNamespace '%s' => '%s|%s'\n",qPrint(scopeName),
// qPrint(className),qPrint(namespaceName));
if (className.endsWith("-p"))
{
className = className.left(className.length()-2);
}
return;
}
QCString insertTemplateSpecifierInScope(const QCString &scope,const QCString &templ)
{
QCString result=scope;
if (!templ.isEmpty() && scope.find('<')==-1)
{
int si=0, pi=0;
ClassDef *cd=nullptr;
while (
(si=scope.find("::",pi))!=-1 && !getClass(scope.left(si)+templ) &&
((cd=getClass(scope.left(si)))==nullptr || cd->templateArguments().empty())
)
{
//printf("Tried '%s'\n",qPrint((scope.left(si)+templ)));
pi=si+2;
}
if (si==-1) // not nested => append template specifier
{
result+=templ;
}
else // nested => insert template specifier before after first class name
{
result=scope.left(si) + templ + scope.right(scope.length()-si);
}
}
//printf("insertTemplateSpecifierInScope('%s','%s')=%s\n",
// qPrint(scope),qPrint(templ),qPrint(result));
return result;
}
/*! Strips the scope from a name. Examples: A::B will return A
* and A<T>::B<N::C<D> > will return A<T>.
*/
QCString stripScope(const QCString &name)
{
QCString result = name;
int l = static_cast<int>(result.length());
int p = 0;
bool done = FALSE;
bool skipBracket=FALSE; // if brackets do not match properly, ignore them altogether
int count=0;
int round=0;
do
{
p=l-1; // start at the end of the string
while (p>=0 && count>=0)
{
char c=result.at(p);
switch (c)
{
case ':':
// only exit in the case of ::
//printf("stripScope(%s)=%s\n",name,qPrint(result.right(l-p-1)));
if (p>0 && result.at(p-1)==':' && (count==0 || skipBracket))
{
return result.right(l-p-1);
}
p--;
break;
case '>':
if (skipBracket) // we don't care about brackets
{
p--;
}
else // count open/close brackets
{
if (p>0 && result.at(p-1)=='>') // skip >> operator
{
p-=2;
break;
}
count=1;
//printf("pos < = %d\n",p);
p--;
bool foundMatch=false;
while (p>=0 && !foundMatch)
{
c=result.at(p--);
switch (c)
{
case ')':
round++;
break;
case '(':
round--;
break;
case '>': // ignore > inside (...) to support e.g. (sizeof(T)>0) inside template parameters
if (round==0) count++;
break;
case '<':
if (round==0)
{
if (p>0)
{
if (result.at(p-1) == '<') // skip << operator
{
p--;
break;
}
}
count--;
foundMatch = count==0;
}
break;
default:
//printf("c=%c count=%d\n",c,count);
break;
}
}
}
//printf("pos > = %d\n",p+1);
break;
default:
p--;
}
}
done = count==0 || skipBracket; // reparse if brackets do not match
skipBracket=TRUE;
}
while (!done); // if < > unbalanced repeat ignoring them
//printf("stripScope(%s)=%s\n",name,name);
return name;
}
/*! Converts a string to a HTML id string */
QCString convertToId(const QCString &s)
{
if (s.isEmpty()) return s;
GrowBuf growBuf;
const char *p = s.data();
char c = 0;
bool first = true;
while ((c=*p++))
{
char encChar[4];
if ((c>='0' && c<='9') || (c>='a' && c<='z') || (c>='A' && c<='Z') || c=='-' || c==':' || c=='.')
{ // any permissive character except _
if (first && c>='0' && c<='9') growBuf.addChar('a'); // don't start with a digit
growBuf.addChar(c);
}
else
{
encChar[0]='_';
encChar[1]=hex[static_cast<unsigned char>(c)>>4];
encChar[2]=hex[static_cast<unsigned char>(c)&0xF];
encChar[3]=0;
growBuf.addStr(encChar);
}
first=FALSE;
}
growBuf.addChar(0);
return growBuf.get();
}
/*! Some strings have been corrected but the requirement regarding the fact
* that an id cannot have a digit at the first position. To overcome problems
* with double labels we always place an "a" in front
*/
QCString correctId(const QCString &s)
{
if (s.isEmpty()) return s;
return "a" + s;
}
/*! Converts a string to an XML-encoded string */
QCString convertToXML(const QCString &s, bool keepEntities)
{
if (s.isEmpty()) return s;
GrowBuf growBuf;
const char *p = s.data();
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '<': growBuf.addStr("<"); break;
case '>': growBuf.addStr(">"); break;
case '&': if (keepEntities)
{
const char *e=p;
char ce = 0;
while ((ce=*e++))
{
if (ce==';' || (!(isId(ce) || ce=='#'))) break;
}
if (ce==';') // found end of an entity
{
// copy entry verbatim
growBuf.addChar(c);
while (p<e) growBuf.addChar(*p++);
}
else
{
growBuf.addStr("&");
}
}
else
{
growBuf.addStr("&");
}
break;
case '\'': growBuf.addStr("'"); break;
case '"': growBuf.addStr("""); break;
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18:
case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26:
case 27: case 28: case 29: case 30: case 31:
break; // skip invalid XML characters (see http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char)
default: growBuf.addChar(c); break;
}
}
growBuf.addChar(0);
return growBuf.get();
}
/*! Converts a string to a HTML-encoded string */
QCString convertToHtml(const QCString &s,bool keepEntities)
{
if (s.isEmpty()) return s;
GrowBuf growBuf;
const char *p=s.data();
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '<': growBuf.addStr("<"); break;
case '>': growBuf.addStr(">"); break;
case '&': if (keepEntities)
{
const char *e=p;
char ce = 0;
while ((ce=*e++))
{
if (ce==';' || (!(isId(ce) || ce=='#'))) break;
}
if (ce==';') // found end of an entity
{
// copy entry verbatim
growBuf.addChar(c);
while (p<e) growBuf.addChar(*p++);
}
else
{
growBuf.addStr("&");
}
}
else
{
growBuf.addStr("&");
}
break;
case '\'': growBuf.addStr("'"); break;
case '"': growBuf.addStr("""); break;
default:
{
uint8_t uc = static_cast<uint8_t>(c);
if (uc<32 && !isspace(c))
{
growBuf.addStr("$");
growBuf.addChar(hex[uc>>4]);
growBuf.addChar(hex[uc&0xF]);
growBuf.addChar(';');
}
else
{
growBuf.addChar(c);
}
}
break;
}
}
growBuf.addChar(0);
return growBuf.get();
}
QCString convertToJSString(const QCString &s)
{
if (s.isEmpty()) return s;
GrowBuf growBuf;
const char *p=s.data();
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '"': growBuf.addStr("\\\""); break;
case '\\': if (*p=='u' && *(p+1)=='{') growBuf.addStr("\\");
else growBuf.addStr("\\\\");
break;
default: growBuf.addChar(c); break;
}
}
growBuf.addChar(0);
return convertCharEntitiesToUTF8(growBuf.get());
}
QCString convertCharEntitiesToUTF8(const QCString &str)
{
if (str.isEmpty()) return QCString();
std::string s = str.data();
static const reg::Ex re(R"(&\a\w*;)");
reg::Iterator it(s,re);
reg::Iterator end;
GrowBuf growBuf;
size_t p=0, i=0, l=0;
for (; it!=end ; ++it)
{
const auto &match = *it;
p = match.position();
l = match.length();
if (p>i)
{
growBuf.addStr(s.substr(i,p-i));
}
QCString entity(match.str());
HtmlEntityMapper::SymType symType = HtmlEntityMapper::instance().name2sym(entity);
const char *code=nullptr;
if (symType!=HtmlEntityMapper::Sym_Unknown && (code=HtmlEntityMapper::instance().utf8(symType)))
{
growBuf.addStr(code);
}
else
{
growBuf.addStr(entity);
}
i=p+l;
}
growBuf.addStr(s.substr(i));
growBuf.addChar(0);
//printf("convertCharEntitiesToUTF8(%s)->%s\n",qPrint(s),growBuf.get());
return growBuf.get();
}
/*! Returns the standard string that is generated when the \\overload
* command is used.
*/
QCString getOverloadDocs()
{
return theTranslator->trOverloadText();
//"This is an overloaded member function, "
// "provided for convenience. It differs from the above "
// "function only in what argument(s) it accepts.";
}
void addMembersToMemberGroup(MemberList *ml,
MemberGroupList *pMemberGroups,
const Definition *context)
{
ASSERT(context!=nullptr);
//printf("addMemberToMemberGroup() context=%s\n",qPrint(context->name()));
if (ml==nullptr) return;
struct MoveMemberInfo
{
MoveMemberInfo(MemberDef *md,MemberGroup *mg,const RefItemVector &rv)
: memberDef(md), memberGroup(mg), sli(rv) {}
MemberDef *memberDef;
MemberGroup *memberGroup;
RefItemVector sli;
};
std::vector<MoveMemberInfo> movedMembers;
for (const auto &md : *ml)
{
if (md->isEnumerate()) // insert enum value of this enum into groups
{
for (const auto &fmd : md->enumFieldList())
{
int groupId=fmd->getMemberGroupId();
if (groupId!=-1)
{
auto it = Doxygen::memberGroupInfoMap.find(groupId);
if (it!=Doxygen::memberGroupInfoMap.end())
{
const auto &info = it->second;
auto mg_it = std::find_if(pMemberGroups->begin(),
pMemberGroups->end(),
[&groupId](const auto &g)
{ return g->groupId()==groupId; }
);
MemberGroup *mg_ptr = nullptr;
if (mg_it==pMemberGroups->end())
{
auto mg = std::make_unique<MemberGroup>(
context,
groupId,
info->header,
info->doc,
info->docFile,
info->docLine,
ml->container());
mg_ptr = mg.get();
pMemberGroups->push_back(std::move(mg));
}
else
{
mg_ptr = (*mg_it).get();
}
mg_ptr->insertMember(fmd); // insert in member group
MemberDefMutable *fmdm = toMemberDefMutable(fmd);
if (fmdm)
{
fmdm->setMemberGroup(mg_ptr);
}
}
}
}
}
int groupId=md->getMemberGroupId();
if (groupId!=-1)
{
auto it = Doxygen::memberGroupInfoMap.find(groupId);
if (it!=Doxygen::memberGroupInfoMap.end())
{
const auto &info = it->second;
auto mg_it = std::find_if(pMemberGroups->begin(),
pMemberGroups->end(),
[&groupId](const auto &g)
{ return g->groupId()==groupId; }
);
MemberGroup *mg_ptr = nullptr;
if (mg_it==pMemberGroups->end())
{
auto mg = std::make_unique<MemberGroup>(
context,
groupId,
info->header,
info->doc,
info->docFile,
info->docLine,
ml->container());
mg_ptr = mg.get();
pMemberGroups->push_back(std::move(mg));
}
else
{
mg_ptr = (*mg_it).get();
}
movedMembers.emplace_back(md,mg_ptr,info->m_sli);
}
}
}
// move the members to their group
for (const auto &mmi : movedMembers)
{
ml->remove(mmi.memberDef); // remove from member list
mmi.memberGroup->insertMember(mmi.memberDef->resolveAlias()); // insert in member group
mmi.memberGroup->setRefItems(mmi.sli);
MemberDefMutable *rmdm = toMemberDefMutable(mmi.memberDef);
if (rmdm)
{
rmdm->setMemberGroup(mmi.memberGroup);
}
}
}
/*! Extracts a (sub-)string from \a type starting at \a pos that
* could form a class. The index of the match is returned and the found
* class \a name and a template argument list \a templSpec. If -1 is returned
* there are no more matches.
*/
int extractClassNameFromType(const QCString &type,int &pos,QCString &name,QCString &templSpec,SrcLangExt lang)
{
static const reg::Ex re_norm(R"(\a[\w:]*)");
static const reg::Ex re_fortran(R"(\a[\w:()=]*)");
const reg::Ex *re = &re_norm;
name.clear();
templSpec.clear();
if (type.isEmpty()) return -1;
size_t typeLen=type.length();
if (typeLen>0)
{
if (lang == SrcLangExt::Fortran)
{
if (type[pos]==',') return -1;
if (!type.lower().startsWith("type"))
{
re = &re_fortran;
}
}
std::string s = type.str();
reg::Iterator it(s,*re,static_cast<int>(pos));
reg::Iterator end;
if (it!=end)
{
const auto &match = *it;
size_t i = match.position();
size_t l = match.length();
size_t ts = i+l;
size_t te = ts;
size_t tl = 0;
while (ts<typeLen && type[static_cast<uint32_t>(ts)]==' ') ts++,tl++; // skip any whitespace
if (ts<typeLen && type[static_cast<uint32_t>(ts)]=='<') // assume template instance
{
// locate end of template
te=ts+1;
int brCount=1;
while (te<typeLen && brCount!=0)
{
if (type[static_cast<uint32_t>(te)]=='<')
{
if (te<typeLen-1 && type[static_cast<uint32_t>(te)+1]=='<') te++; else brCount++;
}
if (type[static_cast<uint32_t>(te)]=='>')
{
if (te<typeLen-1 && type[static_cast<uint32_t>(te)+1]=='>') te++; else brCount--;
}
te++;
}
}
name = match.str();
if (te>ts)
{
templSpec = QCString(type).mid(ts,te-ts);
tl+=te-ts;
pos=static_cast<int>(i+l+tl);
}
else // no template part
{
pos=static_cast<int>(i+l);
}
//printf("extractClassNameFromType([in] type=%s,[out] pos=%d,[out] name=%s,[out] templ=%s)=TRUE i=%d\n",
// qPrint(type),pos,qPrint(name),qPrint(templSpec),i);
return static_cast<int>(i);
}
}
pos = static_cast<int>(typeLen);
//printf("extractClassNameFromType([in] type=%s,[out] pos=%d,[out] name=%s,[out] templ=%s)=FALSE\n",
// qPrint(type),pos,qPrint(name),qPrint(templSpec));
return -1;
}
QCString normalizeNonTemplateArgumentsInString(
const QCString &name,
const Definition *context,
const ArgumentList &formalArgs)
{
// skip until <
int p=name.find('<');
if (p==-1) return name;
p++;
QCString result = name.left(p);
std::string s = name.mid(p).str();
static const reg::Ex re(R"([\a:][\w:]*)");
reg::Iterator it(s,re);
reg::Iterator end;
size_t pi=0;
// for each identifier in the template part (e.g. B<T> -> T)
for (; it!=end ; ++it)
{
const auto &match = *it;
size_t i = match.position();
size_t l = match.length();
result += s.substr(pi,i-pi);
QCString n(match.str());
bool found=FALSE;
for (const Argument &formArg : formalArgs)
{
if (formArg.name == n)
{
found=TRUE;
break;
}
}
if (!found)
{
// try to resolve the type
SymbolResolver resolver;
const ClassDef *cd = resolver.resolveClass(context,n);
if (cd)
{
result+=cd->name();
}
else
{
result+=n;
}
}
else
{
result+=n;
}
pi=i+l;
}
result+=s.substr(pi);
//printf("normalizeNonTemplateArgumentInString(%s)=%s\n",qPrint(name),qPrint(result));
return removeRedundantWhiteSpace(result);
}
/*! Substitutes any occurrence of a formal argument from argument list
* \a formalArgs in \a name by the corresponding actual argument in
* argument list \a actualArgs. The result after substitution
* is returned as a string. The argument \a name is used to
* prevent recursive substitution.
*/
QCString substituteTemplateArgumentsInString(
const QCString &nm,
const ArgumentList &formalArgs,
const ArgumentList *actualArgs)
{
AUTO_TRACE("name={} formalArgs={} actualArgs={}",nm,argListToString(formalArgs),actualArgs ? argListToString(*actualArgs) : QCString());
if (formalArgs.empty()) return nm;
QCString result;
static const reg::Ex re(R"(\a\w*)");
std::string name = nm.str();
reg::Iterator it(name,re);
reg::Iterator end;
size_t p=0;
for (; it!=end ; ++it)
{
const auto &match = *it;
size_t i = match.position();
size_t l = match.length();
if (i>p) result += name.substr(p,i-p);
QCString n(match.str());
ArgumentList::const_iterator actIt;
if (actualArgs)
{
actIt = actualArgs->begin();
}
//printf(": name=%s\n",qPrint(name));
// if n is a template argument, then we substitute it
// for its template instance argument.
bool found=FALSE;
for (auto formIt = formalArgs.begin();
formIt!=formalArgs.end() && !found;
++formIt
)
{
Argument formArg = *formIt;
Argument actArg;
if (actualArgs && actIt!=actualArgs->end())
{
actArg = *actIt;
}
if (formArg.type.startsWith("class ") && formArg.name.isEmpty())
{
formArg.name = formArg.type.mid(6);
formArg.type = "class";
}
else if (formArg.type.startsWith("typename ") && formArg.name.isEmpty())
{
formArg.name = formArg.type.mid(9);
formArg.type = "typename";
}
else if (formArg.type.startsWith("class...")) // match 'class... name' to 'name...'
{
formArg.name += "...";
formArg.type = formArg.type.left(5)+formArg.type.mid(8);
}
else if (formArg.type.startsWith("typename...")) // match 'typename... name' to 'name...'
{
formArg.name += "...";
formArg.type = formArg.type.left(8)+formArg.type.mid(11);
}
//printf(": n=%s formArg->type='%s' formArg->name='%s' formArg->defval='%s' actArg->type='%s' actArg->name='%s' \n",
// qPrint(n),qPrint(formArg.type),qPrint(formArg.name),qPrint(formArg.defval),qPrint(actArg.type),qPrint(actArg.name));
if (formArg.type=="class" || formArg.type=="typename" || formArg.type.startsWith("template"))
{
if (formArg.name==n && actualArgs && actIt!=actualArgs->end() && !actArg.type.isEmpty()) // base class is a template argument
{
static constexpr auto hasRecursion = [](const QCString &prefix,const QCString &nameArg,const QCString &subst) -> bool
{
int ii=0;
int pp=0;
ii = subst.find('<');
//printf("prefix='%s' subst='%s'\n",qPrint(prefix.mid(prefix.length()-ii-2,ii+1)),qPrint(subst.left(ii+1)));
if (ii!=-1 && static_cast<int>(prefix.length())>=ii+2 && prefix.mid(prefix.length()-ii-2,ii+1)==subst.left(ii+1))
{
return true; // don't replace 'A< ' with 'A< A<...', see issue #10951
}
while ((ii=subst.find(nameArg,pp))!=-1)
{
bool beforeNonWord = ii==0 || !isId(subst.at(ii-1));
bool afterNonWord = subst.length()==ii+nameArg.length() || !isId(subst.at(ii+nameArg.length()));
if (beforeNonWord && afterNonWord)
{
return true; // if nameArg=='A' then subst=='A::Z' or 'S<A>' or 'Z::A' should return true, but 'AA::ZZ' or 'BAH' should not match
}
pp=ii+static_cast<int>(nameArg.length());
}
return false;
};
// replace formal argument with the actual argument of the instance
AUTO_TRACE_ADD("result={} n={} type={} hasRecursion={}",result,n,actArg.type,hasRecursion(result,n,actArg.type));
if (!hasRecursion(result,n,actArg.type))
// the scope guard is to prevent recursive lockup for
// template<class A> class C : public<A::T>,
// where A::T would become A::T::T here,
// since n==A and actArg->type==A::T
// see bug595833 for an example
//
// Also prevent recursive substitution if n is part of actArg.type, i.e.
// n='A' in argType='S< A >' would produce 'S< S< A > >'
{
if (actArg.name.isEmpty())
{
result += actArg.type;
}
else
// for case where the actual arg is something like "unsigned int"
// the "int" part is in actArg->name.
{
result += actArg.type+" "+actArg.name;
}
found=TRUE;
}
}
else if (formArg.name==n &&
(actualArgs==nullptr || actIt==actualArgs->end()) &&
!formArg.defval.isEmpty() &&
formArg.defval!=nm /* to prevent recursion */
)
{
result += substituteTemplateArgumentsInString(formArg.defval,formalArgs,actualArgs);
found=TRUE;
}
}
else if (formArg.name==n &&
(actualArgs==nullptr || actIt==actualArgs->end()) &&
!formArg.defval.isEmpty() &&
formArg.defval!=nm /* to prevent recursion */
)
{
result += substituteTemplateArgumentsInString(formArg.defval,formalArgs,actualArgs);
found=TRUE;
}
if (actualArgs && actIt!=actualArgs->end())
{
actIt++;
}
}
if (!found)
{
result += n;
}
p=i+l;
}
result+=name.substr(p);
result=result.simplifyWhiteSpace();
AUTO_TRACE_EXIT("result={}",result);
return result.stripWhiteSpace();
}
/*! Strips template specifiers from scope \a fullName, except those
* that make up specialized classes. The switch \a parentOnly
* determines whether or not a template "at the end" of a scope
* should be considered, e.g. with \a parentOnly is \c TRUE, \c A<T>::B<S> will
* try to strip `<T>` and not `<S>`, while \a parentOnly is \c FALSE will
* strip both unless `A<T>` or `B<S>` are specialized template classes.
*/
QCString stripTemplateSpecifiersFromScope(const QCString &fullName,
bool parentOnly,
QCString *pLastScopeStripped,
QCString scopeName,
bool allowArtificial)
{
//printf("stripTemplateSpecifiersFromScope(name=%s,scopeName=%s)\n",qPrint(fullName),qPrint(scopeName));
int i=fullName.find('<');
if (i==-1) return fullName;
QCString result;
int p=0;
int l=static_cast<int>(fullName.length());
while (i!=-1)
{
//printf("1:result+=%s\n",qPrint(fullName.mid(p,i-p)));
int e=i+1;
int count=1;
int round=0;
while (e<l && count>0)
{
char c=fullName.at(e++);
switch (c)
{
case '(': round++; break;
case ')': if (round>0) round--; break;
case '<': if (round==0) count++; break;
case '>': if (round==0) count--; break;
default:
break;
}
}
int si= fullName.find("::",e);
if (parentOnly && si==-1) break;
// we only do the parent scope, so we stop here if needed
result+=fullName.mid(p,i-p);
//printf(" trying %s\n",qPrint(mergeScopes(scopeName,result+fullName.mid(i,e-i))));
ClassDef *cd = getClass(mergeScopes(scopeName,result+fullName.mid(i,e-i)));
if (cd!=nullptr && (allowArtificial || !cd->isArtificial()))
{
result+=fullName.mid(i,e-i);
//printf(" 2:result+=%s\n",qPrint(fullName.mid(i,e-i-1)));
}
else if (pLastScopeStripped)
{
//printf(" last stripped scope '%s'\n",qPrint(fullName.mid(i,e-i)));
*pLastScopeStripped=fullName.mid(i,e-i);
}
p=e;
i=fullName.find('<',p);
}
result+=fullName.right(l-p);
//printf("3:result+=%s\n",qPrint(fullName.right(l-p)));
//printf("end result=%s\n",qPrint(result));
return result;
}
/*! Merges two scope parts together. The parts may (partially) overlap.
* Example1: \c A::B and \c B::C will result in \c A::B::C <br>
* Example2: \c A and \c B will be \c A::B <br>
* Example3: \c A::B and B will be \c A::B
*
* @param leftScope the left hand part of the scope.
* @param rightScope the right hand part of the scope.
* @returns the merged scope.
*/
QCString mergeScopes(const QCString &leftScope,const QCString &rightScope)
{
// case leftScope=="A" rightScope=="A::B" => result = "A::B"
if (leftScopeMatch(rightScope,leftScope)) return rightScope;
QCString result;
int i=0,p=static_cast<int>(leftScope.length());
// case leftScope=="A::B" rightScope=="B::C" => result = "A::B::C"
// case leftScope=="A::B" rightScope=="B" => result = "A::B"
bool found=FALSE;
while ((i=leftScope.findRev("::",p))>0)
{
if (leftScopeMatch(rightScope,leftScope.right(leftScope.length()-i-2)))
{
result = leftScope.left(i+2)+rightScope;
found=TRUE;
}
p=i-1;
}
if (found) return result;
// case leftScope=="A" rightScope=="B" => result = "A::B"
result=leftScope;
if (!result.isEmpty() && !rightScope.isEmpty()) result+="::";
result+=rightScope;
return result;
}
/*! Returns a fragment from scope \a s, starting at position \a p.
*
* @param s the scope name as a string.
* @param p the start position (0 is the first).
* @param l the resulting length of the fragment.
* @returns the location of the fragment, or -1 if non is found.
*/
int getScopeFragment(const QCString &s,int p,int *l)
{
int sl=static_cast<int>(s.length());
int sp=p;
int count=0;
bool done=false;
if (sp>=sl) return -1;
while (sp<sl)
{
char c=s.at(sp);
if (c==':') sp++,p++; else break;
}
while (sp<sl)
{
char c=s.at(sp);
switch (c)
{
case ':': // found next part
goto found;
case '<': // skip template specifier
count=1;sp++;
done=false;
while (sp<sl && !done)
{
// TODO: deal with << and >> operators!
c=s.at(sp++);
switch(c)
{
case '<': count++; break;
case '>': count--; if (count==0) done=true; break;
default: break;
}
}
break;
default:
sp++;
break;
}
}
found:
*l=sp-p;
//printf("getScopeFragment(%s,%d)=%s\n",qPrint(s),p,qPrint(s.mid(p,*l)));
return p;
}
//----------------------------------------------------------------------------
PageDef *addRelatedPage(const QCString &name,const QCString &ptitle,
const QCString &doc,
const QCString &fileName,
int docLine,
int startLine,
const RefItemVector &sli,
GroupDef *gd,
const TagInfo *tagInfo,
bool xref,
SrcLangExt lang
)
{
PageDef *pd=nullptr;
//printf("addRelatedPage(name=%s gd=%p)\n",qPrint(name),gd);
QCString title=ptitle.stripWhiteSpace();
bool newPage = true;
if ((pd=Doxygen::pageLinkedMap->find(name)) && !pd->isReference())
{
if (!xref && !title.isEmpty() && pd->title()!=pd->name() && pd->title()!=title)
{
warn(fileName,startLine,"multiple use of page label '%s' with different titles, (other occurrence: %s, line: %d)",
qPrint(name),qPrint(pd->docFile()),pd->getStartBodyLine());
}
if (!title.isEmpty() && pd->title()==pd->name()) // pd has no real title yet
{
pd->setTitle(title);
SectionInfo *si = SectionManager::instance().find(pd->name());
if (si)
{
si->setTitle(title);
}
}
// append documentation block to the page.
pd->setDocumentation(doc,fileName,docLine);
//printf("Adding page docs '%s' pi=%p name=%s\n",qPrint(doc),pd,name);
// append (x)refitems to the page.
pd->setRefItems(sli);
newPage = false;
}
if (newPage) // new page
{
QCString baseName=name;
if (baseName.endsWith(".tex"))
baseName=baseName.left(baseName.length()-4);
else if (baseName.right(Doxygen::htmlFileExtension.length())==Doxygen::htmlFileExtension)
baseName=baseName.left(baseName.length()-Doxygen::htmlFileExtension.length());
//printf("Appending page '%s'\n",qPrint(baseName));
if (pd) // replace existing page
{
pd->setDocumentation(doc,fileName,docLine);
pd->setFileName(::convertNameToFile(baseName,FALSE,TRUE));
pd->setShowLineNo(FALSE);
pd->setNestingLevel(0);
pd->setPageScope(nullptr);
pd->setTitle(title);
pd->setReference(QCString());
}
else // newPage
{
pd = Doxygen::pageLinkedMap->add(baseName,
createPageDef(fileName,docLine,baseName,doc,title));
}
pd->setBodySegment(startLine,startLine,-1);
pd->setRefItems(sli);
pd->setLanguage(lang);
if (tagInfo)
{
pd->setReference(tagInfo->tagName);
pd->setFileName(tagInfo->fileName);
}
if (gd) gd->addPage(pd);
if (pd->hasTitle())
{
//outputList->writeTitle(pi->name,pi->title);
// a page name is a label as well!
QCString file;
QCString orgFile;
int line = -1;
if (gd)
{
file=gd->getOutputFileBase();
orgFile=gd->getOutputFileBase();
}
else
{
file=pd->getOutputFileBase();
orgFile=pd->docFile();
line = pd->getStartBodyLine();
}
const SectionInfo *si = SectionManager::instance().find(pd->name());
if (si)
{
if (!si->ref().isEmpty()) // we are from a tag file
{
SectionManager::instance().replace(pd->name(),
file,-1,pd->title(),SectionType::Page,0,pd->getReference());
}
else if (si->lineNr() != -1)
{
warn(orgFile,line,"multiple use of section label '%s', (first occurrence: %s, line %d)",qPrint(pd->name()),qPrint(si->fileName()),si->lineNr());
}
else
{
warn(orgFile,line,"multiple use of section label '%s', (first occurrence: %s)",qPrint(pd->name()),qPrint(si->fileName()));
}
}
else
{
SectionManager::instance().add(pd->name(),
file,-1,pd->title(),SectionType::Page,0,pd->getReference());
//printf("si->label='%s' si->definition=%s si->fileName='%s'\n",
// qPrint(si->label),si->definition?si->definition->name().data():"<none>",
// qPrint(si->fileName));
//printf(" SectionInfo: sec=%p sec->fileName=%s\n",si,qPrint(si->fileName));
//printf("Adding section key=%s si->fileName=%s\n",qPrint(pageName),qPrint(si->fileName));
}
}
}
return pd;
}
//----------------------------------------------------------------------------
void addRefItem(const RefItemVector &sli,
const QCString &key, const QCString &prefix, const QCString &name,
const QCString &title, const QCString &args, const Definition *scope)
{
//printf("addRefItem(sli=%d,key=%s,prefix=%s,name=%s,title=%s,args=%s)\n",(int)sli.size(),key,prefix,name,title,args);
if (!key.isEmpty() && key[0]!='@') // check for @ to skip anonymous stuff (see bug427012)
{
for (RefItem *item : sli)
{
item->setPrefix(prefix);
item->setScope(scope);
item->setName(name);
item->setTitle(title);
item->setArgs(args);
item->setGroup(key);
}
}
}
static ModuleDef *findModuleDef(const Definition *d)
{
ModuleDef *mod = nullptr;
if (d->definitionType()==Definition::TypeFile)
{
const FileDef *fd = toFileDef(d);
if (fd) mod = fd->getModuleDef();
}
else if (d->definitionType()==Definition::TypeClass)
{
const ClassDef *cd = toClassDef(d);
if (cd)
{
const FileDef *fd = cd->getFileDef();
if (fd) mod = fd->getModuleDef();
}
}
else if (d->definitionType()==Definition::TypeConcept)
{
const ConceptDef *cd = toConceptDef(d);
if (cd)
{
const FileDef *fd = cd->getFileDef();
if (fd) mod = fd->getModuleDef();
}
}
return mod;
}
static bool recursivelyAddGroupListToTitle(OutputList &ol,const Definition *d,bool root)
{
ModuleDef *mod = root ? findModuleDef(d) : nullptr;
if (!d->partOfGroups().empty() || mod!=nullptr) // write list of group to which this definition belongs
{
if (root)
{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.writeString("<div class=\"ingroups\">");
}
bool first=true;
for (const auto &gd : d->partOfGroups())
{
if (!first) { ol.writeString(" | "); } else first=false;
if (recursivelyAddGroupListToTitle(ol, gd, FALSE))
{
ol.writeString(" » ");
}
ol.writeObjectLink(gd->getReference(),gd->getOutputFileBase(),QCString(),gd->groupTitle());
}
if (root)
{
// add module as a group to the file as well
if (mod)
{
if (!first) { ol.writeString(" | "); } else first=false;
ol.writeString(theTranslator->trModule(false,true)+" ");
ol.writeObjectLink(mod->getReference(),mod->getOutputFileBase(),QCString(),
mod->displayName());
}
ol.writeString("</div>");
ol.popGeneratorState();
}
return true;
}
return false;
}
void addGroupListToTitle(OutputList &ol,const Definition *d)
{
recursivelyAddGroupListToTitle(ol,d,TRUE);
}
bool checkExtension(const QCString &fName, const QCString &ext)
{
return fName.right(ext.length())==ext;
}
void addHtmlExtensionIfMissing(QCString &fName)
{
if (fName.isEmpty()) return;
int i_fs = fName.findRev('/');
int i_bs = fName.findRev('\\');
int i = fName.find('.',std::max({ i_fs, i_bs ,0})); // search for . after path part
if (i==-1)
{
fName+=Doxygen::htmlFileExtension;
}
}
QCString stripExtensionGeneral(const QCString &fName, const QCString &ext)
{
QCString result=fName;
if (result.right(ext.length())==ext)
{
result=result.left(result.length()-ext.length());
}
return result;
}
QCString stripExtension(const QCString &fName)
{
return stripExtensionGeneral(fName, Doxygen::htmlFileExtension);
}
#if 0
void replaceNamespaceAliases(QCString &scope,size_t i)
{
printf("replaceNamespaceAliases(%s,%zu)\n",qPrint(scope),i);
while (i>0)
{
QCString ns = scope.left(i);
if (!ns.isEmpty())
{
auto it = Doxygen::namespaceAliasMap.find(ns.str());
if (it!=Doxygen::namespaceAliasMap.end())
{
scope=QCString(it->second)+scope.right(scope.length()-i);
i=it->second.length();
}
}
if (i>0 && ns==scope.left(i)) break;
}
printf("result=%s\n",qPrint(scope));
}
#endif
QCString stripPath(const QCString &s)
{
QCString result=s;
int i=result.findRev('/');
if (i!=-1)
{
result=result.mid(i+1);
}
i=result.findRev('\\');
if (i!=-1)
{
result=result.mid(i+1);
}
return result;
}
/** returns \c TRUE iff string \a s contains word \a w */
bool containsWord(const QCString &str,const char *word)
{
if (str.isEmpty() || word==nullptr) return false;
static const reg::Ex re(R"(\a+)");
std::string s = str.str();
for (reg::Iterator it(s,re) ; it!=reg::Iterator() ; ++it)
{
if (it->str()==word) return true;
}
return false;
}
/** removes occurrences of whole \a word from \a sentence,
* while keeps internal spaces and reducing multiple sequences of spaces.
* Example: sentence=` cat+ catfish cat cat concat cat`, word=`cat` returns: `+ catfish concat`
*/
bool findAndRemoveWord(QCString &sentence,const char *word)
{
static reg::Ex re(R"(\s*(\<\a+\>)\s*)");
std::string s = sentence.str();
reg::Iterator it(s,re);
reg::Iterator end;
std::string result;
bool found=false;
size_t p=0;
for ( ; it!=end ; ++it)
{
const auto match = *it;
std::string part = match[1].str();
if (part!=word)
{
size_t i = match.position();
size_t l = match.length();
result+=s.substr(p,i-p);
result+=match.str();
p=i+l;
}
else
{
found=true;
size_t i = match[1].position();
size_t l = match[1].length();
result+=s.substr(p,i-p);
p=i+l;
}
}
result+=s.substr(p);
sentence = QCString(result).simplifyWhiteSpace();
return found;
}
/** Special version of QCString::stripWhiteSpace() that only strips
* completely blank lines.
* @param s the string to be stripped
* @param docLine the line number corresponding to the start of the
* string. This will be adjusted based on the number of lines stripped
* from the start.
* @returns The stripped string.
*/
QCString stripLeadingAndTrailingEmptyLines(const QCString &s,int &docLine)
{
if (s.isEmpty()) return QCString();
const char *p = s.data();
// search for leading empty lines
int i=0,li=-1,l=static_cast<int>(s.length());
char c = 0;
while ((c=*p))
{
if (c==' ' || c=='\t' || c=='\r') i++,p++;
else if (c=='\\' && qstrncmp(p,"\\ilinebr",8)==0) i+=8,li=i,p+=8;
else if (c=='\n') i++,li=i,docLine++,p++;
else break;
}
// search for trailing empty lines
int b=l-1,bi=-1;
p=s.data()+b;
while (b>=0)
{
c=*p;
if (c==' ' || c=='\t' || c=='\r') b--,p--;
else if (c=='r' && b>=7 && qstrncmp(p-7,"\\ilinebr",8)==0) bi=b-7,b-=8,p-=8;
else if (c=='>' && b>=11 && qstrncmp(p-11,"\\ilinebr<br>",12)==0) bi=b-11,b-=12,p-=12;
else if (c=='\n') bi=b,b--,p--;
else break;
}
// return whole string if no leading or trailing lines where found
if (li==-1 && bi==-1) return s;
// return substring
if (bi==-1) bi=l;
if (li==-1) li=0;
if (bi<=li) return QCString(); // only empty lines
//printf("docLine='%s' len=%d li=%d bi=%d\n",qPrint(s),s.length(),li,bi);
return s.mid(li,bi-li);
}
//--------------------------------------------------------------------------
static std::unordered_map<std::string,SrcLangExt> g_extLookup;
struct Lang2ExtMap
{
const char *langName;
const char *parserName;
SrcLangExt parserId;
const char *defExt;
};
static std::vector<Lang2ExtMap> g_lang2extMap =
{
// language parser parser option
{ "idl", "c", SrcLangExt::IDL, ".idl" },
{ "java", "c", SrcLangExt::Java, ".java"},
{ "javascript", "c", SrcLangExt::JS, ".js" },
{ "csharp", "c", SrcLangExt::CSharp, ".cs" },
{ "d", "c", SrcLangExt::D, ".d" },
{ "php", "c", SrcLangExt::PHP, ".php" },
{ "objective-c", "c", SrcLangExt::ObjC, ".m" },
{ "c", "c", SrcLangExt::Cpp, ".c" },
{ "c++", "c", SrcLangExt::Cpp, ".cpp" },
{ "slice", "c", SrcLangExt::Slice, ".ice" },
{ "python", "python", SrcLangExt::Python, ".py" },
{ "fortran", "fortran", SrcLangExt::Fortran, ".f" },
{ "fortranfree", "fortranfree", SrcLangExt::Fortran, ".f90" },
{ "fortranfixed", "fortranfixed", SrcLangExt::Fortran, ".f" },
{ "vhdl", "vhdl", SrcLangExt::VHDL, ".vhdl"},
{ "xml", "xml", SrcLangExt::XML, ".xml" },
{ "sql", "sql", SrcLangExt::SQL, ".sql" },
{ "md", "md", SrcLangExt::Markdown, ".md" },
{ "lex", "lex", SrcLangExt::Lex, ".l" },
};
bool updateLanguageMapping(const QCString &extension,const QCString &language)
{
QCString langName = language.lower();
auto it1 = std::find_if(g_lang2extMap.begin(),g_lang2extMap.end(),
[&langName](const auto &info) { return info.langName==langName; });
if (it1 == g_lang2extMap.end()) return false;
// found the language
SrcLangExt parserId = it1->parserId;
QCString extName = extension.lower();
if (extName.isEmpty()) return FALSE;
if (extName.at(0)!='.') extName.prepend(".");
auto it2 = g_extLookup.find(extName.str());
if (it2!=g_extLookup.end())
{
g_extLookup.erase(it2); // language was already register for this ext
}
//printf("registering extension %s\n",qPrint(extName));
g_extLookup.emplace(extName.str(),parserId);
if (!Doxygen::parserManager->registerExtension(extName,it1->parserName))
{
err("Failed to assign extension %s to parser %s for language %s\n",
extName.data(),it1->parserName,qPrint(language));
}
else
{
//msg("Registered extension %s to language parser %s...\n",
// extName.data(),qPrint(language));
}
return TRUE;
}
void initDefaultExtensionMapping()
{
// NOTE: when adding an extension, also add the extension in config.xml
// extension parser id
updateLanguageMapping(".dox", "c");
updateLanguageMapping(".txt", "c"); // see bug 760836
updateLanguageMapping(".doc", "c");
updateLanguageMapping(".c", "c");
updateLanguageMapping(".C", "c");
updateLanguageMapping(".cc", "c");
updateLanguageMapping(".CC", "c");
updateLanguageMapping(".cxx", "c");
updateLanguageMapping(".cpp", "c");
updateLanguageMapping(".c++", "c");
updateLanguageMapping(".cxxm", "c"); // C++20 modules
updateLanguageMapping(".cppm", "c"); // C++20 modules
updateLanguageMapping(".ccm", "c"); // C++20 modules
updateLanguageMapping(".c++m", "c"); // C++20 modules
updateLanguageMapping(".ii", "c");
updateLanguageMapping(".ixx", "c");
updateLanguageMapping(".ipp", "c");
updateLanguageMapping(".i++", "c");
updateLanguageMapping(".inl", "c");
updateLanguageMapping(".h", "c");
updateLanguageMapping(".H", "c");
updateLanguageMapping(".hh", "c");
updateLanguageMapping(".HH", "c");
updateLanguageMapping(".hxx", "c");
updateLanguageMapping(".hpp", "c");
updateLanguageMapping(".h++", "c");
updateLanguageMapping(".idl", "idl");
updateLanguageMapping(".ddl", "idl");
updateLanguageMapping(".odl", "idl");
updateLanguageMapping(".java", "java");
//updateLanguageMapping(".as", "javascript"); // not officially supported
//updateLanguageMapping(".js", "javascript"); // not officially supported
updateLanguageMapping(".cs", "csharp");
updateLanguageMapping(".d", "d");
updateLanguageMapping(".php", "php");
updateLanguageMapping(".php4", "php");
updateLanguageMapping(".php5", "php");
updateLanguageMapping(".inc", "php");
updateLanguageMapping(".phtml", "php");
updateLanguageMapping(".m", "objective-c");
updateLanguageMapping(".M", "objective-c");
updateLanguageMapping(".mm", "c"); // see bug746361
updateLanguageMapping(".py", "python");
updateLanguageMapping(".pyw", "python");
updateLanguageMapping(".f", "fortran");
updateLanguageMapping(".for", "fortran");
updateLanguageMapping(".f90", "fortran");
updateLanguageMapping(".f95", "fortran");
updateLanguageMapping(".f03", "fortran");
updateLanguageMapping(".f08", "fortran");
updateLanguageMapping(".f18", "fortran");
updateLanguageMapping(".vhd", "vhdl");
updateLanguageMapping(".vhdl", "vhdl");
updateLanguageMapping(".ucf", "vhdl");
updateLanguageMapping(".qsf", "vhdl");
updateLanguageMapping(".md", "md");
updateLanguageMapping(".markdown", "md");
updateLanguageMapping(".ice", "slice");
updateLanguageMapping(".l", "lex");
updateLanguageMapping(".doxygen_lex_c", "c"); // this is a placeholder so we can map initializations
// in the lex scanning to cpp
}
void addCodeOnlyMappings()
{
updateLanguageMapping(".xml", "xml");
updateLanguageMapping(".sql", "sql");
}
SrcLangExt getLanguageFromFileName(const QCString& fileName, SrcLangExt defLang)
{
FileInfo fi(fileName.str());
// we need only the part after the last ".", newer implementations of FileInfo have 'suffix()' for this.
QCString extName = QCString(fi.extension(FALSE)).lower();
if (extName.isEmpty()) extName=".no_extension";
if (extName.at(0)!='.') extName.prepend(".");
auto it = g_extLookup.find(extName.str());
if (it!=g_extLookup.end()) // listed extension
{
//printf("getLanguageFromFileName(%s)=%x\n",qPrint(fi.extension()),*pVal);
return it->second;
}
//printf("getLanguageFromFileName(%s) not found!\n",qPrint(fileName));
return defLang; // not listed => assume C-ish language.
}
/// Routine to handle the language attribute of the `\code` command
SrcLangExt getLanguageFromCodeLang(QCString &fileName)
{
// try the extension
auto lang = getLanguageFromFileName(fileName, SrcLangExt::Unknown);
if (lang == SrcLangExt::Unknown)
{
// try the language names
QCString langName = fileName.lower();
if (langName.at(0)=='.') langName = langName.mid(1);
auto it = std::find_if(g_lang2extMap.begin(),g_lang2extMap.end(),
[&langName](const auto &info) { return info.langName==langName; });
if (it != g_lang2extMap.end())
{
lang = it->parserId;
fileName = it->defExt;
}
else // default to C++
{
return SrcLangExt::Cpp;
}
}
return lang;
}
QCString getFileNameExtension(const QCString &fn)
{
if (fn.isEmpty()) return "";
int lastDot = fn.findRev('.');
if (lastDot!=-1) return fn.mid(lastDot);
return "";
}
//--------------------------------------------------------------------------
static MemberDef *getMemberFromSymbol(const Definition *scope,const FileDef *fileScope,
const QCString &n)
{
if (scope==nullptr ||
(scope->definitionType()!=Definition::TypeClass &&
scope->definitionType()!=Definition::TypeNamespace
)
)
{
scope=Doxygen::globalScope;
}
QCString name = n;
if (name.isEmpty())
return nullptr; // no name was given
auto &range = Doxygen::symbolMap->find(name);
if (range.empty())
return nullptr; // could not find any matching symbols
// mostly copied from getResolvedClassRec()
QCString explicitScopePart;
int qualifierIndex = computeQualifiedIndex(name);
if (qualifierIndex!=-1)
{
explicitScopePart = name.left(qualifierIndex);
replaceNamespaceAliases(explicitScopePart);
name = name.mid(qualifierIndex+2);
}
//printf("explicitScopePart=%s\n",qPrint(explicitScopePart));
int minDistance = 10000;
MemberDef *bestMatch = nullptr;
for (Definition *d : range)
{
if (d->definitionType()==Definition::TypeMember)
{
SymbolResolver resolver(fileScope);
int distance = resolver.isAccessibleFromWithExpScope(scope,d,explicitScopePart);
if (distance!=-1 && distance<minDistance)
{
minDistance = distance;
bestMatch = toMemberDef(d);
//printf("new best match %s distance=%d\n",qPrint(bestMatch->qualifiedName()),distance);
}
}
}
return bestMatch;
}
/*! Returns true iff the given name string appears to be a typedef in scope. */
bool checkIfTypedef(const Definition *scope,const FileDef *fileScope,const QCString &n)
{
MemberDef *bestMatch = getMemberFromSymbol(scope,fileScope,n);
if (bestMatch && bestMatch->isTypedef())
return TRUE; // closest matching symbol is a typedef
else
return FALSE;
}
static int nextUTF8CharPosition(const QCString &utf8Str,uint32_t len,uint32_t startPos)
{
if (startPos>=len) return len;
uint8_t c = static_cast<uint8_t>(utf8Str[startPos]);
int bytes=getUTF8CharNumBytes(c);
if (c=='&') // skip over character entities
{
bytes=1;
int (*matcher)(int) = nullptr;
c = static_cast<uint8_t>(utf8Str[startPos+bytes]);
if (c=='#') // numerical entity?
{
bytes++;
c = static_cast<uint8_t>(utf8Str[startPos+bytes]);
if (c=='x') // hexadecimal entity?
{
bytes++;
matcher = std::isxdigit;
}
else // decimal entity
{
matcher = std::isdigit;
}
}
else if (std::isalnum(c)) // named entity?
{
bytes++;
matcher = std::isalnum;
}
if (matcher)
{
while ((c = static_cast<uint8_t>(utf8Str[startPos+bytes]))!=0 && matcher(c))
{
bytes++;
}
}
if (c!=';')
{
bytes=1; // not a valid entity, reset bytes counter
}
}
return startPos+bytes;
}
QCString parseCommentAsText(const Definition *scope,const MemberDef *md,
const QCString &doc,const QCString &fileName,int lineNr)
{
if (doc.isEmpty()) return "";
//printf("parseCommentAsText(%s)\n",qPrint(doc));
TextStream t;
auto parser { createDocParser() };
auto ast { validatingParseDoc(*parser.get(),
fileName,lineNr,
scope,md,doc,FALSE,FALSE,
QCString(),FALSE,FALSE,Config_getBool(MARKDOWN_SUPPORT)) };
auto astImpl = dynamic_cast<const DocNodeAST*>(ast.get());
if (astImpl)
{
TextDocVisitor visitor(t);
std::visit(visitor,astImpl->root);
}
QCString result = convertCharEntitiesToUTF8(t.str().c_str()).stripWhiteSpace();
int i=0;
int charCnt=0;
int l=static_cast<int>(result.length());
while ((i=nextUTF8CharPosition(result,l,i))<l)
{
charCnt++;
if (charCnt>=80) break;
}
if (charCnt>=80) // try to truncate the string
{
while ((i=nextUTF8CharPosition(result,l,i))<l && charCnt<100)
{
charCnt++;
if (result.at(i)==',' ||
result.at(i)=='.' ||
result.at(i)=='!' ||
result.at(i)=='?' ||
result.at(i)=='}') // good for UTF-16 characters and } otherwise also a good point to stop the string
{
i++; // we want to be "behind" last inspected character
break;
}
}
}
if ( i < l) result=result.left(i)+"...";
return result.data();
}
//--------------------------------------------------------------------------------------
void writeTypeConstraints(OutputList &ol,const Definition *d,const ArgumentList &al)
{
if (al.empty()) return;
ol.startConstraintList(theTranslator->trTypeConstraints());
for (const Argument &a : al)
{
ol.startConstraintParam();
ol.parseText(a.name);
ol.endConstraintParam();
ol.startConstraintType();
linkifyText(TextGeneratorOLImpl(ol),d,nullptr,nullptr,a.type);
ol.endConstraintType();
ol.startConstraintDocs();
ol.generateDoc(d->docFile(),d->docLine(),d,nullptr,a.docs,TRUE,FALSE,
QCString(),FALSE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
ol.endConstraintDocs();
}
ol.endConstraintList();
}
//----------------------------------------------------------------------------
void stackTrace()
{
#ifdef TRACINGSUPPORT
void *backtraceFrames[128];
int frameCount = backtrace(backtraceFrames, 128);
const size_t cmdLen = 40960;
static char cmd[cmdLen];
char *p = cmd;
p += qsnprintf(p,cmdLen,"/usr/bin/atos -p %d ", (int)getpid());
for (int x = 0; x < frameCount; x++)
{
p += qsnprintf(p,cmdLen,"%p ", backtraceFrames[x]);
}
fprintf(stderr,"========== STACKTRACE START ==============\n");
if (FILE *fp = Portable::popen(cmd, "r"))
{
char resBuf[512];
while (size_t len = fread(resBuf, 1, sizeof(resBuf), fp))
{
fwrite(resBuf, 1, len, stderr);
}
Portable::pclose(fp);
}
fprintf(stderr,"============ STACKTRACE END ==============\n");
//fprintf(stderr,"%s\n", frameStrings[x]);
#endif
}
static void transcodeCharacterBuffer(const QCString &fileName,std::string &contents,
const QCString &inputEncoding,const QCString &outputEncoding)
{
if (inputEncoding.isEmpty() || outputEncoding.isEmpty()) return; // no encoding specified
if (qstricmp(inputEncoding,outputEncoding)==0) return; // input encoding same as output encoding
void *cd = portable_iconv_open(outputEncoding.data(),inputEncoding.data());
if (cd==reinterpret_cast<void *>(-1))
{
term("unsupported character conversion: '%s'->'%s': %s\n"
"Check the INPUT_ENCODING setting in the config file!\n",
qPrint(inputEncoding),qPrint(outputEncoding),strerror(errno));
}
size_t iLeft = contents.size();
const char *srcPtr = contents.data();
size_t tmpBufSize = contents.size()*4+1;
size_t oLeft = tmpBufSize;
std::string tmpBuf;
tmpBuf.resize(tmpBufSize);
char *dstPtr = tmpBuf.data();
size_t newSize=0;
if (!portable_iconv(cd, &srcPtr, &iLeft, &dstPtr, &oLeft))
{
newSize = tmpBufSize-oLeft;
tmpBuf.resize(newSize);
std::swap(contents,tmpBuf);
//printf("iconv: input size=%d output size=%d\n[%s]\n",size,newSize,qPrint(srcBuf));
}
else
{
term("%s: failed to translate characters from %s to %s: check INPUT_ENCODING\n",
qPrint(fileName),qPrint(inputEncoding),qPrint(outputEncoding));
}
portable_iconv_close(cd);
}
//! read a file name \a fileName and optionally filter and transcode it
bool readInputFile(const QCString &fileName,std::string &contents,bool filter,bool isSourceCode)
{
// try to open file
FileInfo fi(fileName.str());
if (!fi.exists()) return FALSE;
QCString filterName = getFileFilter(fileName,isSourceCode);
if (filterName.isEmpty() || !filter)
{
std::ifstream f = Portable::openInputStream(fileName,true);
if (!f.is_open())
{
err("could not open file %s\n",qPrint(fileName));
return FALSE;
}
// read the file
auto fileSize = fi.size();
contents.resize(fileSize);
f.read(contents.data(),fileSize);
if (f.fail())
{
err("problems while reading file %s\n",qPrint(fileName));
return FALSE;
}
}
else
{
QCString cmd=filterName+" \""+fileName+"\"";
Debug::print(Debug::ExtCmd,0,"Executing popen(`%s`)\n",qPrint(cmd));
FILE *f=Portable::popen(cmd,"r");
if (!f)
{
err("could not execute filter %s\n",qPrint(filterName));
return FALSE;
}
const int bufSize=4096;
char buf[bufSize];
int numRead = 0;
while ((numRead=static_cast<int>(fread(buf,1,bufSize,f)))>0)
{
//printf(">>>>>>>>Reading %d bytes\n",numRead);
contents.append(buf,numRead);
}
Portable::pclose(f);
Debug::print(Debug::FilterOutput, 0, "Filter output\n");
Debug::print(Debug::FilterOutput,0,"-------------\n%s\n-------------\n",qPrint(contents));
}
if (contents.size()>=2 &&
static_cast<uint8_t>(contents[0])==0xFF &&
static_cast<uint8_t>(contents[1])==0xFE // Little endian BOM
) // UCS-2LE encoded file
{
transcodeCharacterBuffer(fileName,contents,"UCS-2LE","UTF-8");
}
else if (contents.size()>=2 &&
static_cast<uint8_t>(contents[0])==0xFE &&
static_cast<uint8_t>(contents[1])==0xFF // big endian BOM
) // UCS-2BE encoded file
{
transcodeCharacterBuffer(fileName,contents,"UCS-2BE","UTF-8");
}
else if (contents.size()>=3 &&
static_cast<uint8_t>(contents[0])==0xEF &&
static_cast<uint8_t>(contents[1])==0xBB &&
static_cast<uint8_t>(contents[2])==0xBF
) // UTF-8 encoded file
{
contents.erase(0,3); // remove UTF-8 BOM: no translation needed
}
else // transcode according to the INPUT_ENCODING setting
{
// do character transcoding if needed.
transcodeCharacterBuffer(fileName,contents,getEncoding(fi),"UTF-8");
}
filterCRLF(contents);
return true;
}
// Replace %word by word in title
QCString filterTitle(const QCString &title)
{
std::string tf;
std::string t = title.str();
static const reg::Ex re(R"(%[a-z_A-Z]+)");
reg::Iterator it(t,re);
reg::Iterator end;
size_t p = 0;
for (; it!=end ; ++it)
{
const auto &match = *it;
size_t i = match.position();
size_t l = match.length();
if (i>p) tf+=t.substr(p,i-p);
tf+=match.str().substr(1); // skip %
p=i+l;
}
tf+=t.substr(p);
return QCString(tf);
}
//---------------------------------------------------------------------------------------------------
template<class PatternList, class PatternElem, typename PatternGet = QCString(*)(const PatternElem &)>
bool genericPatternMatch(const FileInfo &fi,
const PatternList &patList,
PatternElem &elem,
PatternGet getter)
{
bool caseSenseNames = getCaseSenseNames();
bool found = FALSE;
// For platforms where the file system is non case sensitive overrule the setting
if (!Portable::fileSystemIsCaseSensitive())
{
caseSenseNames = FALSE;
}
if (!patList.empty())
{
std::string fn = fi.fileName();
std::string fp = fi.filePath();
std::string afp= fi.absFilePath();
for (const auto &li : patList)
{
std::string pattern = getter(li).str();
if (!pattern.empty())
{
size_t i=pattern.find('=');
if (i!=std::string::npos) pattern=pattern.substr(0,i); // strip of the extension specific filter name
if (!caseSenseNames)
{
pattern = QCString(pattern).lower().str();
fn = QCString(fn).lower().str();
fp = QCString(fp).lower().str();
afp = QCString(afp).lower().str();
}
reg::Ex re(pattern,reg::Ex::Mode::Wildcard);
found = re.isValid() && (reg::match(fn,re) ||
(fn!=fp && reg::match(fp,re)) ||
(fn!=afp && fp!=afp && reg::match(afp,re)));
if (found)
{
elem = li;
break;
}
//printf("Matching '%s' against pattern '%s' found=%d\n",
// qPrint(fi->fileName()),qPrint(pattern),found);
}
}
}
return found;
}
//----------------------------------------------------------------------------
// returns TRUE if the name of the file represented by 'fi' matches
// one of the file patterns in the 'patList' list.
bool patternMatch(const FileInfo &fi,const StringVector &patList)
{
std::string elem;
auto getter = [](std::string s) { return QCString(s); };
return genericPatternMatch(fi,patList,elem,getter);
}
QCString getEncoding(const FileInfo &fi)
{
InputFileEncoding elem;
auto getter = [](const InputFileEncoding &e) { return e.pattern; };
if (genericPatternMatch(fi,Doxygen::inputFileEncodingList,elem,getter)) // check for file specific encoding
{
return elem.encoding;
}
else // fall back to default encoding
{
return Config_getString(INPUT_ENCODING);
}
}
QCString externalLinkTarget(const bool parent)
{
bool extLinksInWindow = Config_getBool(EXT_LINKS_IN_WINDOW);
if (extLinksInWindow)
return "target=\"_blank\" ";
else if (parent)
return "target=\"_parent\" ";
else
return "";
}
QCString createHtmlUrl(const QCString &relPath,
const QCString &ref,
bool href,
bool isLocalFile,
const QCString &targetFileName,
const QCString &anchor)
{
QCString url;
if (!ref.isEmpty())
{
url = externalRef(relPath,ref,href);
}
if (!targetFileName.isEmpty())
{
QCString fn = targetFileName;
if (ref.isEmpty())
{
if (!anchor.isEmpty() && isLocalFile)
{
fn=""; // omit file name for local links
}
else
{
url = relPath;
}
}
url+=fn;
}
if (!anchor.isEmpty()) url+="#"+anchor;
//printf("createHtmlUrl(relPath=%s,local=%d,target=%s,anchor=%s)=%s\n",qPrint(relPath),isLocalFile,qPrint(targetFileName),qPrint(anchor),qPrint(url));
return url;
}
QCString externalRef(const QCString &relPath,const QCString &ref,bool href)
{
QCString result;
if (!ref.isEmpty())
{
auto it = Doxygen::tagDestinationMap.find(ref.str());
if (it!=Doxygen::tagDestinationMap.end())
{
result = it->second;
size_t l = result.length();
if (!relPath.isEmpty() && l>0 && result.at(0)=='.')
{ // relative path -> prepend relPath.
result.prepend(relPath);
l+=relPath.length();
}
if (l>0 && result.at(l-1)!='/') result+='/';
if (!href) result.append("\" ");
}
}
else
{
result = relPath;
}
return result;
}
/** Writes the intensity only bitmap represented by \a data as an image to
* directory \a dir using the colors defined by HTML_COLORSTYLE_*.
*/
void writeColoredImgData(const QCString &dir,ColoredImgDataItem data[])
{
int hue = Config_getInt(HTML_COLORSTYLE_HUE);
int sat = Config_getInt(HTML_COLORSTYLE_SAT);
int gamma = Config_getInt(HTML_COLORSTYLE_GAMMA);
while (data->name)
{
QCString fileName = dir+"/"+data->name;
ColoredImage img(data->width,data->height,data->content,data->alpha,
sat,hue,gamma);
if (!img.save(fileName))
{
fprintf(stderr,"Warning: Cannot open file %s for writing\n",data->name);
}
Doxygen::indexList->addImageFile(data->name);
data++;
}
}
/** Replaces any markers of the form \#\#AA in input string \a str
* by new markers of the form \#AABBCC, where \#AABBCC represents a
* valid color, based on the intensity represented by hex number AA
* and the current HTML_COLORSTYLE_* settings.
*/
QCString replaceColorMarkers(const QCString &str)
{
if (str.isEmpty()) return QCString();
std::string result;
std::string s=str.str();
static const reg::Ex re(R"(##[0-9A-Fa-f][0-9A-Fa-f])");
reg::Iterator it(s,re);
reg::Iterator end;
int hue = Config_getInt(HTML_COLORSTYLE_HUE);
int sat = Config_getInt(HTML_COLORSTYLE_SAT);
int gamma = Config_getInt(HTML_COLORSTYLE_GAMMA);
size_t sl=s.length();
size_t p=0;
for (; it!=end ; ++it)
{
const auto &match = *it;
size_t i = match.position();
size_t l = match.length();
if (i>p) result+=s.substr(p,i-p);
std::string lumStr = match.str().substr(2);
#define HEXTONUM(x) (((x)>='0' && (x)<='9') ? ((x)-'0') : \
((x)>='a' && (x)<='f') ? ((x)-'a'+10) : \
((x)>='A' && (x)<='F') ? ((x)-'A'+10) : 0)
double r = 0,g = 0,b = 0;
int level = HEXTONUM(lumStr[0])*16+HEXTONUM(lumStr[1]);
ColoredImage::hsl2rgb(hue/360.0,sat/255.0,
pow(level/255.0,gamma/100.0),&r,&g,&b);
int red = static_cast<int>(r*255.0);
int green = static_cast<int>(g*255.0);
int blue = static_cast<int>(b*255.0);
char colStr[8];
colStr[0]='#';
colStr[1]=hex[red>>4];
colStr[2]=hex[red&0xf];
colStr[3]=hex[green>>4];
colStr[4]=hex[green&0xf];
colStr[5]=hex[blue>>4];
colStr[6]=hex[blue&0xf];
colStr[7]=0;
//printf("replacing %s->%s (level=%d)\n",qPrint(lumStr),colStr,level);
result+=colStr;
p=i+l;
}
if (p<sl) result+=s.substr(p);
return QCString(result);
}
/** Copies the contents of file with name \a src to the newly created
* file with name \a dest. Returns TRUE if successful.
*/
bool copyFile(const QCString &src,const QCString &dest)
{
if (!Dir().copy(src.str(),dest.str()))
{
err("could not copy file %s to %s\n",qPrint(src),qPrint(dest));
return false;
}
return true;
}
/** Returns the line number of the line following the line with the marker.
* \sa routine extractBlock
*/
int lineBlock(const QCString &text,const QCString &marker)
{
int result = 1;
// find the character positions of the first marker
int m1 = text.find(marker);
if (m1==-1) return result;
// find start line positions for the markers
bool found=false;
int p=0, i=0;
while (!found && (i=text.find('\n',p))!=-1)
{
found = (p<=m1 && m1<i); // found the line with the start marker
p=i+1;
result++;
}
return result;
}
/** Returns a string representation of \a lang. */
QCString langToString(SrcLangExt lang)
{
switch(lang)
{
case SrcLangExt::Unknown: return "Unknown";
case SrcLangExt::IDL: return "IDL";
case SrcLangExt::Java: return "Java";
case SrcLangExt::CSharp: return "C#";
case SrcLangExt::D: return "D";
case SrcLangExt::PHP: return "PHP";
case SrcLangExt::ObjC: return "Objective-C";
case SrcLangExt::Cpp: return "C++";
case SrcLangExt::JS: return "JavaScript";
case SrcLangExt::Python: return "Python";
case SrcLangExt::Fortran: return "Fortran";
case SrcLangExt::VHDL: return "VHDL";
case SrcLangExt::XML: return "XML";
case SrcLangExt::SQL: return "SQL";
case SrcLangExt::Markdown: return "Markdown";
case SrcLangExt::Slice: return "Slice";
case SrcLangExt::Lex: return "Lex";
}
return "Unknown";
}
/** Returns the scope separator to use given the programming language \a lang */
QCString getLanguageSpecificSeparator(SrcLangExt lang,bool classScope)
{
if (lang==SrcLangExt::Java || lang==SrcLangExt::CSharp || lang==SrcLangExt::VHDL || lang==SrcLangExt::Python)
{
return ".";
}
else if (lang==SrcLangExt::PHP && !classScope)
{
return "\\";
}
else
{
return "::";
}
}
/** Checks whether the given url starts with a supported protocol */
bool isURL(const QCString &url)
{
static const std::unordered_set<std::string> schemes = {
"http", "https", "ftp", "ftps", "sftp", "file", "news", "irc", "ircs"
};
QCString loc_url = url.stripWhiteSpace();
int colonPos = loc_url.find(':');
return colonPos!=-1 && schemes.find(loc_url.left(colonPos).str())!=schemes.end();
}
/** Corrects URL \a url according to the relative path \a relPath.
* Returns the corrected URL. For absolute URLs no correction will be done.
*/
QCString correctURL(const QCString &url,const QCString &relPath)
{
QCString result = url;
if (!relPath.isEmpty() && !isURL(url))
{
result.prepend(relPath);
}
return result;
}
//---------------------------------------------------------------------------
bool protectionLevelVisible(Protection prot)
{
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
bool extractPackage = Config_getBool(EXTRACT_PACKAGE);
return (prot!=Protection::Private && prot!=Protection::Package) ||
(prot==Protection::Private && extractPrivate) ||
(prot==Protection::Package && extractPackage);
}
//---------------------------------------------------------------------------
QCString stripIndentation(const QCString &s)
{
if (s.isEmpty()) return s; // empty string -> we're done
//printf("stripIndentation:\n%s\n------\n",qPrint(s));
// compute minimum indentation over all lines
const char *p=s.data();
char c=0;
int indent=0;
int minIndent=1000000; // "infinite"
bool searchIndent=TRUE;
int tabSize=Config_getInt(TAB_SIZE);
while ((c=*p++))
{
if (c=='\t') indent+=tabSize - (indent%tabSize);
else if (c=='\n') indent=0,searchIndent=TRUE;
else if (c==' ') indent++;
else if (searchIndent)
{
searchIndent=FALSE;
if (indent<minIndent) minIndent=indent;
}
}
// no indent to remove -> we're done
if (minIndent==0) return substitute(s,"@ilinebr","\\ilinebr");
// remove minimum indentation for each line
TextStream result;
p=s.data();
indent=0;
while ((c=*p++))
{
if (c=='\n') // start of new line
{
indent=0;
result << c;
}
else if (indent<minIndent) // skip until we reach minIndent
{
if (c=='\t')
{
int newIndent = indent+tabSize-(indent%tabSize);
int i=newIndent;
while (i>minIndent) // if a tab crosses the minIndent boundary fill the rest with spaces
{
result << ' ';
i--;
}
indent=newIndent;
}
else // space
{
indent++;
}
}
else if (c=='\\' && qstrncmp(p,"ilinebr ",8)==0)
// we also need to remove the indentation after a \ilinebr command at the end of a line
{
result << "\\ilinebr ";
p+=8;
int skipAmount=0;
for (int j=0;j<minIndent;j++) if (*(p+j)==' ') skipAmount++; // test to see if we have the indent
if (skipAmount==minIndent)
{
p+=skipAmount; // remove the indent
}
}
else if (c=='@' && qstrncmp(p,"ilinebr",7)==0)
{
result << "\\ilinebr";
p+=7;
}
else // copy anything until the end of the line
{
result << c;
}
}
//printf("stripIndentation: result=\n%s\n------\n",qPrint(result.str()));
return result.str();
}
// strip up to \a indentationLevel spaces from each line in \a doc (excluding the first line)
void stripIndentationVerbatim(QCString &doc,const int indentationLevel)
{
//printf("stripIndentationVerbatim(level=%d):\n%s\n------\n",indentationLevel,qPrint(doc));
if (indentationLevel <= 0 || doc.isEmpty()) return; // nothing to strip
// by stripping content the string will only become shorter so we write the results
// back into the input string and then resize it at the end.
char c = 0;
const char *src = doc.data();
char *dst = doc.rawData();
bool insideIndent = false; // skip the initial line from stripping
int cnt = 0;
while ((c=*src++))
{
// invariant: dst<=src
switch(c)
{
case '\n':
*dst++ = c;
insideIndent = true;
cnt = indentationLevel;
break;
case ' ':
if (insideIndent)
{
if (cnt>0) // count down the spacing until the end of the indent
{
cnt--;
}
else // reached the end of the indent, start of the part of the line to keep
{
insideIndent = false;
*dst++ = c;
}
}
else // part after indent, copy to the output
{
*dst++ = c;
}
break;
default:
insideIndent = false;
*dst++ = c;
break;
}
}
doc.resize(static_cast<uint32_t>(dst-doc.data()));
//printf("stripIndentationVerbatim: result=\n%s\n------\n",qPrint(doc));
}
bool fileVisibleInIndex(const FileDef *fd,bool &genSourceFile)
{
bool allExternals = Config_getBool(ALLEXTERNALS);
bool isDocFile = fd->isDocumentationFile();
genSourceFile = !isDocFile && fd->generateSourceFile();
return ( ((allExternals && fd->isLinkable()) ||
fd->isLinkableInProject()
) &&
!isDocFile
);
}
//--------------------------------------------------------------------------------------
#if 0
/*! @brief Get one unicode character as an unsigned integer from utf-8 string
*
* @param s utf-8 encoded string
* @param idx byte position of given string \a s.
* @return the unicode codepoint, 0 - MAX_UNICODE_CODEPOINT
* @see getNextUtf8OrToLower()
* @see getNextUtf8OrToUpper()
*/
uint32_t getUtf8Code( const QCString& s, int idx )
{
const int length = s.length();
if (idx >= length) { return 0; }
const uint32_t c0 = (uint8_t)s.at(idx);
if ( c0 < 0xC2 || c0 >= 0xF8 ) // 1 byte character
{
return c0;
}
if (idx+1 >= length) { return 0; }
const uint32_t c1 = ((uint8_t)s.at(idx+1)) & 0x3f;
if ( c0 < 0xE0 ) // 2 byte character
{
return ((c0 & 0x1f) << 6) | c1;
}
if (idx+2 >= length) { return 0; }
const uint32_t c2 = ((uint8_t)s.at(idx+2)) & 0x3f;
if ( c0 < 0xF0 ) // 3 byte character
{
return ((c0 & 0x0f) << 12) | (c1 << 6) | c2;
}
if (idx+3 >= length) { return 0; }
// 4 byte character
const uint32_t c3 = ((uint8_t)s.at(idx+3)) & 0x3f;
return ((c0 & 0x07) << 18) | (c1 << 12) | (c2 << 6) | c3;
}
/*! @brief Returns one unicode character as an unsigned integer
* from utf-8 string, making the character lower case if it was upper case.
*
* @param s utf-8 encoded string
* @param idx byte position of given string \a s.
* @return the unicode codepoint, 0 - MAX_UNICODE_CODEPOINT, excludes 'A'-'Z'
* @see getNextUtf8Code()
*/
uint32_t getUtf8CodeToLower( const QCString& s, int idx )
{
const uint32_t v = getUtf8Code( s, idx );
return v < 0x7f ? tolower( v ) : v;
}
/*! @brief Returns one unicode character as an unsigned integer
* from utf-8 string, making the character upper case if it was lower case.
*
* @param s utf-8 encoded string
* @param idx byte position of given string \a s.
* @return the unicode codepoint, 0 - MAX_UNICODE_CODEPOINT, excludes 'A'-'Z'
* @see getNextUtf8Code()
*/
uint32_t getUtf8CodeToUpper( const QCString& s, int idx )
{
const uint32_t v = getUtf8Code( s, idx );
return v < 0x7f ? toupper( v ) : v;
}
#endif
//----------------------------------------------------------------------------
/** Strip the direction part from docs and return it as a string in canonical form
* The input \a docs string can start with e.g. "[in]", "[in, out]", "[inout]", "[out,in]"...
* @returns either "[in,out]", "[in]", or "[out]" or the empty string.
*/
QCString extractDirection(QCString &docs)
{
std::string s = docs.str();
static const reg::Ex re(R"(\[([ inout,]+)\])");
reg::Iterator it(s,re);
reg::Iterator end;
if (it!=end)
{
const auto &match = *it;
size_t p = match.position();
size_t l = match.length();
if (p==0 && l>2)
{
// make dir the part inside [...] without separators
std::string dir = match[1].str();
// strip , and ' ' from dir
dir.erase(std::remove_if(dir.begin(),dir.end(),
[](const char c) { return c==' ' || c==','; }
),dir.end());
unsigned char ioMask=0;
size_t inIndex = dir.find( "in");
size_t outIndex = dir.find("out");
if ( inIndex!=std::string::npos) dir.erase( inIndex,2),ioMask|=(1<<0);
if (outIndex!=std::string::npos) dir.erase(outIndex,3),ioMask|=(1<<1);
if (dir.empty() && ioMask!=0) // only in and/or out attributes found
{
docs = s.substr(l); // strip attributes
if (ioMask==((1<<0)|(1<<1))) return "[in,out]";
else if (ioMask==(1<<0)) return "[in]";
else if (ioMask==(1<<1)) return "[out]";
}
}
}
return "";
}
//-----------------------------------------------------------
/** Computes for a given list type \a inListType, which are the
* the corresponding list type(s) in the base class that are to be
* added to this list.
*
* So for public inheritance, the mapping is 1-1, so outListType1=inListType
* Private members are to be hidden completely.
*
* For protected inheritance, both protected and public members of the
* base class should be joined in the protected member section.
*
* For private inheritance, both protected and public members of the
* base class should be joined in the private member section.
*/
void convertProtectionLevel(
MemberListType inListType,
Protection inProt,
MemberListType *outListType1,
MemberListType *outListType2
)
{
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
// default representing 1-1 mapping
*outListType1=inListType;
*outListType2=MemberListType::Invalid();
if (inProt==Protection::Public)
{
if (inListType.isPrivate())
{
*outListType1=MemberListType::Invalid();
}
}
else if (inProt==Protection::Protected)
{
if (inListType.isPrivate() || inListType.isPublic())
{
*outListType1=MemberListType::Invalid();
}
else if (inListType.isProtected())
{
*outListType2=inListType.toPublic();
}
}
else if (inProt==Protection::Private)
{
if (inListType.isPublic() || inListType.isProtected())
{
*outListType1=MemberListType::Invalid();
}
else if (inListType.isPrivate())
{
if (extractPrivate)
{
*outListType1=inListType.toPublic();
*outListType2=inListType.toProtected();
}
else
{
*outListType1=MemberListType::Invalid();
}
}
}
//printf("convertProtectionLevel(type=%s prot=%d): %s,%s\n",
// qPrint(inListType.to_string()),inProt,qPrint(outListType1->to_string()),qPrint(outListType2->to_string()));
}
bool mainPageHasTitle()
{
return Doxygen::mainPage!=nullptr && Doxygen::mainPage->hasTitle();
}
QCString getDotImageExtension()
{
QCString imgExt = Config_getEnumAsString(DOT_IMAGE_FORMAT);
int i= imgExt.find(':'); // strip renderer part when using e.g. 'png:cairo:gd' as format
return i==-1 ? imgExt : imgExt.left(i);
}
bool openOutputFile(const QCString &outFile,std::ofstream &f)
{
assert(!f.is_open());
bool fileOpened=FALSE;
bool writeToStdout=outFile=="-";
if (writeToStdout) // write to stdout
{
f.basic_ios<char>::rdbuf(std::cout.rdbuf());
fileOpened = true;
}
else // write to file
{
FileInfo fi(outFile.str());
if (fi.exists()) // create a backup
{
Dir dir;
FileInfo backup(fi.filePath()+".bak");
if (backup.exists()) // remove existing backup
dir.remove(backup.filePath());
dir.rename(fi.filePath(),fi.filePath()+".bak");
}
f = Portable::openOutputStream(outFile);
fileOpened = f.is_open();
}
return fileOpened;
}
static bool keyWordsFortranC(const char *contents)
{
static const std::unordered_set<std::string> fortran_C_keywords = {
"character", "call", "close", "common", "continue",
"case", "contains", "cycle", "class", "codimension",
"concurrent", "contiguous", "critical"
};
if (*contents != 'c' && *contents != 'C') return false;
const char *c = contents;
QCString keyword;
while (*c && *c != ' ') {keyword += *c; c++;}
keyword = keyword.lower();
return (fortran_C_keywords.find(keyword.str()) != fortran_C_keywords.end());
}
//------------------------------------------------------
// simplified way to know if this is fixed form
bool recognizeFixedForm(const QCString &contents, FortranFormat format)
{
int column=0;
bool skipLine=FALSE;
if (format == FortranFormat::Fixed) return TRUE;
if (format == FortranFormat::Free) return FALSE;
int tabSize=Config_getInt(TAB_SIZE);
size_t sizCont = contents.length();
for (size_t i=0;i<sizCont;i++)
{
column++;
switch(contents.at(i))
{
case '\n':
column=0;
skipLine=FALSE;
break;
case '\t':
column += tabSize-1;
break;
case ' ':
break;
case '\000':
return FALSE;
case '#':
skipLine=TRUE;
break;
case 'C':
case 'c':
if (column==1)
{
return !keyWordsFortranC(contents.data()+i);
}
// fallthrough
case '*':
if (column==1) return TRUE;
if (skipLine) break;
return FALSE;
case '!':
if (column!=6) skipLine=TRUE;
break;
default:
if (skipLine) break;
if (column>=7) return TRUE;
return FALSE;
}
}
return FALSE;
}
FortranFormat convertFileNameFortranParserCode(QCString fn)
{
QCString ext = getFileNameExtension(fn);
QCString parserName = Doxygen::parserManager->getParserName(ext);
if (parserName == "fortranfixed") return FortranFormat::Fixed;
else if (parserName == "fortranfree") return FortranFormat::Free;
return FortranFormat::Unknown;
}
//------------------------------------------------------------------------
//! remove disabled blocks and all block markers from \a s and return the result as a string
QCString selectBlocks(const QCString &s,const SelectionBlockList &blockList,const SelectionMarkerInfo &markerInfo)
{
if (s.isEmpty()) return s;
// helper to find the end of a block
auto skipBlock = [&markerInfo](const char *p,const SelectionBlock &blk)
{
char c = 0;
while ((c=*p))
{
if (c==markerInfo.markerChar && qstrncmp(p,markerInfo.endStr,markerInfo.endLen)==0) // end marker
{
size_t len = markerInfo.endLen;
bool negate = *(p+markerInfo.endLen)=='!';
if (negate) len++;
size_t blkNameLen = qstrlen(blk.name);
if (qstrncmp(p+len,blk.name,blkNameLen)==0 && // matching marker name
qstrncmp(p+len+blkNameLen,markerInfo.closeStr,markerInfo.closeLen)==0) // matching marker closing
{
//printf("Found end marker %s enabled=%d negate=%d\n",blk.name,blk.enabled,negate);
return p+len+blkNameLen+markerInfo.closeLen;
}
else // not the right marker id
{
p++;
}
}
else // not and end marker
{
p++;
}
}
return p;
};
QCString result;
result.reserve(s.length());
const char *p = s.data();
char c = 0;
while ((c=*p))
{
if (c==markerInfo.markerChar) // potential start of marker
{
if (qstrncmp(p,markerInfo.beginStr,markerInfo.beginLen)==0) // start of begin marker
{
bool found = false;
size_t len = markerInfo.beginLen;
bool negate = *(p+len)=='!';
if (negate) len++;
for (const auto &blk : blockList)
{
size_t blkNameLen = qstrlen(blk.name);
if (qstrncmp(p+len,blk.name,blkNameLen)==0 && // matching marker name
qstrncmp(p+len+blkNameLen,markerInfo.closeStr,markerInfo.closeLen)==0) // matching marker closing
{
bool blockEnabled = blk.enabled!=negate;
//printf("Found start marker %s enabled=%d negate=%d\n",blk.name,blk.enabled,negate);
p+=len+blkNameLen+markerInfo.closeLen;
if (!blockEnabled) // skip until the end of the block
{
//printf("skipping block\n");
p=skipBlock(p,blk);
}
found=true;
break;
}
}
if (!found) // unknown marker id
{
result+=c;
p++;
}
}
else if (qstrncmp(p,markerInfo.endStr,markerInfo.endLen)==0) // start of end marker
{
bool found = false;
size_t len = markerInfo.endLen;
bool negate = *(p+len)=='!';
if (negate) len++;
for (const auto &blk : blockList)
{
size_t blkNameLen = qstrlen(blk.name);
if (qstrncmp(p+len,blk.name,blkNameLen)==0 && // matching marker name
qstrncmp(p+len+blkNameLen,markerInfo.closeStr,markerInfo.closeLen)==0) // matching marker closing
{
//printf("Found end marker %s enabled=%d negate=%d\n",blk.name,blk.enabled,negate);
p+=len+blkNameLen+markerInfo.closeLen;
found=true;
break;
}
}
if (!found) // unknown marker id
{
result+=c;
p++;
}
}
else // not a start or end marker
{
result+=c;
p++;
}
}
else // not a marker character
{
result+=c;
p++;
}
}
//printf("====\n%s\n-----\n%s\n~~~~\n",qPrint(s),qPrint(result));
return result;
}
void checkBlocks(const QCString &s, const QCString fileName,const SelectionMarkerInfo &markerInfo)
{
if (s.isEmpty()) return;
const char *p = s.data();
char c = 0;
while ((c=*p))
{
if (c==markerInfo.markerChar) // potential start of marker
{
if (qstrncmp(p,markerInfo.beginStr,markerInfo.beginLen)==0) // start of begin marker
{
size_t len = markerInfo.beginLen;
bool negate = *(p+len)=='!';
if (negate) len++;
p += len;
QCString marker;
while (*p)
{
if (markerInfo.closeLen==0 && *p=='\n') // matching end of line
{
warn(fileName,-1,"Remaining begin replacement with marker '%s'",qPrint(marker));
break;
}
else if (markerInfo.closeLen!= 0 && qstrncmp(p,markerInfo.closeStr,markerInfo.closeLen)==0) // matching marker closing
{
p += markerInfo.closeLen;
warn(fileName,-1,"Remaining begin replacement with marker '%s'",qPrint(marker));
break;
}
marker += *p;
p++;
}
}
else if (qstrncmp(p,markerInfo.endStr,markerInfo.endLen)==0) // start of end marker
{
size_t len = markerInfo.endLen;
bool negate = *(p+len)=='!';
if (negate) len++;
p += len;
QCString marker;
while (*p)
{
if (markerInfo.closeLen==0 && *p=='\n') // matching end of line
{
warn(fileName,-1,"Remaining end replacement with marker '%s'",qPrint(marker));
break;
}
else if (markerInfo.closeLen!= 0 && qstrncmp(p,markerInfo.closeStr,markerInfo.closeLen)==0) // matching marker closing
{
p += markerInfo.closeLen;
warn(fileName,-1,"Remaining end replacement with marker '%s'",qPrint(marker));
break;
}
marker += *p;
p++;
}
}
}
p++;
}
}
QCString removeEmptyLines(const QCString &s)
{
std::string out;
out.reserve(s.length());
const char *p=s.data();
if (p)
{
char c = 0;
while ((c=*p++))
{
if (c=='\n')
{
const char *e = p;
while (*e==' ' || *e=='\t') e++;
if (*e=='\n')
{
p=e;
}
else out+=c;
}
else
{
out+=c;
}
}
}
//printf("removeEmptyLines(%s)=%s\n",qPrint(s),qPrint(out));
return out;
}
/// split input string \a s by string delimiter \a delimiter.
/// returns a vector of non-empty strings that are between the delimiters
StringVector split(const std::string &s,const std::string &delimiter)
{
StringVector result;
size_t prev = 0, pos = 0, len = s.length();
do
{
pos = s.find(delimiter, prev);
if (pos == std::string::npos) pos = len;
if (pos>prev) result.push_back(s.substr(prev,pos-prev));
prev = pos + delimiter.length();
}
while (pos<len && prev<len);
return result;
}
/// split input string \a s by regular expression delimiter \a delimiter.
/// returns a vector of non-empty strings that are between the delimiters
StringVector split(const std::string &s,const reg::Ex &delimiter)
{
StringVector result;
reg::Iterator iter(s, delimiter);
reg::Iterator end;
size_t p=0;
for ( ; iter != end; ++iter)
{
const auto &match = *iter;
size_t i=match.position();
size_t l=match.length();
if (i>p) result.push_back(s.substr(p,i-p));
p=i+l;
}
if (p<s.length()) result.push_back(s.substr(p));
return result;
}
/// find the index of a string in a vector of strings, returns -1 if the string could not be found
int findIndex(const StringVector &sv,const std::string &s)
{
auto it = std::find(sv.begin(),sv.end(),s);
return it!=sv.end() ? static_cast<int>(it-sv.begin()) : -1;
}
/// find the index of the first occurrence of pattern \a re in a string \a s
/// returns -1 if the pattern could not be found
int findIndex(const std::string &s,const reg::Ex &re)
{
reg::Match match;
return reg::search(s,match,re) ? static_cast<int>(match.position()) : -1;
}
/// create a string where the string in the vector are joined by the given delimiter
std::string join(const StringVector &sv,const std::string &delimiter)
{
std::string result;
bool first=true;
for (const auto &s : sv)
{
if (!first) result+=delimiter;
first=false;
result+=s;
}
return result;
}
QCString integerToAlpha(int n, bool upper)
{
QCString result;
int residual = n;
char modVal[2];
modVal[1] = 0;
while (residual > 0)
{
modVal[0] = (upper ? 'A': 'a') + (residual-1)%26;
result = modVal + result;
residual = (residual-1) / 26;
}
return result;
}
QCString integerToRoman(int n, bool upper)
{
static const char *str_romans_upper[] = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
static const char *str_romans_lower[] = { "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i" };
static const int values[] = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
static const char **str_romans = upper ? str_romans_upper : str_romans_lower;
QCString result;
int residual = n;
for (int i = 0; i < 13; ++i)
{
while (residual - values[i] >= 0)
{
result += str_romans[i];
residual -= values[i];
}
}
return result;
}
QCString detab(const QCString &s,size_t &refIndent)
{
int tabSize = Config_getInt(TAB_SIZE);
size_t size = s.length();
GrowBuf out(size);
const char *data = s.data();
size_t i=0;
int col=0;
constexpr auto doxy_nbsp = "&_doxy_nbsp;"; // doxygen escape command for UTF-8 nbsp
const int maxIndent=1000000; // value representing infinity
int minIndent=maxIndent;
bool skip = false;
while (i<size)
{
char c = data[i++];
switch(c)
{
case '\t': // expand tab
{
int stop = tabSize - (col%tabSize);
//printf("expand at %d stop=%d\n",col,stop);
col+=stop;
while (stop--) out.addChar(' ');
}
break;
case '\\':
if (data[i] == '\\') // escaped command -> ignore
{
out.addChar(c);
out.addChar(data[i++]);
col+=2;
}
else if (i+5<size && qstrncmp(&data[i],"iskip",5)==0) // \iskip command
{
i+=5;
skip = true;
}
else if (i+8<size && qstrncmp(&data[i],"endiskip",8)==0) // \endiskip command
{
i+=8;
skip = false;
}
else // some other command
{
out.addChar(c);
col++;
}
break;
case '\n': // reset column counter
out.addChar(c);
col=0;
break;
case ' ': // increment column counter
out.addChar(c);
col++;
break;
default: // non-whitespace => update minIndent
if (c<0 && i<size) // multibyte sequence
{
// special handling of the UTF-8 nbsp character 0xC2 0xA0
int nb = isUTF8NonBreakableSpace(data);
if (nb>0)
{
out.addStr(doxy_nbsp);
i+=nb-1;
}
else
{
int bytes = getUTF8CharNumBytes(c);
for (int j=0;j<bytes-1 && c;j++)
{
out.addChar(c);
c = data[i++];
}
out.addChar(c);
}
}
else
{
out.addChar(c);
}
if (!skip && col<minIndent) minIndent=col;
col++;
}
}
if (minIndent!=maxIndent) refIndent=minIndent; else refIndent=0;
out.addChar(0);
//printf("detab(\n%s\n)=[\n%s\n]\n",qPrint(s),qPrint(out.get()));
return out.get();
}
QCString getProjectId()
{
QCString projectCookie = Config_getString(HTML_PROJECT_COOKIE);
if (projectCookie.isEmpty()) return QCString();
uint8_t md5_sig[16];
char sigStr[34];
MD5Buffer(projectCookie.data(),static_cast<unsigned int>(projectCookie.length()),md5_sig);
MD5SigToString(md5_sig,sigStr);
sigStr[32]='_'; sigStr[33]=0;
return sigStr;
}
//! Return the index of the last :: in the string \a name that is still before the first <
int computeQualifiedIndex(const QCString &name)
{
int l = static_cast<int>(name.length());
int lastSepPos = -1;
const char *p = name.data();
int i=l-2;
int sharpCount=0;
// --- begin optimized version of ts=name.findRev(">::");
int ts = -1;
while (i>=0)
{
if (p[i]=='>')
{
if (sharpCount==0 && p[i+1]==':' && p[i+2]==':')
{
ts=i;
break;
}
sharpCount++;
}
else if (p[i]=='<')
{
sharpCount--;
}
i--;
}
// --- end optimized version
if (ts==-1) ts=0; else p+=++ts;
for (i=ts;i<l-1;i++)
{
char c=*p++;
if (c==':' && *p==':') lastSepPos=i;
if (c=='<') break;
}
return lastSepPos;
}
void mergeMemberOverrideOptions(MemberDefMutable *md1,MemberDefMutable *md2)
{
if (Config_getBool(CALL_GRAPH) !=md1->hasCallGraph()) md2->overrideCallGraph(md1->hasCallGraph());
if (Config_getBool(CALLER_GRAPH)!=md1->hasCallerGraph()) md2->overrideCallerGraph(md1->hasCallerGraph());
if (Config_getBool(CALL_GRAPH) !=md2->hasCallGraph()) md1->overrideCallGraph( md2->hasCallGraph());
if (Config_getBool(CALLER_GRAPH)!=md2->hasCallerGraph()) md1->overrideCallerGraph(md2->hasCallerGraph());
if (Config_getBool(SHOW_ENUM_VALUES) !=md1->hasEnumValues()) md2->overrideEnumValues(md1->hasEnumValues());
if (Config_getBool(SHOW_ENUM_VALUES) !=md2->hasEnumValues()) md1->overrideEnumValues( md2->hasEnumValues());
if (Config_getBool(REFERENCED_BY_RELATION)!=md1->hasReferencedByRelation()) md2->overrideReferencedByRelation(md1->hasReferencedByRelation());
if (Config_getBool(REFERENCES_RELATION) !=md1->hasReferencesRelation()) md2->overrideReferencesRelation(md1->hasReferencesRelation());
if (Config_getBool(REFERENCED_BY_RELATION)!=md2->hasReferencedByRelation()) md1->overrideReferencedByRelation(md2->hasReferencedByRelation());
if (Config_getBool(REFERENCES_RELATION) !=md2->hasReferencesRelation()) md1->overrideReferencesRelation(md2->hasReferencesRelation());
if (Config_getBool(INLINE_SOURCES)!=md1->hasInlineSource()) md2->overrideInlineSource(md1->hasInlineSource());
if (Config_getBool(INLINE_SOURCES)!=md2->hasInlineSource()) md1->overrideInlineSource(md2->hasInlineSource());
}
size_t updateColumnCount(const char *s,size_t col)
{
if (s)
{
const int tabSize = Config_getInt(TAB_SIZE);
char c;
while ((c=*s++))
{
switch(c)
{
case '\t': col+=tabSize - (col%tabSize);
break;
case '\n': col=0;
break;
default:
col++;
if (c<0) // multi-byte character
{
int numBytes = getUTF8CharNumBytes(c);
for (int i=0;i<numBytes-1 && (c=*s++);i++) {} // skip over extra chars
if (c==0) return col; // end of string half way a multibyte char
}
break;
}
}
}
return col;
}
| 224,798
|
C++
|
.cpp
| 6,790
| 26.928719
| 162
| 0.579398
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,411
|
dotclassgraph.cpp
|
doxygen_doxygen/src/dotclassgraph.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include <algorithm>
#include "containers.h"
#include "dotclassgraph.h"
#include "dotnode.h"
#include "textstream.h"
#include "config.h"
#include "util.h"
void DotClassGraph::addClass(const ClassDef *cd,DotNode *n,EdgeInfo::Colors color,
const QCString &label,const QCString &usedName,const QCString &templSpec,bool base,int distance)
{
if (Config_getBool(HIDE_UNDOC_CLASSES) && !cd->isLinkable()) return;
EdgeInfo::Styles edgeStyle = (!label.isEmpty() || color==EdgeInfo::Orange || color==EdgeInfo::Orange2) ? EdgeInfo::Dashed : EdgeInfo::Solid;
QCString className;
QCString fullName;
if (cd->isAnonymous())
{
className="anonymous:";
className+=label;
fullName = className;
}
else if (!usedName.isEmpty()) // name is a typedef
{
className=usedName;
fullName = className;
}
else if (!templSpec.isEmpty()) // name has a template part
{
className=insertTemplateSpecifierInScope(cd->displayName(),templSpec);
fullName =insertTemplateSpecifierInScope(cd->name(),templSpec);
}
else // just a normal name
{
className=cd->displayName();
fullName = cd->name();
}
//printf("DotClassGraph::addClass(class='%s',parent=%s,prot=%d,label=%s,dist=%d,usedName=%s,templSpec=%s,base=%d)\n",
// qPrint(className),qPrint(n->label()),prot,label,distance,usedName,templSpec,base);
auto it = m_usedNodes.find(fullName.str());
if (it!=m_usedNodes.end()) // class already inserted
{
DotNode *bn = it->second;
if (base)
{
n->addChild(bn,color,edgeStyle,label);
bn->addParent(n);
}
else
{
bn->addChild(n,color,edgeStyle,label);
n->addParent(bn);
}
bn->setDistance(distance);
//printf(" add exiting node %s of %s\n",qPrint(bn->label()),qPrint(n->label()));
}
else // new class
{
QCString displayName=className;
if (Config_getBool(HIDE_SCOPE_NAMES)) displayName=stripScope(displayName);
QCString tmp_url;
if (cd->isLinkable() && !cd->isHidden())
{
tmp_url=cd->getReference()+"$"+cd->getOutputFileBase();
if (!cd->anchor().isEmpty())
{
tmp_url+="#"+cd->anchor();
}
}
QCString tooltip = cd->briefDescriptionAsTooltip();
DotNode *bn = new DotNode(this,
displayName,
tooltip,
tmp_url,
FALSE, // rootNode
cd
);
if (base)
{
n->addChild(bn,color,edgeStyle,label);
bn->addParent(n);
}
else
{
bn->addChild(n,color,edgeStyle,label);
n->addParent(bn);
}
bn->setDistance(distance);
m_usedNodes.emplace(fullName.str(),bn);
//printf(" add new child node '%s' to %s hidden=%d url=%s\n",
// qPrint(className),qPrint(n->label()),cd->isHidden(),qPrint(tmp_url));
buildGraph(cd,bn,base,distance+1);
}
}
void DotClassGraph::determineTruncatedNodes(DotNodeDeque &queue,bool includeParents)
{
while (!queue.empty())
{
DotNode *n = queue.front();
queue.pop_front();
if (n->isVisible() && n->isTruncated()==DotNode::Unknown)
{
bool truncated = FALSE;
for (const auto &dn : n->children())
{
if (!dn->isVisible())
truncated = TRUE;
else
queue.push_back(dn);
}
if (includeParents)
{
for (const auto &dn : n->parents())
{
if (!dn->isVisible())
truncated = TRUE;
else
queue.push_back(dn);
}
}
n->markAsTruncated(truncated);
}
}
}
bool DotClassGraph::determineVisibleNodes(DotNode *rootNode,
int maxNodes,bool includeParents)
{
DotNodeDeque childQueue;
DotNodeDeque parentQueue;
std::vector<size_t> childTreeWidth;
std::vector<size_t> parentTreeWidth;
childQueue.push_back(rootNode);
if (includeParents) parentQueue.push_back(rootNode);
bool firstNode=TRUE; // flag to force reprocessing rootNode in the parent loop
// despite being marked visible in the child loop
while ((!childQueue.empty() || !parentQueue.empty()) && maxNodes>0)
{
if (!childQueue.empty())
{
DotNode *n = childQueue.front();
childQueue.pop_front();
size_t distance = n->distance();
if (!n->isVisible() && distance<=static_cast<size_t>(Config_getInt(MAX_DOT_GRAPH_DEPTH))) // not yet processed
{
if (distance>0)
{
size_t oldSize=childTreeWidth.size();
if (distance>oldSize)
{
childTreeWidth.resize(std::max(childTreeWidth.size(),distance));
for (size_t i=oldSize;i<distance;i++) childTreeWidth[i]=0;
}
childTreeWidth[distance-1]+=n->label().length();
}
n->markAsVisible();
maxNodes--;
// add direct children
for (const auto &dn : n->children())
{
childQueue.push_back(dn);
}
}
}
if (includeParents && !parentQueue.empty())
{
DotNode *n = parentQueue.front();
parentQueue.pop_front();
if ((!n->isVisible() || firstNode) && n->distance()<=Config_getInt(MAX_DOT_GRAPH_DEPTH)) // not yet processed
{
firstNode=FALSE;
size_t distance = n->distance();
if (distance>0)
{
size_t oldSize = parentTreeWidth.size();
if (distance>oldSize)
{
parentTreeWidth.resize(std::max(parentTreeWidth.size(),distance));
for (size_t i=oldSize;i<distance;i++) parentTreeWidth[i]=0;
}
parentTreeWidth[distance-1]+=n->label().length();
}
n->markAsVisible();
maxNodes--;
// add direct parents
for (const auto &dn : n->parents())
{
parentQueue.push_back(dn);
}
}
}
}
if (Config_getBool(UML_LOOK)) return FALSE; // UML graph are always top to bottom
size_t maxWidth=0;
size_t maxHeight=std::max(childTreeWidth.size(),parentTreeWidth.size());
for (size_t i=0;i<childTreeWidth.size();i++)
{
if (childTreeWidth.at(i)>maxWidth) maxWidth=childTreeWidth.at(i);
}
for (size_t i=0;i<parentTreeWidth.size();i++)
{
if (parentTreeWidth.at(i)>maxWidth) maxWidth=parentTreeWidth.at(i);
}
//printf("max tree width=%d, max tree height=%d\n",maxWidth,maxHeight);
return maxWidth>80 && maxHeight<12; // used metric to decide to render the tree
// from left to right instead of top to bottom,
// with the idea to render very wide trees in
// left to right order.
}
static QCString joinLabels(const StringSet &ss)
{
QCString label;
int count=1;
int maxLabels=10;
auto it = std::begin(ss), e = std::end(ss);
if (it!=e) // set not empty
{
label += (*it++).c_str();
for (; it!=e && count < maxLabels ; ++it,++count)
{
label += '\n';
label += (*it).c_str();
}
if (count==maxLabels) label+="\n...";
}
return label;
}
void DotClassGraph::buildGraph(const ClassDef *cd,DotNode *n,bool base,int distance)
{
//printf("DocClassGraph::buildGraph(%s,distance=%d,base=%d)\n",
// qPrint(cd->name()),distance,base);
// ---- Add inheritance relations
if (m_graphType == GraphType::Inheritance || m_graphType==GraphType::Collaboration)
{
for (const auto &bcd : base ? cd->baseClasses() : cd->subClasses())
{
//printf("-------- inheritance relation %s->%s templ='%s'\n",
// qPrint(cd->name()),qPrint(bcd->classDef->name()),qPrint(bcd->templSpecifiers));
addClass(bcd.classDef,n,EdgeInfo::protectionToColor(bcd.prot),QCString(),bcd.usedName,bcd.templSpecifiers,base,distance);
}
}
if (m_graphType == GraphType::Collaboration)
{
// ---- Add usage relations
const UsesClassList &list = base ? cd->usedImplementationClasses() :
cd->usedByImplementationClasses() ;
for (const auto &ucd : list)
{
//printf("addClass: %s templSpec=%s\n",qPrint(ucd.classDef->name()),qPrint(ucd.templSpecifiers));
addClass(ucd.classDef,n,EdgeInfo::Purple,joinLabels(ucd.accessors),QCString(),
ucd.templSpecifiers,base,distance);
}
}
if (Config_getBool(TEMPLATE_RELATIONS) && base)
{
for (const auto &ccd : cd->templateTypeConstraints())
{
//printf("addClass: %s\n",qPrint(ccd.classDef->name()));
addClass(ccd.classDef,n,EdgeInfo::Orange2,joinLabels(ccd.accessors),QCString(),
QCString(),TRUE,distance);
}
}
// ---- Add template instantiation relations
if (Config_getBool(TEMPLATE_RELATIONS))
{
if (base) // template relations for base classes
{
const ClassDef *templMaster=cd->templateMaster();
if (templMaster)
{
for (const auto &ti : templMaster->getTemplateInstances())
if (ti.classDef==cd)
{
addClass(templMaster,n,EdgeInfo::Orange,ti.templSpec,QCString(),QCString(),TRUE,distance);
}
}
}
else // template relations for super classes
{
for (const auto &ti : cd->getTemplateInstances())
{
addClass(ti.classDef,n,EdgeInfo::Orange,ti.templSpec,QCString(),QCString(),FALSE,distance);
}
}
}
}
DotClassGraph::DotClassGraph(const ClassDef *cd,GraphType t)
{
//printf("--------------- DotClassGraph::DotClassGraph '%s'\n",qPrint(cd->displayName()));
m_graphType = t;
QCString tmp_url="";
if (cd->isLinkable() && !cd->isHidden())
{
tmp_url=cd->getReference()+"$"+cd->getOutputFileBase();
if (!cd->anchor().isEmpty())
{
tmp_url+="#"+cd->anchor();
}
}
QCString className = cd->displayName();
QCString tooltip = cd->briefDescriptionAsTooltip();
m_startNode = new DotNode(this,
className,
tooltip,
tmp_url,
TRUE, // is a root node
cd
);
m_startNode->setDistance(0);
m_usedNodes.emplace(className.str(),m_startNode);
buildGraph(cd,m_startNode,TRUE,1);
if (t==GraphType::Inheritance) buildGraph(cd,m_startNode,FALSE,1);
m_lrRank = determineVisibleNodes(m_startNode,Config_getInt(DOT_GRAPH_MAX_NODES),t==GraphType::Inheritance);
DotNodeDeque openNodeQueue;
openNodeQueue.push_back(m_startNode);
determineTruncatedNodes(openNodeQueue,t==GraphType::Inheritance);
m_collabFileName = cd->collaborationGraphFileName();
m_inheritFileName = cd->inheritanceGraphFileName();
}
bool DotClassGraph::isTrivial() const
{
if (m_graphType==GraphType::Inheritance)
return m_startNode->children().empty() && m_startNode->parents().empty();
else
return !Config_getBool(UML_LOOK) && m_startNode->children().empty();
}
bool DotClassGraph::isTooBig() const
{
return numNodes()>=Config_getInt(DOT_GRAPH_MAX_NODES);
}
int DotClassGraph::numNodes() const
{
size_t numNodes = 0;
numNodes+= m_startNode->children().size();
if (m_graphType==GraphType::Inheritance)
{
numNodes+= m_startNode->parents().size();
}
return static_cast<int>(numNodes);
}
DotClassGraph::~DotClassGraph()
{
DotNode::deleteNodes(m_startNode);
}
QCString DotClassGraph::getBaseName() const
{
switch (m_graphType)
{
case GraphType::Collaboration:
return m_collabFileName;
break;
case GraphType::Inheritance:
return m_inheritFileName;
break;
default:
ASSERT(0);
break;
}
return "";
}
void DotClassGraph::computeTheGraph()
{
computeGraph(
m_startNode,
m_graphType,
m_graphFormat,
m_lrRank ? "LR" : "",
m_graphType == GraphType::Inheritance,
TRUE,
m_startNode->label(),
m_theGraph
);
}
QCString DotClassGraph::getMapLabel() const
{
QCString mapName;
switch (m_graphType)
{
case GraphType::Collaboration:
mapName="coll_map";
break;
case GraphType::Inheritance:
mapName="inherit_map";
break;
default:
ASSERT(0);
break;
}
return escapeCharsInString(m_startNode->label(),FALSE)+"_"+escapeCharsInString(mapName,FALSE);
}
QCString DotClassGraph::getImgAltText() const
{
switch (m_graphType)
{
case GraphType::Collaboration:
return "Collaboration graph";
break;
case GraphType::Inheritance:
return "Inheritance graph";
break;
default:
ASSERT(0);
break;
}
return "";
}
QCString DotClassGraph::writeGraph(TextStream &out,
GraphOutputFormat graphFormat,
EmbeddedOutputFormat textFormat,
const QCString &path,
const QCString &fileName,
const QCString &relPath,
bool /*isTBRank*/,
bool generateImageMap,
int graphId)
{
return DotGraph::writeGraph(out, graphFormat, textFormat, path, fileName, relPath, generateImageMap, graphId);
}
//--------------------------------------------------------------------
void DotClassGraph::writeXML(TextStream &t)
{
for (const auto &[name,node] : m_usedNodes)
{
node->writeXML(t,TRUE);
}
}
void DotClassGraph::writeDocbook(TextStream &t)
{
for (const auto &[name,node] : m_usedNodes)
{
node->writeDocbook(t,TRUE);
}
}
void DotClassGraph::writeDEF(TextStream &t)
{
for (const auto &[name,node] : m_usedNodes)
{
node->writeDEF(t);
}
}
| 13,708
|
C++
|
.cpp
| 451
| 25.439024
| 142
| 0.641285
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,412
|
dotnode.cpp
|
doxygen_doxygen/src/dotnode.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include "dotnode.h"
#include "classdef.h"
#include "config.h"
#include "memberlist.h"
#include "membergroup.h"
#include "language.h"
#include "doxygen.h"
#include "util.h"
#include "textstream.h"
/** Helper struct holding the properties of a edge in a dot graph. */
struct EdgeProperties
{
const char * const *edgeColorMap;
const char * const *arrowStyleMap;
const char * const *edgeStyleMap;
};
/*! mapping from protection levels to color names */
static const char *normalEdgeColorMap[] =
{
"steelblue1", // Public
"darkgreen", // Protected
"firebrick4", // Private
"darkorchid3", // "use" relation
"grey75", // Undocumented
"orange", // template relation
"orange" // type constraint
};
static const char *normalArrowStyleMap[] =
{
"empty", // Public
"empty", // Protected
"empty", // Private
"open", // "use" relation
nullptr, // Undocumented
nullptr // template relation
};
static const char *normalEdgeStyleMap[] =
{
"solid", // inheritance
"dashed" // usage
};
static const char *umlEdgeColorMap[] =
{
"steelblue1", // Public
"darkgreen", // Protected
"firebrick4", // Private
"steelblue1", // "use" relation
"grey75", // Undocumented
"orange", // template relation
"orange" // type constraint
};
static const char *umlArrowStyleMap[] =
{
"onormal", // Public
"onormal", // Protected
"onormal", // Private
"odiamond", // "use" relation
nullptr, // Undocumented
nullptr // template relation
};
static const char *umlEdgeStyleMap[] =
{
"solid", // inheritance
"solid" // usage
};
static EdgeProperties normalEdgeProps =
{
normalEdgeColorMap, normalArrowStyleMap, normalEdgeStyleMap
};
static EdgeProperties umlEdgeProps =
{
umlEdgeColorMap, umlArrowStyleMap, umlEdgeStyleMap
};
QCString escapeTooltip(const QCString &tooltip)
{
if (tooltip.isEmpty()) return tooltip;
QCString result;
const char *p=tooltip.data();
char c = 0;
while ((c=*p++))
{
switch(c)
{
case '"': result+="\\\""; break;
case '\\': result+="\\\\"; break;
default: result+=c; break;
}
}
return result;
}
static void writeBoxMemberList(TextStream &t,
char prot,const MemberList *ml,const ClassDef *scope,
bool &lineWritten,
bool isStatic=FALSE,const StringUnorderedSet *skipNames=nullptr)
{
constexpr auto tr_start = "<TR><TD VALIGN=\"top\" CELLPADDING=\"1\" CELLSPACING=\"0\">";
constexpr auto tr_mid = "</TD><TD VALIGN=\"top\" ALIGN=\"LEFT\" CELLPADDING=\"1\" CELLSPACING=\"0\">";
constexpr auto tr_end = "</TD></TR>\n";
constexpr auto br = "<BR ALIGN=\"LEFT\"/>";
if (ml)
{
auto hideUndocMembers = Config_getEnum(HIDE_UNDOC_MEMBERS);
int totalCount=0;
for (const auto &mma : *ml)
{
if (mma->getClassDef()==scope &&
(skipNames==nullptr || skipNames->find(mma->name().str())==std::end(*skipNames)) &&
!(hideUndocMembers && !mma->hasDocumentation())
)
{
totalCount++;
}
}
int count=0;
auto dotUmlDetails = Config_getEnum(DOT_UML_DETAILS);
for (const auto &mma : *ml)
{
if (mma->getClassDef() == scope &&
(skipNames==nullptr || skipNames->find(mma->name().str())==std::end(*skipNames)) &&
!(hideUndocMembers && !mma->hasDocumentation())
)
{
int numFields = Config_getInt(UML_LIMIT_NUM_FIELDS);
if (numFields>0 && (totalCount>numFields*3/2 && count>=numFields))
{
t << tr_start << tr_mid << theTranslator->trAndMore(QCString().sprintf("%d",totalCount-count)) << tr_end;
lineWritten = true;
break;
}
else
{
t << tr_start << prot << tr_mid;
QCString label;
if (dotUmlDetails==DOT_UML_DETAILS_t::YES)
{
label+=mma->typeString();
label+=" ";
}
label+=mma->name();
if (!mma->isObjCMethod() && (mma->isFunction() || mma->isSlot() || mma->isSignal()))
{
if (dotUmlDetails==DOT_UML_DETAILS_t::YES)
{
label+=mma->argsString();
}
else
{
label+="()";
}
}
t << DotNode::convertLabel(label,true);
t << br << tr_end;
lineWritten = true;
count++;
}
}
}
// write member groups within the memberlist
for (const auto &mg : ml->getMemberGroupList())
{
if (!mg->members().empty())
{
writeBoxMemberList(t,prot,&mg->members(),scope,lineWritten,isStatic,skipNames);
}
}
}
}
QCString DotNode::convertLabel(const QCString &l, bool htmlLike)
{
QCString bBefore("\\_/<({[: =-+@%#~?$"); // break before character set
QCString bAfter(">]),:;|"); // break after character set
QCString p(l);
if (p.isEmpty()) return QCString();
QCString result;
char pc=0;
uint32_t idx = 0;
int charsLeft=static_cast<int>(p.length());
int sinceLast=0;
int foldLen = Config_getInt(DOT_WRAP_THRESHOLD); // ideal text length
QCString br;
if (htmlLike)
br = "<BR ALIGN=\"LEFT\"/>";
else
br = "\\l";
while (idx < p.length())
{
char c = p[idx++];
char cs[2] = { c, 0 };
const char *replacement = cs;
if (htmlLike)
{
switch(c)
{
case '\\': replacement="\\\\"; break;
case '\n': replacement="\\n"; break;
case '<': replacement="<"; break;
case '>': replacement=">"; break;
case '"': replacement="""; break;
case '\'': replacement="'"; break;
case '&': replacement="&"; break;
}
}
else
{
switch(c)
{
case '\\': replacement="\\\\"; break;
case '\n': replacement="\\n"; break;
case '<': replacement="\\<"; break;
case '>': replacement="\\>"; break;
case '"': replacement="\\\""; break;
case '|': replacement="\\|"; break;
case '{': replacement="\\{"; break;
case '}': replacement="\\}"; break;
}
}
// Some heuristics to insert newlines to prevent too long
// boxes and at the same time prevent ugly breaks
if (c=='\n')
{
result+=replacement;
foldLen = (3*foldLen+sinceLast+2)/4;
sinceLast=1;
}
else if ((pc!=':' || c!=':') && charsLeft>foldLen/3 && sinceLast>foldLen && bBefore.contains(c))
{
result+=br;
result+=replacement;
foldLen = (foldLen+sinceLast+1)/2;
sinceLast=1;
}
else if (charsLeft>1+foldLen/4 && sinceLast>foldLen+foldLen/3 &&
!isupper(c) && isupper(p[idx]))
{
result+=replacement;
result+=br;
foldLen = (foldLen+sinceLast+1)/2;
sinceLast=0;
}
else if (charsLeft>foldLen/3 && sinceLast>foldLen && bAfter.contains(c) && (c!=':' || p[idx]!=':'))
{
result+=replacement;
result+=br;
foldLen = (foldLen+sinceLast+1)/2;
sinceLast=0;
}
else
{
result+=replacement;
sinceLast++;
}
charsLeft--;
pc=c;
}
if (htmlLike)
{
result = result.stripWhiteSpace();
}
return result;
}
static QCString stripProtectionPrefix(const QCString &s)
{
if (!s.isEmpty() && (s[0]=='-' || s[0]=='+' || s[0]=='~' || s[0]=='#'))
{
return s.mid(1);
}
else
{
return s;
}
}
DotNode::DotNode(DotGraph *graph,const QCString &lab,const QCString &tip, const QCString &url,
bool isRoot,const ClassDef *cd)
: m_graph(graph)
, m_number(graph->getNextNodeNumber())
, m_label(lab)
, m_tooltip(tip)
, m_url(url)
, m_isRoot(isRoot)
, m_classDef(cd)
{
}
void DotNode::addChild(DotNode *n,
EdgeInfo::Colors edgeColor,
EdgeInfo::Styles edgeStyle,
const QCString &edgeLab,
const QCString &edgeURL,
int edgeLabCol
)
{
m_children.push_back(n);
m_edgeInfo.emplace_back(
edgeColor,
edgeStyle,
edgeLab,
edgeURL,
edgeLabCol==-1 ? edgeColor : edgeLabCol);
}
void DotNode::addParent(DotNode *n)
{
m_parents.push_back(n);
}
void DotNode::removeChild(DotNode *n)
{
auto it = std::find(m_children.begin(),m_children.end(),n);
if (it!=m_children.end()) m_children.erase(it);
}
void DotNode::removeParent(DotNode *n)
{
auto it = std::find(m_parents.begin(),m_parents.end(),n);
if (it!=m_parents.end()) m_parents.erase(it);
}
void DotNode::deleteNode(DotNodeRefVector &deletedList)
{
if (m_deleted) return; // avoid recursive loops in case the graph has cycles
m_deleted=TRUE;
// delete all parent nodes of this node
for (const auto &pn : m_parents)
{
pn->deleteNode(deletedList);
}
// delete all child nodes of this node
for (const auto &cn : m_children)
{
cn->deleteNode(deletedList);
}
// add this node to the list of deleted nodes.
deletedList.push_back(this);
}
void DotNode::setDistance(int distance)
{
if (distance<m_distance) m_distance = distance;
}
inline int DotNode::findParent( DotNode *n )
{
auto it = std::find(m_parents.begin(),m_parents.end(),n);
return it!=m_parents.end() ? static_cast<int>(it-m_parents.begin()) : -1;
}
/*! helper function that deletes all nodes in a connected graph, given
* one of the graph's nodes
*/
void DotNode::deleteNodes(DotNode *node)
{
DotNodeRefVector deletedNodes;
node->deleteNode(deletedNodes); // collect nodes to be deleted.
for (const auto &dotNode : deletedNodes)
{
delete dotNode;
}
}
void DotNode::writeLabel(TextStream &t, GraphType gt) const
{
if (m_classDef && Config_getBool(UML_LOOK) && (gt==GraphType::Inheritance || gt==GraphType::Collaboration))
{
// Set shape to the plain type.
// the UML properties and methods are rendered using dot' HTML like table format
t << "shape=plain,label=";
// add names shown as relations to a set, so we don't show
// them as attributes as well
StringUnorderedSet arrowNames;
// for each edge
for (const auto &ei : m_edgeInfo)
{
if (!ei.label().isEmpty()) // labels joined by \n
{
int i=0;
int p=0;
QCString lab;
while ((i=ei.label().find('\n',p))!=-1)
{
lab = stripProtectionPrefix(ei.label().mid(p,i-p));
arrowNames.insert(lab.str());
p=i+1;
}
lab = stripProtectionPrefix(ei.label().right(ei.label().length()-p));
arrowNames.insert(lab.str());
}
}
constexpr auto hr_start = "<TR><TD COLSPAN=\"2\" CELLPADDING=\"1\" CELLSPACING=\"0\">";
constexpr auto hr_end = "</TD></TR>\n";
constexpr auto sep = "<HR/>\n";
constexpr auto empty_line = "<TR><TD COLSPAN=\"2\" CELLPADDING=\"1\" CELLSPACING=\"0\"> </TD></TR>\n";
//printf("DotNode::writeBox for %s\n",qPrint(m_classDef->name()));
t << "<<TABLE CELLBORDER=\"0\" BORDER=\"1\">";
t << hr_start << convertLabel(m_label,true) << hr_end;
auto dotUmlDetails = Config_getEnum(DOT_UML_DETAILS);
if (dotUmlDetails!=DOT_UML_DETAILS_t::NONE)
{
bool lineWritten = false;
t << sep;
writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType::PubAttribs()),m_classDef,lineWritten,FALSE,&arrowNames);
writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType::PubStaticAttribs()),m_classDef,lineWritten,TRUE,&arrowNames);
writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType::Properties()),m_classDef,lineWritten,FALSE,&arrowNames);
writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType::PacAttribs()),m_classDef,lineWritten,FALSE,&arrowNames);
writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType::PacStaticAttribs()),m_classDef,lineWritten,TRUE,&arrowNames);
writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType::ProAttribs()),m_classDef,lineWritten,FALSE,&arrowNames);
writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType::ProStaticAttribs()),m_classDef,lineWritten,TRUE,&arrowNames);
if (Config_getBool(EXTRACT_PRIVATE))
{
writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType::PriAttribs()),m_classDef,lineWritten,FALSE,&arrowNames);
writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType::PriStaticAttribs()),m_classDef,lineWritten,TRUE,&arrowNames);
}
if (!lineWritten) t << empty_line;
t << sep;
lineWritten = false;
writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType::PubMethods()),m_classDef,lineWritten);
writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType::PubStaticMethods()),m_classDef,lineWritten,TRUE);
writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType::PubSlots()),m_classDef,lineWritten);
writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType::PacMethods()),m_classDef,lineWritten);
writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType::PacStaticMethods()),m_classDef,lineWritten,TRUE);
writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType::ProMethods()),m_classDef,lineWritten);
writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType::ProStaticMethods()),m_classDef,lineWritten,TRUE);
writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType::ProSlots()),m_classDef,lineWritten);
if (Config_getBool(EXTRACT_PRIVATE))
{
writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType::PriMethods()),m_classDef,lineWritten);
writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType::PriStaticMethods()),m_classDef,lineWritten,TRUE);
writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType::PriSlots()),m_classDef,lineWritten);
}
if (m_classDef->getLanguage()!=SrcLangExt::Fortran)
{
for (const auto &mg : m_classDef->getMemberGroups())
{
if (!mg->members().empty())
{
writeBoxMemberList(t,'*',&mg->members(),m_classDef,lineWritten,FALSE,&arrowNames);
}
}
}
if (!lineWritten) t << empty_line;
}
t << "</TABLE>>\n";
}
else if (Config_getString(DOT_NODE_ATTR).contains("shape=plain"))
{
t << "label=";
if (m_isRoot)
t << "<<b>" << convertToXML(m_label) << "</b>>";
else if (m_truncated == Truncated)
t << "<<i>" << convertToXML(m_label) << "</i>>";
else
t << '"' << convertLabel(m_label) << '"';
}
else // standard look
{
t << "label=" << '"' << convertLabel(m_label) << '"';
}
}
void DotNode::writeUrl(TextStream &t) const
{
if (m_url.isEmpty() || m_url == DotNode::placeholderUrl) return;
int tagPos = m_url.findRev('$');
t << ",URL=\"";
QCString noTagURL = m_url;
if (tagPos!=-1)
{
t << m_url.left(tagPos);
noTagURL = m_url.mid(tagPos);
}
int anchorPos = noTagURL.findRev('#');
if (anchorPos==-1)
{
addHtmlExtensionIfMissing(noTagURL);
t << noTagURL << "\"";
}
else // insert extensiom before anchor
{
QCString fn = noTagURL.left(anchorPos);
addHtmlExtensionIfMissing(fn);
t << fn << noTagURL.right(noTagURL.length() - anchorPos) << "\"";
}
}
void DotNode::writeBox(TextStream &t,
GraphType gt,
GraphOutputFormat /*format*/,
bool hasNonReachableChildren) const
{
const char *labCol = nullptr;
const char *fillCol = "white";
if (m_classDef)
{
if (m_classDef->hasDocumentation() && hasNonReachableChildren)
{
labCol = "red";
fillCol = "#FFF0F0";
}
else if (m_classDef->hasDocumentation() && !hasNonReachableChildren)
{
labCol = "gray40";
}
else if (!m_classDef->hasDocumentation() && hasNonReachableChildren)
{
labCol = "orangered";
}
else // (!m_classDef->hasDocumentation() && !hasNonReachableChildren)
{
labCol = "grey75";
if (m_classDef->templateMaster() && m_classDef->templateMaster()->hasDocumentation())
{
labCol = "gray40";
}
}
}
else
{
labCol = m_url.isEmpty() ? "grey60" : // non link
(hasNonReachableChildren ? "red" : "grey40");
fillCol = m_url.isEmpty() ? "#E0E0E0" :
(hasNonReachableChildren ? "#FFF0F0" : "white");
}
t << " Node" << m_number << " [";
t << "id=\"Node" << QCString().sprintf("%06d",m_number) << "\",";
writeLabel(t,gt);
t << ",height=0.2,width=0.4";
if (m_isRoot)
{
t << ",color=\"gray40\", fillcolor=\"grey60\", style=\"filled\", fontcolor=\"black\"";
}
else
{
t << ",color=\"" << labCol << "\"";
t << ", fillcolor=\"" << fillCol << "\"";
t << ", style=\"filled\"";
writeUrl(t);
}
if (!m_tooltip.isEmpty())
{
t << ",tooltip=\"" << escapeTooltip(m_tooltip) << "\"";
}
else
{
t << ",tooltip=\" \""; // space in tooltip is required otherwise still something like 'Node0' is used
}
t << "];\n";
}
void DotNode::writeArrow(TextStream &t,
GraphType gt,
GraphOutputFormat /* format */,
const DotNode *cn,
const EdgeInfo *ei,
bool topDown,
bool pointBack) const
{
t << " Node";
if (topDown)
t << cn->number();
else
t << m_number;
t << " -> Node";
if (topDown)
t << m_number;
else
t << cn->number();
t << " [";
const EdgeProperties *eProps = Config_getBool(UML_LOOK) ? ¨EdgeProps : &normalEdgeProps;
QCString aStyle = eProps->arrowStyleMap[ei->color()];
bool umlUseArrow = aStyle=="odiamond";
t << "id=\"edge" << m_graph->getNextEdgeNumber() <<
"_Node" << QCString().sprintf("%06d",m_number) <<
"_Node" << QCString().sprintf("%06d",cn->number()) << "\",";
if (pointBack && !umlUseArrow) t << "dir=\"back\",";
t << "color=\"" << eProps->edgeColorMap[ei->color()] << "\",";
t << "style=\"" << eProps->edgeStyleMap[ei->style()] << "\"";
t << ",tooltip=\" \""; // space in tooltip is required otherwise still something like 'Node0 -> Node1' is used
if (!ei->label().isEmpty())
{
t << ",label=\" " << convertLabel(ei->label()) << "\",fontcolor=\"grey\" ";
}
if (Config_getBool(UML_LOOK) &&
eProps->arrowStyleMap[ei->color()] &&
(gt==GraphType::Inheritance || gt==GraphType::Collaboration)
)
{
bool rev = pointBack;
if (umlUseArrow) rev=!rev; // UML use relates has arrow on the start side
if (rev)
t << ",arrowtail=\"" << eProps->arrowStyleMap[ei->color()] << "\"";
else
t << ",arrowhead=\"" << eProps->arrowStyleMap[ei->color()] << "\"";
}
t << "];\n";
}
void DotNode::write(TextStream &t,
GraphType gt,
GraphOutputFormat format,
bool topDown,
bool toChildren,
bool backArrows)
{
//printf("DotNode::write(%d) name=%s this=%p written=%d visible=%d\n",m_distance,qPrint(m_label),this,m_written,m_visible);
if (m_written) return; // node already written to the output
if (!m_visible) return; // node is not visible
writeBox(t,gt,format,m_truncated==Truncated);
m_written=TRUE;
if (toChildren)
{
auto it = m_edgeInfo.begin();
for (const auto &cn : m_children)
{
if (cn->isVisible())
{
//printf("write arrow %s%s%s\n",qPrint(label()),backArrows?"<-":"->",qPrint(cn->label()));
writeArrow(t,gt,format,cn,&(*it),topDown,backArrows);
}
cn->write(t,gt,format,topDown,toChildren,backArrows);
++it;
}
}
else // render parents
{
for (const auto &pn : m_parents)
{
if (pn->isVisible())
{
const auto &children = pn->children();
auto child_it = std::find(children.begin(),children.end(),this);
size_t index = child_it - children.begin();
//printf("write arrow %s%s%s\n",qPrint(label()),backArrows?"<-":"->",qPrint(pn->label()));
writeArrow(t,
gt,
format,
pn,
&pn->edgeInfo()[index],
FALSE,
backArrows
);
}
pn->write(t,gt,format,TRUE,FALSE,backArrows);
}
}
//printf("end DotNode::write(%d) name=%s\n",distance,qPrint(m_label));
}
void DotNode::writeXML(TextStream &t,bool isClassGraph) const
{
t << " <node id=\"" << m_number << "\">\n";
t << " <label>" << convertToXML(m_label) << "</label>\n";
if (!m_url.isEmpty())
{
QCString url(m_url);
int dollarPos = url.find('$');
if (dollarPos!=-1)
{
t << " <link refid=\"" << convertToXML(url.mid(dollarPos+1)) << "\"";
if (dollarPos>0)
{
t << " external=\"" << convertToXML(url.left(dollarPos)) << "\"";
}
t << "/>\n";
}
}
auto it = m_edgeInfo.begin();
for (const auto &childNode : m_children)
{
const EdgeInfo &edgeInfo = *it;
t << " <childnode refid=\"" << childNode->number() << "\" relation=\"";
if (isClassGraph)
{
switch(edgeInfo.color())
{
case EdgeInfo::Blue: t << "public-inheritance"; break;
case EdgeInfo::Green: t << "protected-inheritance"; break;
case EdgeInfo::Red: t << "private-inheritance"; break;
case EdgeInfo::Purple: t << "usage"; break;
case EdgeInfo::Orange: t << "template-instance"; break;
case EdgeInfo::Orange2: t << "type-constraint"; break;
case EdgeInfo::Grey: ASSERT(0); break;
}
}
else // include graph
{
t << "include";
}
t << "\">\n";
if (!edgeInfo.label().isEmpty())
{
int p=0;
int ni=0;
while ((ni=edgeInfo.label().find('\n',p))!=-1)
{
t << " <edgelabel>"
<< convertToXML(edgeInfo.label().mid(p,ni-p))
<< "</edgelabel>\n";
p=ni+1;
}
t << " <edgelabel>"
<< convertToXML(edgeInfo.label().right(edgeInfo.label().length()-p))
<< "</edgelabel>\n";
}
t << " </childnode>\n";
++it;
}
t << " </node>\n";
}
void DotNode::writeDocbook(TextStream &t,bool isClassGraph) const
{
t << " <node id=\"" << m_number << "\">\n";
t << " <label>" << convertToXML(m_label) << "</label>\n";
if (!m_url.isEmpty())
{
QCString url(m_url);
int dollarPos = url.find('$');
if (dollarPos!=-1)
{
t << " <link refid=\"" << convertToXML(url.mid(dollarPos+1)) << "\"";
if (dollarPos>0)
{
t << " external=\"" << convertToXML(url.left(dollarPos)) << "\"";
}
t << "/>\n";
}
}
auto it = m_edgeInfo.begin();
for (const auto &childNode : m_children)
{
const EdgeInfo &edgeInfo = *it;
t << " <childnode refid=\"" << childNode->number() << "\" relation=\"";
if (isClassGraph)
{
switch(edgeInfo.color())
{
case EdgeInfo::Blue: t << "public-inheritance"; break;
case EdgeInfo::Green: t << "protected-inheritance"; break;
case EdgeInfo::Red: t << "private-inheritance"; break;
case EdgeInfo::Purple: t << "usage"; break;
case EdgeInfo::Orange: t << "template-instance"; break;
case EdgeInfo::Orange2: t << "type-constraint"; break;
case EdgeInfo::Grey: ASSERT(0); break;
}
}
else // include graph
{
t << "include";
}
t << "\">\n";
if (!edgeInfo.label().isEmpty())
{
int p=0;
int ni=0;
while ((ni=edgeInfo.label().find('\n',p))!=-1)
{
t << " <edgelabel>"
<< convertToXML(edgeInfo.label().mid(p,ni-p))
<< "</edgelabel>\n";
p=ni+1;
}
t << " <edgelabel>"
<< convertToXML(edgeInfo.label().right(edgeInfo.label().length()-p))
<< "</edgelabel>\n";
}
t << " </childnode>\n";
++it;
}
t << " </node>\n";
}
void DotNode::writeDEF(TextStream &t) const
{
const char* nodePrefix = " node-";
t << " node = {\n";
t << nodePrefix << "id = " << m_number << ";\n";
t << nodePrefix << "label = '" << m_label << "';\n";
if (!m_url.isEmpty())
{
QCString url(m_url);
int dollarPos = url.find('$');
if (dollarPos!=-1)
{
t << nodePrefix << "link = {\n" << " "
<< nodePrefix << "link-id = '" << url.mid(dollarPos+1) << "';\n";
if (dollarPos>0)
{
t << " " << nodePrefix << "link-external = '"
<< url.left(dollarPos) << "';\n";
}
t << " };\n";
}
}
auto it = m_edgeInfo.begin();
for (const auto &childNode : m_children)
{
const EdgeInfo &edgeInfo = *it;
t << " node-child = {\n";
t << " child-id = '" << childNode->number() << "';\n";
t << " relation = ";
switch (edgeInfo.color())
{
case EdgeInfo::Blue: t << "public-inheritance"; break;
case EdgeInfo::Green: t << "protected-inheritance"; break;
case EdgeInfo::Red: t << "private-inheritance"; break;
case EdgeInfo::Purple: t << "usage"; break;
case EdgeInfo::Orange: t << "template-instance"; break;
case EdgeInfo::Orange2: t << "type-constraint"; break;
case EdgeInfo::Grey: ASSERT(0); break;
}
t << ";\n";
if (!edgeInfo.label().isEmpty())
{
t << " edgelabel = <<_EnD_oF_dEf_TeXt_\n"
<< edgeInfo.label() << "\n"
<< "_EnD_oF_dEf_TeXt_;\n";
}
t << " }; /* node-child */\n";
++it;
}
t << " }; /* node */\n";
}
void DotNode::clearWriteFlag()
{
m_written=FALSE;
for (const auto &pn : m_parents) if (pn->isWritten()) pn->clearWriteFlag();
for (const auto &cn : m_children) if (cn->isWritten()) cn->clearWriteFlag();
}
void DotNode::colorConnectedNodes(int curColor)
{
for (const auto &cn : m_children)
{
if (cn->subgraphId()==-1) // uncolored child node
{
cn->setSubgraphId(curColor);
cn->markAsVisible();
cn->colorConnectedNodes(curColor);
//printf("coloring node %s (%p): %d\n",qPrint(cn->label()),cn,cn->subgraphId());
}
}
for (const auto &pn : m_parents)
{
if (pn->subgraphId()==-1) // uncolored parent node
{
pn->setSubgraphId(curColor);
pn->markAsVisible();
pn->colorConnectedNodes(curColor);
//printf("coloring node %s (%p): %d\n",qPrint(pn->label()),pn,pn->subgraphId());
}
}
}
#define DEBUG_RENUMBERING 0
void DotNode::renumberNodes(int &number)
{
if (!isRenumbered())
{
#if DEBUG_RENUMBERING
static int level = 0;
printf("%3d: ",subgraphId());
for (int i = 0; i < level; i++) printf(" ");
printf("> %s old = %d new = %d\n",qPrint(m_label),m_number,number);
level++;
#endif
m_number = number++;
markRenumbered();
for (const auto &cn : m_children)
{
cn->renumberNodes(number);
}
for (const auto &pn : m_parents)
{
pn->renumberNodes(number);
}
#if DEBUG_RENUMBERING
level--;
printf("%3d: ",subgraphId());
for (int i = 0; i < level; i++) printf(" ");
printf("< %s assigned = %d\n",qPrint(m_label),m_number);
#endif
}
}
| 27,872
|
C++
|
.cpp
| 878
| 26.527335
| 136
| 0.585087
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,413
|
cite.cpp
|
doxygen_doxygen/src/cite.cpp
|
/******************************************************************************
*
* Copyright (C) 2020 by Dimitri van Heesch
* Based on a patch by David Munger
*
* 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.
*
*/
#include "cite.h"
#include "config.h"
#include "language.h"
#include "message.h"
#include "portable.h"
#include "resourcemgr.h"
#include "util.h"
#include "debug.h"
#include "fileinfo.h"
#include "dir.h"
#include "growbuf.h"
#include "entry.h"
#include "commentscan.h"
#include "linkedmap.h"
#include <map>
#include <unordered_map>
#include <string>
#include <fstream>
const char *bibTmpFile = "bibTmpFile_";
const char *bibTmpDir = "bibTmpDir/";
//! class that provide information about the p[osition of a citation name
class CitePosition
{
public:
CitePosition(const QCString &fn, int l) : fileName(fn), lineNr(l) {}
QCString fileName;
int lineNr;
};
static QCString getBibFile(const QCString &inFile)
{
QCString name = inFile;
if (!name.isEmpty() && !name.endsWith(".bib")) name+=".bib";
return name;
}
class CiteInfoImpl : public CiteInfo
{
public:
CiteInfoImpl(const QCString &label, const QCString &text=QCString())
: m_label(label), m_text(text) { }
QCString label() const override { return m_label; }
QCString text() const override { return m_text; }
void setText(const QCString &s) { m_text = s; }
private:
QCString m_label;
QCString m_text;
};
struct CitationManager::Private
{
std::map< std::string,std::unique_ptr<CiteInfoImpl> > entries;
std::unordered_map< int,std::string > formulaCite;
std::unordered_map< std::string, CitePosition > citePosition;
};
CitationManager &CitationManager::instance()
{
static CitationManager ct;
return ct;
}
CitationManager::CitationManager() : p(new Private)
{
}
void CitationManager::insert(const QCString &label)
{
QCString lowerCaseLabel = label.lower();
p->entries.emplace(lowerCaseLabel.str(),std::make_unique<CiteInfoImpl>(lowerCaseLabel));
}
const CiteInfo *CitationManager::find(const QCString &label) const
{
auto it = p->entries.find(label.lower().str());
if (it!=p->entries.end())
{
return it->second.get();
}
return nullptr;
}
void CitationManager::clear()
{
p->entries.clear();
}
bool CitationManager::isEmpty() const
{
size_t numFiles = Config_getList(CITE_BIB_FILES).size();
return (numFiles==0 || p->entries.empty());
}
QCString CitationManager::fileName() const
{
return "citelist";
}
QCString CitationManager::anchorPrefix() const
{
return "CITEREF_";
}
void CitationManager::insertCrossReferencesForBibFile(const QCString &bibFile)
{
// sanity checks
if (bibFile.isEmpty())
{
return;
}
FileInfo fi(bibFile.str());
if (!fi.exists())
{
err("bib file %s not found!\n",qPrint(bibFile));
return;
}
std::ifstream f = Portable::openInputStream(bibFile);
if (!f.is_open())
{
err("could not open file %s for reading\n",qPrint(bibFile));
return;
}
// search for citation cross references
QCString citeName;
std::string lineStr;
int lineCount = 0;
while (getline(f,lineStr))
{
int i = -1;
QCString line(lineStr);
lineCount++;
if (line.stripWhiteSpace().startsWith("@"))
{
// assumption entry like: "@book { name," or "@book { name" (spaces optional)
int j = line.find('{');
// when no {, go hunting for it
while (j==-1 && getline(f,lineStr))
{
line = lineStr;
lineCount++;
j = line.find('{');
}
// search for the name
citeName = "";
if (!f.eof() && j!=-1) // to prevent something like "@manual ," and no { found
{
int k = line.find(',',j);
j++;
// found a line "@....{.....,...." or "@.....{....."
// ^=j ^=k ^=j k=-1
while (!f.eof() && citeName.isEmpty())
{
if (k!=-1)
{
citeName = line.mid(static_cast<size_t>(j),static_cast<size_t>(k-j));
}
else
{
citeName = line.mid(static_cast<size_t>(j));
}
citeName = citeName.stripWhiteSpace();
j = 0;
if (citeName.isEmpty() && getline(f,lineStr))
{
line = lineStr;
lineCount++;
k = line.find(',');
}
}
}
//printf("citeName = #%s#\n",qPrint(citeName));
if (!citeName.isEmpty())
{
std::string lCiteName = citeName.lower().str();
auto it = p->citePosition.find(lCiteName);
if (it != p->citePosition.end())
{
warn(bibFile,lineCount,"multiple use of citation name '%s', (first occurrence: %s, line %d)",
qPrint(lCiteName),qPrint(it->second.fileName),it->second.lineNr);
}
else
{
p->citePosition.emplace(lCiteName,CitePosition(bibFile,lineCount));
}
}
}
else if ((i=line.find("crossref"))!=-1 && !citeName.isEmpty()) /* assumption cross reference is on one line and the only item */
{
int j = line.find('{',i);
int k = line.find('}',i);
if (j>i && k>j)
{
QCString crossrefName = line.mid(static_cast<size_t>(j+1),static_cast<uint32_t>(k-j-1));
// check if the reference with the cross reference is used
// insert cross reference when cross reference has not yet been added.
if (find(citeName) && !find(crossrefName)) // not found yet
{
insert(crossrefName);
}
}
}
}
}
const std::string g_formulaMarker = "CITE_FORMULA_";
QCString CitationManager::getFormulas(const QCString &s)
{
if (s.isEmpty()) return s;
GrowBuf growBuf;
GrowBuf formulaBuf;
bool insideFormula = false;
int citeFormulaCnt = 1;
const size_t tmpLen = 30;
char tmp[tmpLen];
const char *ps=s.data();
char c = 0;
while ((c=*ps++))
{
if (insideFormula)
{
switch (c)
{
case '\\':
formulaBuf.addChar(c);
c = *ps++;
formulaBuf.addChar(c);
break;
case '\n':
formulaBuf.addChar(c);
formulaBuf.addChar(0);
growBuf.addChar('$');
growBuf.addStr(formulaBuf.get());
insideFormula = false;
formulaBuf.clear();
break;
case '$':
qsnprintf(tmp,tmpLen,"%s%06d",g_formulaMarker.c_str(),citeFormulaCnt);
formulaBuf.addChar(0);
p->formulaCite.emplace(citeFormulaCnt,std::string("\\f$") + formulaBuf.get() + "\\f$");
citeFormulaCnt++;
// need { and } due to the capitalization rules of bibtex.
growBuf.addChar('{');
growBuf.addStr(tmp);
growBuf.addChar('}');
insideFormula = false;
formulaBuf.clear();
break;
default:
formulaBuf.addChar(c);
break;
}
}
else
{
switch (c)
{
case '\\':
growBuf.addChar(c);
c = *ps++;
growBuf.addChar(c);
break;
case '$':
insideFormula = true;
break;
default:
growBuf.addChar(c);
break;
}
}
}
if (insideFormula)
{
formulaBuf.addChar(0);
growBuf.addStr(formulaBuf.get());
formulaBuf.clear();
}
growBuf.addChar(0);
return growBuf.get();
}
QCString CitationManager::replaceFormulas(const QCString &s)
{
if (s.isEmpty()) return s;
QCString t;
int pos=0;
int i = -1;
while ((i=s.find(g_formulaMarker.c_str(),pos))!=-1)
{
t += s.mid(pos,i-pos);
int markerSize = static_cast<int>( g_formulaMarker.length());
int markerId = atoi(s.mid(i+markerSize,6).data());
auto it = p->formulaCite.find(markerId);
if (it != p->formulaCite.end()) t += it->second;
pos = i + markerSize+6;
}
t += s.mid(pos);
//printf("replaceFormulas(%s)=%s\n",qPrint(s),qPrint(t));
return t;
}
void CitationManager::generatePage()
{
//printf("** CitationManager::generatePage() count=%d\n",m_ordering.count());
// do not generate an empty citations page
if (isEmpty()) return; // nothing to cite
bool citeDebug = Debug::isFlagSet(Debug::Cite);
// 0. add cross references from the bib files to the cite dictionary
const StringVector &citeDataList = Config_getList(CITE_BIB_FILES);
for (const auto &bibdata : citeDataList)
{
QCString bibFile = getBibFile(QCString(bibdata));
insertCrossReferencesForBibFile(bibFile);
}
// 1. generate file with markers and citations to OUTPUT_DIRECTORY
QCString outputDir = Config_getString(OUTPUT_DIRECTORY);
QCString citeListFile = outputDir+"/citelist.doc";
{
std::ofstream t = Portable::openOutputStream(citeListFile);
if (!t.is_open())
{
err("could not open file %s for writing\n",qPrint(citeListFile));
}
t << "<!-- BEGIN CITATIONS -->\n";
t << "<!--\n";
for (const auto &it : p->entries)
{
t << "\\citation{" << it.second->label() << "}\n";
}
t << "-->\n";
t << "<!-- END CITATIONS -->\n";
t << "<!-- BEGIN BIBLIOGRAPHY -->\n";
t << "<!-- END BIBLIOGRAPHY -->\n";
t.close();
}
// 2. generate bib2xhtml
QCString bib2xhtmlFile = outputDir+"/bib2xhtml.pl";
ResourceMgr::instance().copyResource("bib2xhtml.pl",outputDir);
// 3. generate doxygen.bst
QCString doxygenBstFile = outputDir+"/doxygen.bst";
ResourceMgr::instance().copyResource("doxygen.bst",outputDir);
// 4. for all formats we just copy the bib files to as special output directory
// so bibtex can find them without path (bibtex doesn't support paths or
// filenames with spaces!)
// Strictly not required when only latex is generated
QCString bibOutputDir = outputDir+"/"+bibTmpDir;
QCString bibOutputFiles = "";
Dir thisDir;
if (!thisDir.exists(bibOutputDir.str()) && !thisDir.mkdir(bibOutputDir.str()))
{
err("Failed to create temporary output directory '%s', skipping citations\n",qPrint(bibOutputDir));
return;
}
int i = 0;
for (const auto &bibdata : citeDataList)
{
QCString bibFile = getBibFile(QCString(bibdata));
FileInfo fi(bibFile.str());
if (fi.exists())
{
if (!bibFile.isEmpty())
{
++i;
std::ifstream f_org = Portable::openInputStream(bibFile);
if (!f_org.is_open())
{
err("could not open file %s for reading\n",qPrint(bibFile));
}
std::ofstream f_out = Portable::openOutputStream(bibOutputDir + bibTmpFile + QCString().setNum(i) + ".bib");
if (!f_out.is_open())
{
err("could not open file %s for reading\n",qPrint(bibOutputDir + bibTmpFile + QCString().setNum(i) + ".bib"));
}
QCString docs;
std::string lineStr;
while (getline(f_org,lineStr))
{
docs += lineStr + "\n";
}
docs = getFormulas(docs);
f_out << docs;
if (f_org.is_open()) f_org.close();
if (f_out.is_open()) f_out.close();
bibOutputFiles = bibOutputFiles + " " + bibTmpDir + bibTmpFile + QCString().setNum(i) + ".bib";
}
}
}
std::string oldDir = Dir::currentDirPath();
Dir::setCurrent(outputDir.str());
// 5. run bib2xhtml perl script on the generated file which will insert the
// bibliography in citelist.doc
QCString perlArgs = "\""+bib2xhtmlFile+"\" "+bibOutputFiles+" \""+ citeListFile+"\"";
if (citeDebug) perlArgs+=" -d";
int exitCode = Portable::system("perl",perlArgs);
if (exitCode!=0)
{
err("Problems running bibtex. Verify that the command 'perl --version' works from the command line. Exit code: %d\n",
exitCode);
}
Dir::setCurrent(oldDir);
// 6. read back the file
QCString doc;
{
std::ifstream f = Portable::openInputStream(citeListFile);
if (!f.is_open())
{
err("could not open file %s for reading\n",qPrint(citeListFile));
}
bool insideBib=FALSE;
//printf("input=[%s]\n",qPrint(input));
std::string lineStr;
while (getline(f,lineStr))
{
QCString line(lineStr);
//printf("pos=%d s=%d line=[%s]\n",pos,s,qPrint(line));
if (line.find("<!-- BEGIN BIBLIOGRAPHY")!=-1) insideBib=TRUE;
else if (line.find("<!-- END BIBLIOGRAPH")!=-1) insideBib=FALSE;
// determine text to use at the location of the @cite command
if (insideBib && ((i=line.find("name=\"CITEREF_"))!=-1 || (i=line.find("name=\"#CITEREF_"))!=-1))
{
int j=line.find("\">[");
int k=line.find("]</a>");
if (j!=-1 && k!=-1)
{
size_t ui=static_cast<size_t>(i);
size_t uj=static_cast<size_t>(j);
size_t uk=static_cast<size_t>(k);
QCString label = line.mid(ui+14,uj-ui-14);
QCString number = line.mid(uj+2,uk-uj-1);
line = line.left(ui+14) + label + line.right(line.length()-uj);
auto it = p->entries.find(label.lower().str());
//printf("label='%s' number='%s' => %p\n",qPrint(label),qPrint(number),it->second.get());
if (it!=p->entries.end())
{
it->second->setText(number);
}
}
}
if (insideBib) doc+=line+"\n";
}
//printf("doc=[%s]\n",qPrint(doc));
}
// 7. place formulas back and run the conversion of \f$ ... \f$ to the internal required format
{
doc = replaceFormulas(doc);
Entry current;
bool needsEntry = false;
CommentScanner commentScanner;
int lineNr = 0;
int pos = 0;
GuardedSectionStack guards;
Protection prot = Protection::Public;
commentScanner.parseCommentBlock(
nullptr,
¤t,
doc, // text
fileName(), // file
lineNr, // line of block start
false, // isBrief
false, // isJavaDocStyle
false, // isInBody
prot, // protection
pos, // position,
needsEntry,
false,
&guards
);
doc = current.doc;
}
// 8. add it as a page
addRelatedPage(fileName(),theTranslator->trCiteReferences(),doc,fileName(),1,1);
// 9. for latex we just copy the bib files to the output and let
// latex do this work.
if (Config_getBool(GENERATE_LATEX))
{
// copy bib files to the latex output dir
QCString latexOutputDir = Config_getString(LATEX_OUTPUT)+"/";
i = 0;
for (const auto &bibdata : citeDataList)
{
QCString bibFile = getBibFile(QCString(bibdata));
FileInfo fi(bibFile.str());
if (fi.exists())
{
if (!bibFile.isEmpty())
{
// bug_700510, multiple times the same name were overwriting; creating new names
// also for names with spaces
++i;
copyFile(bibFile,latexOutputDir + bibTmpFile + QCString().setNum(i) + ".bib");
}
}
else
{
err("bib file %s not found!\n",qPrint(bibFile));
}
}
}
// 10. Remove temporary files
if (!citeDebug)
{
thisDir.remove(citeListFile.str());
thisDir.remove(doxygenBstFile.str());
thisDir.remove(bib2xhtmlFile.str());
// we might try to remove too many files as empty files didn't get a corresponding new file
// but the remove function does not emit an error for it and we don't catch the error return
// so no problem.
for (size_t j = 1; j <= citeDataList.size(); j++)
{
QCString bibFile = bibOutputDir + bibTmpFile + QCString().setNum(static_cast<int>(j)) + ".bib";
thisDir.remove(bibFile.str());
}
thisDir.rmdir(bibOutputDir.str());
}
}
QCString CitationManager::latexBibFiles()
{
QCString result;
const StringVector &citeDataList = Config_getList(CITE_BIB_FILES);
int i = 0;
for (const auto &bibdata : citeDataList)
{
QCString bibFile = getBibFile(QCString(bibdata));
FileInfo fi(bibFile.str());
if (fi.exists())
{
if (!bibFile.isEmpty())
{
if (i) result += ",";
i++;
result += bibTmpFile;
result += QCString().setNum(i);
}
}
}
return result;
}
| 16,637
|
C++
|
.cpp
| 536
| 25.496269
| 132
| 0.603911
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,414
|
docbookgen.cpp
|
doxygen_doxygen/src/docbookgen.cpp
|
/******************************************************************************
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include <stdlib.h>
#include "docbookgen.h"
#include "doxygen.h"
#include "message.h"
#include "config.h"
#include "classlist.h"
#include "classdef.h"
#include "diagram.h"
#include "util.h"
#include "defargs.h"
#include "outputgen.h"
#include "dot.h"
#include "dotcallgraph.h"
#include "dotclassgraph.h"
#include "dotdirdeps.h"
#include "dotgroupcollaboration.h"
#include "dotincldepgraph.h"
#include "pagedef.h"
#include "filename.h"
#include "version.h"
#include "docbookvisitor.h"
#include "docparser.h"
#include "language.h"
#include "parserintf.h"
#include "arguments.h"
#include "memberlist.h"
#include "groupdef.h"
#include "memberdef.h"
#include "namespacedef.h"
#include "membername.h"
#include "membergroup.h"
#include "dirdef.h"
#include "section.h"
#include "dir.h"
#include "growbuf.h"
#include "outputlist.h"
#include "moduledef.h"
// no debug info
#define Docbook_DB(x) do {} while(0)
// debug to stdout
//#define Docbook_DB(x) printf x
// debug inside output
//#define Docbook_DB(x) QCString __t;__t.sprintf x;m_t << __t
#if 0
#define DB_GEN_C DB_GEN_C1(m_t)
#define DB_GEN_C1(x) x << "<!-- DB_GEN_C " << __LINE__ << " -->\n";
#define DB_GEN_C2(y) DB_GEN_C2a(m_t,y)
#define DB_GEN_C2a(x,y) x << "<!-- DB_GEN_C " << __LINE__ << " " << y << " -->\n";
#else
#define DB_GEN_C
#define DB_GEN_C1(x)
#define DB_GEN_C2(y)
#define DB_GEN_C2a(x,y)
#endif
//------------------
inline void writeDocbookString(TextStream &t,const QCString &s)
{
t << convertToDocBook(s);
}
inline void writeDocbookCodeString(bool hide,TextStream &t,const QCString &str, size_t &col, size_t stripIndentAmount)
{
if (str.isEmpty()) return;
const int tabSize = Config_getInt(TAB_SIZE);
const char *s = str.data();
char c=0;
if (hide)
{
col = updateColumnCount(s,col);
}
else
{
while ((c=*s++))
{
switch(c)
{
case '\t':
{
int spacesToNextTabStop = tabSize - (col%tabSize);
while (spacesToNextTabStop--)
{
if (col>=stripIndentAmount) t << " ";
col++;
}
break;
}
case ' ':
if (col>=stripIndentAmount) t << " ";
col++;
break;
case '<': t << "<"; col++; break;
case '>': t << ">"; col++; break;
case '&': t << "&"; col++; break;
case '\'': t << "'"; col++; break;
case '"': t << """; col++; break;
default:
{
uint8_t uc = static_cast<uint8_t>(c);
static const char *hex="0123456789ABCDEF";
if (uc<32)
{
t << "$" << hex[uc>>4] << hex[uc&0xF] << ";";
}
else
{
t << c;
}
col++;
}
break;
}
}
}
}
static void addIndexTerm(TextStream &t, QCString prim, QCString sec = "")
{
t << "<indexterm><primary>";
t << convertToDocBook(prim);
t << "</primary>";
if (!sec.isEmpty())
{
t << "<secondary>";
t << convertToDocBook(sec);
t << "</secondary>";
}
t << "</indexterm>\n";
}
void writeDocbookLink(TextStream &t,const QCString & /*extRef*/,const QCString &compoundId,
const QCString &anchorId,const QCString & text,const QCString & /*tooltip*/)
{
t << "<link linkend=\"_" << stripPath(compoundId);
if (!anchorId.isEmpty()) t << "_1" << anchorId;
t << "\"";
t << ">";
writeDocbookString(t,text);
t << "</link>";
}
DocbookCodeGenerator::DocbookCodeGenerator(TextStream *t) : m_t(t)
{
}
void DocbookCodeGenerator::codify(const QCString &text)
{
Docbook_DB(("(codify \"%s\")\n",text));
writeDocbookCodeString(m_hide,*m_t,text,m_col,static_cast<size_t>(m_stripIndentAmount));
}
void DocbookCodeGenerator::stripCodeComments(bool b)
{
m_stripCodeComments = b;
}
void DocbookCodeGenerator::startSpecialComment()
{
m_hide = m_stripCodeComments;
}
void DocbookCodeGenerator::endSpecialComment()
{
m_hide = false;
}
void DocbookCodeGenerator::setStripIndentAmount(size_t amount)
{
m_stripIndentAmount = amount;
}
void DocbookCodeGenerator::writeCodeLink(CodeSymbolType,
const QCString &ref,const QCString &file,
const QCString &anchor,const QCString &name,
const QCString &tooltip)
{
if (m_hide) return;
Docbook_DB(("(writeCodeLink)\n"));
writeDocbookLink(*m_t,ref,file,anchor,name,tooltip);
m_col+=name.length();
}
void DocbookCodeGenerator::writeCodeLinkLine(CodeSymbolType,
const QCString &,const QCString &file,
const QCString &,const QCString &name,
const QCString &,bool writeLineAnchor)
{
if (m_hide) return;
Docbook_DB(("(writeCodeLinkLine)\n"));
if (!writeLineAnchor) return;
*m_t << "<anchor xml:id=\"_" << stripExtensionGeneral(stripPath(file),".xml");
*m_t << "_1l";
writeDocbookString(*m_t,name);
*m_t << "\"/>";
m_col+=name.length();
}
void DocbookCodeGenerator::writeTooltip(const QCString &, const DocLinkInfo &, const QCString &,
const QCString &, const SourceLinkInfo &, const SourceLinkInfo &
)
{
Docbook_DB(("(writeToolTip)\n"));
}
void DocbookCodeGenerator::startCodeLine(int)
{
if (m_hide) return;
Docbook_DB(("(startCodeLine)\n"));
m_insideCodeLine=TRUE;
m_col=0;
}
void DocbookCodeGenerator::endCodeLine()
{
if (m_hide) return;
if (m_insideCodeLine) *m_t << "\n";
Docbook_DB(("(endCodeLine)\n"));
m_lineNumber = -1;
m_refId.clear();
m_external.clear();
m_insideCodeLine=FALSE;
}
void DocbookCodeGenerator::startFontClass(const QCString &colorClass)
{
if (m_hide) return;
Docbook_DB(("(startFontClass)\n"));
*m_t << "<emphasis role=\"" << colorClass << "\">";
m_insideSpecialHL=TRUE;
}
void DocbookCodeGenerator::endFontClass()
{
if (m_hide) return;
Docbook_DB(("(endFontClass)\n"));
*m_t << "</emphasis>"; // non DocBook
m_insideSpecialHL=FALSE;
}
void DocbookCodeGenerator::writeCodeAnchor(const QCString &)
{
Docbook_DB(("(writeCodeAnchor)\n"));
}
void DocbookCodeGenerator::writeLineNumber(const QCString &ref,const QCString &fileName,
const QCString &anchor,int l,bool writeLineAnchor)
{
if (m_hide) return;
Docbook_DB(("(writeLineNumber)\n"));
m_insideCodeLine = TRUE;
if (Config_getBool(SOURCE_BROWSER))
{
QCString lineNumber;
lineNumber.sprintf("%05d",l);
if (!m_sourceFileName.isEmpty())
{
writeCodeLinkLine(CodeSymbolType::Default,ref,m_sourceFileName,anchor,lineNumber,QCString(),writeLineAnchor);
}
if (!fileName.isEmpty())
{
writeCodeLink(CodeSymbolType::Default,ref,fileName,anchor,lineNumber,QCString());
}
else
{
codify(lineNumber);
}
*m_t << " ";
}
else
{
*m_t << l << " ";
}
m_col=0;
}
void DocbookCodeGenerator::finish()
{
endCodeLine();
}
void DocbookCodeGenerator::startCodeFragment(const QCString &)
{
DB_GEN_C1(*m_t)
*m_t << "<programlisting linenumbering=\"unnumbered\">";
}
void DocbookCodeGenerator::endCodeFragment(const QCString &)
{
DB_GEN_C1(*m_t)
//endCodeLine checks is there is still an open code line, if so closes it.
endCodeLine();
*m_t << "</programlisting>";
}
//-------------------------------------------------------------------------------
DocbookGenerator::DocbookGenerator()
: OutputGenerator(Config_getString(DOCBOOK_OUTPUT))
, m_codeList(std::make_unique<OutputCodeList>())
{
DB_GEN_C
m_codeGen = m_codeList->add<DocbookCodeGenerator>(&m_t);
}
DocbookGenerator::DocbookGenerator(const DocbookGenerator &og) : OutputGenerator(og.m_dir), OutputGenIntf()
{
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<DocbookCodeGenerator>(OutputType::Docbook);
m_codeGen->setTextStream(&m_t);
m_denseText = og.m_denseText;
m_inGroup = og.m_inGroup;
m_levelListItem = og.m_levelListItem;
m_inListItem = og.m_inListItem;
m_inSimpleSect = og.m_inSimpleSect;
m_descTable = og.m_descTable;
m_simpleTable = og.m_simpleTable;
m_inLevel = og.m_inLevel;
m_firstMember = og.m_firstMember;
m_openSectionCount = og.m_openSectionCount;
}
DocbookGenerator &DocbookGenerator::operator=(const DocbookGenerator &og)
{
if (this!=&og)
{
m_dir = og.m_dir;
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<DocbookCodeGenerator>(OutputType::Docbook);
m_codeGen->setTextStream(&m_t);
m_denseText = og.m_denseText;
m_inGroup = og.m_inGroup;
m_levelListItem = og.m_levelListItem;
m_inListItem = og.m_inListItem;
m_inSimpleSect = og.m_inSimpleSect;
m_descTable = og.m_descTable;
m_simpleTable = og.m_simpleTable;
m_inLevel = og.m_inLevel;
m_firstMember = og.m_firstMember;
m_openSectionCount = og.m_openSectionCount;
}
return *this;
}
DocbookGenerator::~DocbookGenerator() = default;
void DocbookGenerator::addCodeGen(OutputCodeList &list)
{
list.add<DocbookCodeGeneratorDefer>(m_codeGen);
}
void DocbookGenerator::init()
{
QCString dir=Config_getString(DOCBOOK_OUTPUT);
Dir d(dir.str());
if (!d.exists() && !d.mkdir(dir.str()))
{
term("Could not create output directory %s\n",qPrint(dir));
}
createSubDirs(d);
}
void DocbookGenerator::cleanup()
{
QCString dname = Config_getString(DOCBOOK_OUTPUT);
Dir d(dname.str());
clearSubDirs(d);
}
void DocbookGenerator::startFile(const QCString &name,const QCString &,const QCString &,int,int)
{
DB_GEN_C
QCString fileName=name;
QCString pageName;
QCString fileType="section";
if (fileName == "refman")
{
fileName="index";
fileType="book";
}
else if (fileName == "index")
{
fileName="mainpage";
fileType="chapter";
}
pageName = fileName;
relPath = relativePathToRoot(fileName);
if (!fileName.endsWith(".xml")) fileName+=".xml";
startPlainFile(fileName);
m_codeGen->setRelativePath(relPath);
m_codeGen->setSourceFileName(stripPath(fileName));
m_pageLinks = QCString();
m_t << "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n";
m_t << "<" << fileType << " xmlns=\"http://docbook.org/ns/docbook\" version=\"5.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"";
if (!pageName.isEmpty()) m_t << " xml:id=\"_" << stripPath(pageName) << "\"";
m_t << " xml:lang=\"" << theTranslator->trISOLang() << "\"";
m_t << ">\n";
}
void DocbookGenerator::endFile()
{
DB_GEN_C
closeAllSections();
m_inLevel = -1;
m_inGroup = FALSE;
// Write page links only after all sections have been closed to avoid bugs
m_t << m_pageLinks;
QCString fileType="section";
QCString fileName= m_codeGen->sourceFileName();
if (fileName == "index.xml")
{
fileType="book";
}
else if (fileName == "mainpage.xml")
{
fileType="chapter";
}
m_t << "</" << fileType << ">\n";
endPlainFile();
m_codeGen->setSourceFileName("");
}
void DocbookGenerator::startIndexSection(IndexSection is)
{
DB_GEN_C2("IndexSection " << is)
switch (is)
{
case IndexSection::isTitlePageStart:
{
QCString dbk_projectName = Config_getString(PROJECT_NAME);
m_t << " <info>\n";
m_t << " <title>" << convertToDocBook(dbk_projectName) << "</title>\n";
m_t << " </info>\n";
}
break;
case IndexSection::isTitlePageAuthor:
break;
case IndexSection::isMainPage:
break;
case IndexSection::isModuleIndex:
//Module Index\n"
break;
case IndexSection::isTopicIndex:
//Module Index\n"
break;
case IndexSection::isDirIndex:
//Directory Index\n"
break;
case IndexSection::isNamespaceIndex:
//Namespace Index\n"
break;
case IndexSection::isConceptIndex:
//Concept Index\n"
break;
case IndexSection::isClassHierarchyIndex:
//Hierarchical Index\n"
break;
case IndexSection::isCompoundIndex:
//m_t << "{"; //Class Index}\n"
break;
case IndexSection::isFileIndex:
//Annotated File Index\n"
break;
case IndexSection::isPageIndex:
//Annotated Page Index\n"
break;
case IndexSection::isModuleDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isTopicDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isDirDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isNamespaceDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isConceptDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isClassDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isFileDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isExampleDocumentation:
m_t << "<chapter>\n";
m_t << " <title>";
break;
case IndexSection::isPageDocumentation:
break;
case IndexSection::isPageDocumentation2:
break;
case IndexSection::isEndIndex:
break;
}
}
void DocbookGenerator::endIndexSection(IndexSection is)
{
DB_GEN_C2("IndexSection " << is)
switch (is)
{
case IndexSection::isTitlePageStart:
break;
case IndexSection::isTitlePageAuthor:
break;
case IndexSection::isMainPage:
{
if (Doxygen::mainPage)
{
writePageLink(QCString("mainpage"), TRUE);
}
}
break;
case IndexSection::isModuleIndex:
//m_t << "</chapter>\n";
break;
case IndexSection::isTopicIndex:
//m_t << "</chapter>\n";
break;
case IndexSection::isDirIndex:
//m_t << "<xi:include href=\"dirs.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>";
//m_t << "</chapter>\n";
break;
case IndexSection::isNamespaceIndex:
//m_t << "<xi:include href=\"namespaces.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>";
//m_t << "</chapter>\n";
break;
case IndexSection::isConceptIndex:
//m_t << "<xi:include href=\"concepts.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>";
//m_t << "</chapter>\n";
break;
case IndexSection::isClassHierarchyIndex:
//m_t << "<xi:include href=\"hierarchy.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>";
//m_t << "</chapter>\n";
break;
case IndexSection::isCompoundIndex:
//m_t << "</chapter>\n";
break;
case IndexSection::isFileIndex:
//m_t << "<xi:include href=\"files.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>";
//m_t << "</chapter>\n";
break;
case IndexSection::isPageIndex:
//m_t << "<xi:include href=\"pages.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>";
//m_t << "</chapter>\n";
break;
case IndexSection::isTopicDocumentation:
{
m_t << "</title>\n";
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (!gd->isReference() && !gd->isASubGroup())
{
writePageLink(gd->getOutputFileBase(), TRUE);
}
}
}
m_t << "</chapter>\n";
break;
case IndexSection::isModuleDocumentation:
{
m_t << "</title>\n";
for (const auto &mod : ModuleManager::instance().modules())
{
if (!mod->isReference() && mod->isPrimaryInterface())
{
writePageLink(mod->getOutputFileBase(), TRUE);
}
}
}
m_t << "</chapter>\n";
break;
break;
case IndexSection::isDirDocumentation:
{
m_t << "</title>\n";
for (const auto &dd : *Doxygen::dirLinkedMap)
{
if (dd->isLinkableInProject())
{
m_t << "< xi:include href=\"" << dd->getOutputFileBase() << ".xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n";
}
}
}
m_t << "</chapter>\n";
break;
case IndexSection::isNamespaceDocumentation:
{
m_t << "</title>\n";
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject() && !nd->isAlias())
{
m_t << "<xi:include href=\"" << nd->getOutputFileBase() << ".xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n";
}
}
}
m_t << "</chapter>\n";
break;
case IndexSection::isConceptDocumentation:
{
m_t << "</title>\n";
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject() && !cd->isAlias())
{
m_t << "<xi:include href=\"" << cd->getOutputFileBase() << ".xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n";
}
}
}
m_t << "</chapter>\n";
break;
case IndexSection::isClassDocumentation:
{
m_t << "</title>\n";
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkableInProject() &&
cd->templateMaster()==nullptr &&
!cd->isEmbeddedInOuterScope() &&
!cd->isAlias()
)
{
m_t << " <xi:include href=\"" << cd->getOutputFileBase() << ".xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n";
}
}
}
m_t << "</chapter>\n";
break;
case IndexSection::isFileDocumentation:
{
m_t << "</title>\n";
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->isLinkableInProject())
{
m_t << " <xi:include href=\"" << fd->getOutputFileBase() << ".xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n";
}
if (fd->generateSourceFile())
{
m_t << " <xi:include href=\"" << fd->getSourceFileBase() << ".xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n";
}
}
}
}
m_t << "</chapter>\n";
break;
case IndexSection::isExampleDocumentation:
{
m_t << "</title>\n";
for (const auto &pd : *Doxygen::exampleLinkedMap)
{
m_t << " <xi:include href=\"" << pd->getOutputFileBase() << ".xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n";
}
}
m_t << "</chapter>\n";
break;
case IndexSection::isPageDocumentation:
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (!pd->getGroupDef() && !pd->isReference() && !pd->hasParentPage()
&& Doxygen::mainPage.get() != pd.get())
{
writePageLink(pd->getOutputFileBase(), TRUE);
}
}
break;
case IndexSection::isPageDocumentation2:
break;
case IndexSection::isEndIndex:
m_t << "<index/>\n";
break;
}
}
void DocbookGenerator::writePageLink(const QCString &name, bool first)
{
DB_GEN_C
QCString link;
link.sprintf(" <xi:include href=\"%s.xml\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"/>\n",
name.data());
if (first)
m_t << link;
else
// Buffer page links and write them after all sections are closed
m_pageLinks += link;
}
void DocbookGenerator::writeDoc(const IDocNodeAST *ast,const Definition *ctx,const MemberDef *,int)
{
DB_GEN_C
auto astImpl = dynamic_cast<const DocNodeAST*>(ast);
if (astImpl)
{
DocbookDocVisitor visitor(m_t,*m_codeList,ctx?ctx->getDefFileExtension():QCString());
std::visit(visitor,astImpl->root);
}
}
void DocbookGenerator::startParagraph(const QCString &)
{
DB_GEN_C
m_t << "<para>\n";
}
void DocbookGenerator::endParagraph()
{
DB_GEN_C
m_t << "</para>\n";
}
void DocbookGenerator::writeString(const QCString &text)
{
DB_GEN_C
m_t << text;
}
void DocbookGenerator::startMemberHeader(const QCString &,int)
{
DB_GEN_C
m_t << "<simplesect>\n";
m_inSimpleSect[m_levelListItem] = TRUE;
m_t << " <title>";
}
void DocbookGenerator::endMemberHeader()
{
DB_GEN_C
m_t << " </title>\n";
}
void DocbookGenerator::docify(const QCString &str)
{
DB_GEN_C
m_t << convertToDocBook(str);
}
static QCString objectLinkToString(const QCString &, const QCString &f,
const QCString &anchor, const QCString &text)
{
DB_GEN_C
QCString result;
if (!anchor.isEmpty())
{
if (!f.isEmpty()) result += "<link linkend=\"_" + stripPath(f) + "_1" + anchor + "\">";
else result += "<link linkend=\"_" + anchor + "\">";
}
else
{
result += "<link linkend=\"_" + stripPath(f) + "\">";
}
result += convertToDocBook(text);
result += "</link>";
return result;
}
void DocbookGenerator::writeObjectLink(const QCString &ref, const QCString &f,
const QCString &anchor, const QCString &text)
{
DB_GEN_C
m_t << objectLinkToString(ref,f,anchor,text);
}
void DocbookGenerator::startMemberList()
{
DB_GEN_C
m_t << " <itemizedlist>\n";
m_levelListItem++;
}
void DocbookGenerator::endMemberList()
{
DB_GEN_C
if (m_inListItem[m_levelListItem]) m_t << "</listitem>\n";
m_inListItem[m_levelListItem] = FALSE;
m_t << " </itemizedlist>\n";
m_levelListItem = (m_levelListItem> 0 ? m_levelListItem - 1 : 0);
if (m_inSimpleSect[m_levelListItem]) m_t << "</simplesect>\n";
m_inSimpleSect[m_levelListItem] = FALSE;
}
void DocbookGenerator::startMemberItem(const QCString &,MemberItemType,const QCString &)
{
DB_GEN_C
if (m_inListItem[m_levelListItem]) m_t << "</listitem>\n";
m_t << " <listitem><para>";
m_inListItem[m_levelListItem] = TRUE;
}
void DocbookGenerator::endMemberItem(MemberItemType)
{
DB_GEN_C
m_t << "</para>\n";
}
void DocbookGenerator::startBold()
{
DB_GEN_C
m_t << "<emphasis role=\"strong\">";
}
void DocbookGenerator::endBold()
{
DB_GEN_C
m_t << "</emphasis>";
}
void DocbookGenerator::startGroupHeader(int extraIndentLevel)
{
DB_GEN_C2("m_inLevel " << m_inLevel)
DB_GEN_C2("extraIndentLevel " << extraIndentLevel)
m_firstMember = TRUE;
if (m_inSimpleSect[m_levelListItem]) m_t << "</simplesect>\n";
m_inSimpleSect[m_levelListItem] = FALSE;
if (m_inLevel != -1) m_inGroup = TRUE;
if (m_inLevel == extraIndentLevel) closeSection();
m_inLevel = extraIndentLevel;
openSection();
m_t << "<title>";
}
void DocbookGenerator::writeRuler()
{
DB_GEN_C2("m_inLevel " << m_inLevel)
DB_GEN_C2("m_inGroup " << m_inGroup)
if (m_inGroup) closeSection();
m_inGroup = FALSE;
}
void DocbookGenerator::endGroupHeader(int)
{
DB_GEN_C
m_t << "</title>\n";
}
void DocbookGenerator::startParameterList(bool openBracket)
{
DB_GEN_C
if (openBracket) m_t << "(";
}
void DocbookGenerator::endParameterList()
{
DB_GEN_C
}
void DocbookGenerator::writeNonBreakableSpace(int n)
{
DB_GEN_C
for (int i=0;i<n;i++) m_t << " ";
}
void DocbookGenerator::lineBreak(const QCString &)
{
DB_GEN_C
m_t << "<?linebreak?>";
}
void DocbookGenerator::startTypewriter()
{
DB_GEN_C
if (!m_denseText) m_t << "<computeroutput>";
}
void DocbookGenerator::endTypewriter()
{
DB_GEN_C
if (!m_denseText) m_t << "</computeroutput>\n";
}
void DocbookGenerator::startTextBlock(bool dense)
{
DB_GEN_C
if (dense)
{
m_denseText = TRUE;
m_t << "<programlisting linenumbering=\"unnumbered\">";
}
}
void DocbookGenerator::endTextBlock(bool)
{
DB_GEN_C
if (m_denseText)
{
m_denseText = FALSE;
m_t << "</programlisting>";
}
}
void DocbookGenerator::startMemberDoc(const QCString &clname, const QCString &memname, const QCString &, const QCString &title,
int memCount, int memTotal, bool)
{
DB_GEN_C2("m_inLevel " << m_inLevel)
openSection();
m_t << " <title>" << convertToDocBook(title);
if (memTotal>1)
{
m_t << "<computeroutput>[" << memCount << "/" << memTotal << "]</computeroutput>";
}
m_t << "</title>\n";
if (!memname.isEmpty() && memname[0]!='@')
{
addIndexTerm(m_t,memname,clname);
addIndexTerm(m_t,clname,memname);
}
}
void DocbookGenerator::endMemberDoc(bool)
{
DB_GEN_C
m_t << "</computeroutput></para>";
}
void DocbookGenerator::startTitleHead(const QCString &)
{
DB_GEN_C
m_t << "<title>";
}
void DocbookGenerator::endTitleHead(const QCString &,const QCString &name)
{
DB_GEN_C
m_t << "</title>\n";
if (!name.isEmpty()) addIndexTerm(m_t, name);
}
void DocbookGenerator::startDoxyAnchor(const QCString &fName,const QCString &,
const QCString &anchor,const QCString &,
const QCString &)
{
DB_GEN_C
if (!m_inListItem[m_levelListItem] && !m_descTable && !m_simpleTable)
{
if (!m_firstMember) closeSection();
m_firstMember = FALSE;
}
if (!anchor.isEmpty())
{
m_t << "<anchor xml:id=\"_" << stripPath(fName) << "_1" << anchor << "\"/>";
}
}
void DocbookGenerator::endDoxyAnchor(const QCString &,const QCString &)
{
DB_GEN_C
}
void DocbookGenerator::addLabel(const QCString &,const QCString &)
{
DB_GEN_C
}
void DocbookGenerator::startMemberDocName(bool)
{
DB_GEN_C
m_t << "<para><computeroutput>";
}
void DocbookGenerator::endMemberDocName()
{
DB_GEN_C
}
void DocbookGenerator::startMemberGroupHeader(bool)
{
DB_GEN_C
m_t << "<simplesect><title>";
}
void DocbookGenerator::endMemberGroupHeader()
{
DB_GEN_C
m_t << "</title>\n";
}
void DocbookGenerator::startMemberGroup()
{
DB_GEN_C
}
void DocbookGenerator::endMemberGroup(bool)
{
DB_GEN_C
m_t << "</simplesect>\n";
}
void DocbookGenerator::startClassDiagram()
{
DB_GEN_C
m_t << "<para>";
}
void DocbookGenerator::endClassDiagram(const ClassDiagram &d, const QCString &fileName,const QCString &)
{
DB_GEN_C
m_t << " <informalfigure>\n";
m_t << " <mediaobject>\n";
m_t << " <imageobject>\n";
m_t << " <imagedata width=\"50%\" align=\"center\" valign=\"middle\" scalefit=\"0\" fileref=\""
<< relPath << fileName << ".png\">" << "</imagedata>\n";
m_t << " </imageobject>\n";
d.writeImage(m_t,dir(),relPath,fileName,FALSE);
m_t << " </mediaobject>\n";
m_t << " </informalfigure>\n";
m_t << "</para>\n";
}
void DocbookGenerator::startLabels()
{
DB_GEN_C
}
void DocbookGenerator::writeLabel(const QCString &l,bool isLast)
{
DB_GEN_C
m_t << "<computeroutput>[" << l << "]</computeroutput>";
if (!isLast) m_t << ", ";
}
void DocbookGenerator::endLabels()
{
DB_GEN_C
}
void DocbookGenerator::startExamples()
{
DB_GEN_C
m_t << "<simplesect><title>";
docify(theTranslator->trExamples());
m_t << "</title>";
}
void DocbookGenerator::endExamples()
{
DB_GEN_C
m_t << "</simplesect>\n";
}
void DocbookGenerator::startCompoundTemplateParams()
{
DB_GEN_C
m_t << "<simplesect><title>";
}
void DocbookGenerator::endCompoundTemplateParams()
{
DB_GEN_C
m_t << "</title></simplesect>\n";
}
void DocbookGenerator::writeChar(char c)
{
DB_GEN_C
char cs[2];
cs[0]=c;
cs[1]=0;
docify(cs);
}
void DocbookGenerator::startMemberDocPrefixItem()
{
DB_GEN_C
m_t << "<computeroutput>";
}
void DocbookGenerator::endMemberDocPrefixItem()
{
DB_GEN_C
m_t << "</computeroutput>";
}
void DocbookGenerator::exceptionEntry(const QCString &prefix,bool closeBracket)
{
DB_GEN_C
if (!prefix.isEmpty())
{
m_t << " " << prefix << "(";
}
else if (closeBracket)
{
m_t << ")";
}
m_t << " ";
}
void DocbookGenerator::startParameterName(bool)
{
DB_GEN_C
m_t << " ";
}
void DocbookGenerator::endParameterName()
{
DB_GEN_C
}
void DocbookGenerator::startParameterExtra()
{
DB_GEN_C
}
void DocbookGenerator::endParameterExtra(bool last,bool /*emptyList*/,bool closeBracket)
{
DB_GEN_C
if (last && closeBracket)
{
m_t << ")";
}
}
void DocbookGenerator::startParameterDefVal(const char *sep)
{
DB_GEN_C
m_t << sep;
if (!m_denseText) m_t << "<computeroutput>";
}
void DocbookGenerator::endParameterDefVal()
{
DB_GEN_C
if (!m_denseText) m_t << "</computeroutput>\n";
}
void DocbookGenerator::startMemberTemplateParams()
{
DB_GEN_C
}
void DocbookGenerator::endMemberTemplateParams(const QCString &,const QCString &)
{
DB_GEN_C
m_t << "</para>";
m_t << "<para>";
}
void DocbookGenerator::startSection(const QCString &lab,const QCString &,SectionType)
{
DB_GEN_C
openSection("xml:id=\"_" + stripPath(lab) + "\"");
m_t << "<title>";
}
void DocbookGenerator::endSection(const QCString &,SectionType)
{
DB_GEN_C
m_t << "</title>";
closeSection();
}
void DocbookGenerator::addIndexItem(const QCString &prim,const QCString &sec)
{
DB_GEN_C
addIndexTerm(m_t, prim, sec);
}
void DocbookGenerator::startMemberDocSimple(bool isEnum)
{
DB_GEN_C
int ncols=0;
QCString title;
if (isEnum)
{
ncols = 2;
title = theTranslator->trEnumerationValues();
}
else
{
ncols = 3;
title = theTranslator->trCompoundMembers();
}
m_t << "<table frame=\"all\">\n";
if (!title.isEmpty()) m_t << "<title>" << convertToDocBook(title) << "</title>\n";
m_t << " <tgroup cols=\"" << ncols << "\" align=\"left\" colsep=\"1\" rowsep=\"1\">\n";
for (int i = 0; i < ncols; i++)
{
m_t << " <colspec colname='c" << i+1 << "'/>\n";
}
m_t << "<tbody>\n";
m_simpleTable = true;
}
void DocbookGenerator::endMemberDocSimple(bool /* isEnum */)
{
DB_GEN_C
m_t << " </tbody>\n";
m_t << " </tgroup>\n";
m_t << "</table>\n";
m_simpleTable = false;
}
void DocbookGenerator::startInlineMemberType()
{
DB_GEN_C
m_t << "<row><entry>";
}
void DocbookGenerator::endInlineMemberType()
{
DB_GEN_C
m_t << "</entry>";
}
void DocbookGenerator::startInlineMemberName()
{
DB_GEN_C
m_t << "<entry>";
}
void DocbookGenerator::endInlineMemberName()
{
DB_GEN_C
m_t << "</entry>";
}
void DocbookGenerator::startInlineMemberDoc()
{
DB_GEN_C
m_t << "<entry>";
}
void DocbookGenerator::endInlineMemberDoc()
{
DB_GEN_C
m_t << "</entry></row>\n";
}
void DocbookGenerator::startDescTable(const QCString &title,const bool hasInits)
{
DB_GEN_C
int ncols = (hasInits?3:2);
m_t << "<informaltable frame=\"all\">\n";
if (!title.isEmpty()) m_t << "<title>" << convertToDocBook(title) << "</title>\n";
m_t << " <tgroup cols=\"" << ncols << "\" align=\"left\" colsep=\"1\" rowsep=\"1\">\n";
int i = 1;
m_t << " <colspec colname='c" << i++ << "'/>\n";
if (hasInits) m_t << " <colspec colname='c" << i++ << "' align='right'/>\n";
m_t << " <colspec colname='c" << i++ << "'/>\n";
m_t << "<tbody>\n";
m_descTable = TRUE;
}
void DocbookGenerator::endDescTable()
{
DB_GEN_C
m_t << " </tbody>\n";
m_t << " </tgroup>\n";
m_t << "</informaltable>\n";
m_descTable = FALSE;
}
void DocbookGenerator::startDescTableRow()
{
DB_GEN_C
m_t << "<row>";
m_t << "<entry>";
}
void DocbookGenerator::endDescTableRow()
{
DB_GEN_C
m_t << "</row>";
}
void DocbookGenerator::startDescTableTitle()
{
DB_GEN_C
}
void DocbookGenerator::endDescTableTitle()
{
DB_GEN_C
}
void DocbookGenerator::startDescTableInit()
{
DB_GEN_C
m_t << "</entry><entry>";
}
void DocbookGenerator::endDescTableInit()
{
DB_GEN_C
}
void DocbookGenerator::startDescTableData()
{
DB_GEN_C
m_t << "</entry><entry>";
}
void DocbookGenerator::endDescTableData()
{
DB_GEN_C
m_t << "</entry>";
}
void DocbookGenerator::startGroupCollaboration()
{
DB_GEN_C
}
void DocbookGenerator::endGroupCollaboration(DotGroupCollaboration &g)
{
DB_GEN_C
g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::DocBook,dir(),fileName(),relPath,FALSE);
}
void DocbookGenerator::startDotGraph()
{
DB_GEN_C
}
void DocbookGenerator::endDotGraph(DotClassGraph &g)
{
DB_GEN_C
g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::DocBook,dir(),fileName(),relPath,TRUE,FALSE);
}
void DocbookGenerator::startInclDepGraph()
{
DB_GEN_C
}
void DocbookGenerator::endInclDepGraph(DotInclDepGraph &g)
{
DB_GEN_C
QCString fn = g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::DocBook,dir(),fileName(),relPath,FALSE);
}
void DocbookGenerator::startCallGraph()
{
DB_GEN_C
}
void DocbookGenerator::endCallGraph(DotCallGraph &g)
{
DB_GEN_C
QCString fn = g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::DocBook,dir(),fileName(),relPath,FALSE);
}
void DocbookGenerator::startDirDepGraph()
{
DB_GEN_C
}
void DocbookGenerator::endDirDepGraph(DotDirDeps &g)
{
DB_GEN_C
QCString fn = g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::DocBook,dir(),fileName(),relPath,FALSE);
}
void DocbookGenerator::startMemberDocList()
{
DB_GEN_C
}
void DocbookGenerator::endMemberDocList()
{
DB_GEN_C
m_inGroup = TRUE;
}
void DocbookGenerator::startConstraintList(const QCString &header)
{
DB_GEN_C
m_t << "<simplesect><title>";
docify(header);
m_t << "</title>\n";
}
void DocbookGenerator::startConstraintParam()
{
DB_GEN_C
m_t << "<para><emphasis role=\"strong\">";
}
void DocbookGenerator::endConstraintParam()
{
DB_GEN_C
}
void DocbookGenerator::startConstraintType()
{
DB_GEN_C
m_t << ":";
}
void DocbookGenerator::endConstraintType()
{
DB_GEN_C
m_t << "</emphasis></para>\n";
}
void DocbookGenerator::startConstraintDocs()
{
DB_GEN_C
}
void DocbookGenerator::endConstraintDocs()
{
DB_GEN_C
}
void DocbookGenerator::endConstraintList()
{
DB_GEN_C
m_t << "</simplesect>\n";
}
void DocbookGenerator::openSection(const QCString &attr)
{
m_t << "<section";
if (!attr.isEmpty()) m_t << " " << attr;
m_t << ">\n";
m_openSectionCount++;
}
void DocbookGenerator::closeSection()
{
m_t << "</section>\n";
m_openSectionCount--;
}
void DocbookGenerator::closeAllSections()
{
while (m_openSectionCount>0)
{
closeSection();
}
}
void DocbookGenerator::writeInheritedSectionTitle(
const QCString &/*id*/,const QCString &ref,
const QCString &file, const QCString &anchor,
const QCString &title, const QCString &name)
{
DB_GEN_C
m_t << theTranslator->trInheritedFrom(convertToDocBook(title), objectLinkToString(ref, file, anchor, name));
}
void DocbookGenerator::writeLocalToc(const SectionRefs §ionRefs,const LocalToc &localToc)
{
if (localToc.isDocbookEnabled())
{
m_t << " <toc>\n";
m_t << " <title>" << theTranslator->trRTFTableOfContents() << "</title>\n";
int level=1;
int maxLevel = localToc.docbookLevel();
BoolVector inLi(maxLevel+1,false);
for (const SectionInfo *si : sectionRefs)
{
SectionType type = si->type();
if (type.isSection())
{
//printf(" level=%d title=%s\n",level,qPrint(si->title));
int nextLevel = type.level();
if (nextLevel>level)
{
for (int l=level;l<nextLevel;l++)
{
if (l < maxLevel) m_t << " <tocdiv>\n";
}
}
else if (nextLevel<level)
{
for (int l=level;l>nextLevel;l--)
{
inLi[l]=FALSE;
if (l <= maxLevel) m_t << " </tocdiv>\n";
}
}
if (nextLevel <= maxLevel)
{
QCString titleDoc = convertToDocBook(si->title());
QCString label = convertToDocBook(si->label());
if (titleDoc.isEmpty()) titleDoc = label;
m_t << " <tocentry>" << titleDoc << "</tocentry>\n";
}
inLi[nextLevel]=TRUE;
level = nextLevel;
}
}
if (level > maxLevel) level = maxLevel;
while (level>1 && level <= maxLevel)
{
inLi[level]=FALSE;
m_t << "</tocdiv>\n";
level--;
}
m_t << " </toc>\n";
}
}
//-------------------------------------------------------------------------------------------------
static constexpr auto hex="0123456789ABCDEF";
/*! Converts a string to an DocBook-encoded string */
QCString convertToDocBook(const QCString &s, const bool retainNewline)
{
if (s.isEmpty()) return s;
GrowBuf growBuf;
const char *p = s.data();
const char *q = nullptr;
int cnt = 0;
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '\n': if (retainNewline) growBuf.addStr("<literallayout> 
</literallayout>"); growBuf.addChar(c); break;
case '<': growBuf.addStr("<"); break;
case '>': growBuf.addStr(">"); break;
case '&': // possibility to have a special symbol
q = p;
cnt = 2; // we have to count & and ; as well
while ((*q >= 'a' && *q <= 'z') || (*q >= 'A' && *q <= 'Z') || (*q >= '0' && *q <= '9'))
{
cnt++;
q++;
}
if (*q == ';')
{
--p; // we need & as well
HtmlEntityMapper::SymType res = HtmlEntityMapper::instance().name2sym(QCString(p).left(cnt));
if (res == HtmlEntityMapper::Sym_Unknown)
{
p++;
growBuf.addStr("&");
}
else
{
growBuf.addStr(HtmlEntityMapper::instance().docbook(res));
q++;
p = q;
}
}
else
{
growBuf.addStr("&");
}
break;
case '\'': growBuf.addStr("'"); break;
case '"': growBuf.addStr("""); break;
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
case 11: case 12: case 14: case 15: case 16: case 17: case 18:
case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26:
case 27: case 28: case 29: case 30: case 31:
growBuf.addStr("$");
growBuf.addChar(hex[static_cast<uint8_t>(c)>>4]);
growBuf.addChar(hex[static_cast<uint8_t>(c)&0xF]);
growBuf.addChar(';');
break;
default:
growBuf.addChar(c);
break;
}
}
growBuf.addChar(0);
return growBuf.get();
}
| 38,598
|
C++
|
.cpp
| 1,446
| 22.624481
| 135
| 0.618342
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,415
|
classdef.cpp
|
doxygen_doxygen/src/classdef.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2024 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.
*
*/
#include <cstdio>
#include <algorithm>
#include "types.h"
#include "classdef.h"
#include "classlist.h"
#include "entry.h"
#include "doxygen.h"
#include "membername.h"
#include "message.h"
#include "config.h"
#include "util.h"
#include "diagram.h"
#include "language.h"
#include "htmlhelp.h"
#include "example.h"
#include "outputlist.h"
#include "dot.h"
#include "dotclassgraph.h"
#include "dotrunner.h"
#include "defargs.h"
#include "debug.h"
#include "docparser.h"
#include "searchindex.h"
#include "vhdldocgen.h"
#include "layout.h"
#include "arguments.h"
#include "memberlist.h"
#include "groupdef.h"
#include "filedef.h"
#include "namespacedef.h"
#include "membergroup.h"
#include "definitionimpl.h"
#include "symbolresolver.h"
#include "fileinfo.h"
#include "trace.h"
#include "moduledef.h"
//-----------------------------------------------------------------------------
static QCString makeQualifiedNameWithTemplateParameters(const ClassDef *cd,
const ArgumentLists *actualParams,uint32_t *actualParamIndex)
{
//bool optimizeOutputJava = Config_getBool(OPTIMIZE_OUTPUT_JAVA);
bool hideScopeNames = Config_getBool(HIDE_SCOPE_NAMES);
//printf("qualifiedNameWithTemplateParameters() localName=%s\n",qPrint(cd->localName()));
QCString scName;
const Definition *d=cd->getOuterScope();
if (d)
{
if (d->definitionType()==Definition::TypeClass)
{
const ClassDef *ocd=toClassDef(d);
scName = ocd->qualifiedNameWithTemplateParameters(actualParams,actualParamIndex);
}
else if (!hideScopeNames)
{
scName = d->qualifiedName();
}
}
SrcLangExt lang = cd->getLanguage();
QCString scopeSeparator = getLanguageSpecificSeparator(lang);
if (!scName.isEmpty()) scName+=scopeSeparator;
bool isSpecialization = cd->localName().find('<')!=-1;
QCString clName = cd->className();
scName+=clName;
if (!cd->templateArguments().empty())
{
if (actualParams && *actualParamIndex<actualParams->size())
{
const ArgumentList &al = actualParams->at(*actualParamIndex);
if (!isSpecialization)
{
scName+=tempArgListToString(al,lang);
}
(*actualParamIndex)++;
}
else
{
if (!isSpecialization)
{
scName+=tempArgListToString(cd->templateArguments(),lang);
}
}
}
//printf("qualifiedNameWithTemplateParameters: scope=%s qualifiedName=%s\n",qPrint(name()),qPrint(scName));
return scName;
}
static QCString makeDisplayName(const ClassDef *cd,bool includeScope)
{
//bool optimizeOutputForJava = Config_getBool(OPTIMIZE_OUTPUT_JAVA);
SrcLangExt lang = cd->getLanguage();
//bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
QCString n;
if (lang==SrcLangExt::VHDL)
{
n = VhdlDocGen::getClassName(cd);
}
else
{
if (includeScope)
{
n=cd->qualifiedNameWithTemplateParameters();
}
else
{
n=cd->className();
}
}
if (cd->isAnonymous())
{
n = removeAnonymousScopes(n);
}
QCString sep=getLanguageSpecificSeparator(lang);
if (sep!="::")
{
n=substitute(n,"::",sep);
}
if (cd->compoundType()==ClassDef::Protocol && n.endsWith("-p"))
{
n="<"+n.left(n.length()-2)+">";
}
return n;
}
//-----------------------------------------------------------------------------
static QCString getCompoundTypeString(SrcLangExt lang,ClassDef::CompoundType compType,bool isJavaEnum)
{
if (lang==SrcLangExt::Fortran)
{
switch (compType)
{
case ClassDef::Class: return "module";
case ClassDef::Struct: return "type";
case ClassDef::Union: return "union";
case ClassDef::Interface: return "interface";
case ClassDef::Protocol: return "protocol";
case ClassDef::Category: return "category";
case ClassDef::Exception: return "exception";
default: return "unknown";
}
}
else
{
switch (compType)
{
case ClassDef::Class: return isJavaEnum ? "enum" : "class";
case ClassDef::Struct: return "struct";
case ClassDef::Union: return "union";
case ClassDef::Interface: return lang==SrcLangExt::ObjC ? "class" : "interface";
case ClassDef::Protocol: return "protocol";
case ClassDef::Category: return "category";
case ClassDef::Exception: return "exception";
case ClassDef::Service: return "service";
case ClassDef::Singleton: return "singleton";
default: return "unknown";
}
}
}
//-----------------------------------------------------------------------------
/** Implementation of the ClassDef interface */
class ClassDefImpl : public DefinitionMixin<ClassDefMutable>
{
public:
ClassDefImpl(const QCString &fileName,int startLine,int startColumn,
const QCString &name,CompoundType ct,
const QCString &ref=QCString(),const QCString &fName=QCString(),
bool isSymbol=TRUE,bool isJavaEnum=FALSE);
DefType definitionType() const override { return TypeClass; }
std::unique_ptr<ClassDef> deepCopy(const QCString &name) const override;
void moveTo(Definition *) override;
CodeSymbolType codeSymbolType() const override;
QCString getOutputFileBase() const override;
QCString getInstanceOutputFileBase() const override;
QCString getSourceFileBase() const override;
QCString getReference() const override;
bool isReference() const override;
bool isLocal() const override;
ClassLinkedRefMap getClasses() const override;
bool hasDocumentation() const override;
bool hasDetailedDescription() const override;
QCString collaborationGraphFileName() const override;
QCString inheritanceGraphFileName() const override;
QCString displayName(bool includeScope=TRUE) const override;
CompoundType compoundType() const override;
QCString compoundTypeString() const override;
const BaseClassList &baseClasses() const override;
void updateBaseClasses(const BaseClassList &bcd) override;
const BaseClassList &subClasses() const override;
void updateSubClasses(const BaseClassList &bcd) override;
const MemberNameInfoLinkedMap &memberNameInfoLinkedMap() const override;
Protection protection() const override;
bool isLinkableInProject() const override;
bool isLinkable() const override;
bool isVisibleInHierarchy() const override;
bool visibleInParentsDeclList() const override;
const ArgumentList &templateArguments() const override;
FileDef *getFileDef() const override;
ModuleDef *getModuleDef() const override;
const MemberDef *getMemberByName(const QCString &) const override;
int isBaseClass(const ClassDef *bcd,bool followInstances,const QCString &templSpec) const override;
bool isSubClass(ClassDef *bcd,int level=0) const override;
bool isAccessibleMember(const MemberDef *md) const override;
const TemplateInstanceList &getTemplateInstances() const override;
const ClassDef *templateMaster() const override;
bool isTemplate() const override;
const IncludeInfo *includeInfo() const override;
const UsesClassList &usedImplementationClasses() const override;
const UsesClassList &usedByImplementationClasses() const override;
const ConstraintClassList &templateTypeConstraints() const override;
bool isTemplateArgument() const override;
const Definition *findInnerCompound(const QCString &name) const override;
ArgumentLists getTemplateParameterLists() const override;
QCString qualifiedNameWithTemplateParameters(
const ArgumentLists *actualParams=nullptr,uint32_t *actualParamIndex=nullptr) const override;
bool isAbstract() const override;
bool isObjectiveC() const override;
bool isFortran() const override;
bool isCSharp() const override;
bool isFinal() const override;
bool isSealed() const override;
bool isPublished() const override;
bool isExtension() const override;
bool isForwardDeclared() const override;
bool isInterface() const override;
ClassDef *categoryOf() const override;
QCString className() const override;
MemberList *getMemberList(MemberListType lt) const override;
const MemberLists &getMemberLists() const override;
const MemberGroupList &getMemberGroups() const override;
const TemplateNameMap &getTemplateBaseClassNames() const override;
bool isUsedOnly() const override;
QCString anchor() const override;
bool isEmbeddedInOuterScope() const override;
bool isSimple() const override;
const ClassDef *tagLessReference() const override;
const MemberDef *isSmartPointer() const override;
bool isJavaEnum() const override;
QCString title() const override;
QCString generatedFromFiles() const override;
const FileList &usedFiles() const override;
const ArgumentList &typeConstraints() const override;
const ExampleList &getExamples() const override;
bool hasExamples() const override;
QCString getMemberListFileName() const override;
bool subGrouping() const override;
bool isSliceLocal() const override;
bool hasNonReferenceSuperClass() const override;
QCString requiresClause() const override;
StringVector getQualifiers() const override;
bool containsOverload(const MemberDef *md) const override;
ClassDef *insertTemplateInstance(const QCString &fileName,int startLine,int startColumn,
const QCString &templSpec,bool &freshInstance) const override;
bool isImplicitTemplateInstance() const override;
void insertBaseClass(ClassDef *,const QCString &name,Protection p,Specifier s,const QCString &t=QCString()) override;
void insertSubClass(ClassDef *,Protection p,Specifier s,const QCString &t=QCString()) override;
void insertExplicitTemplateInstance(ClassDef *instance,const QCString &spec) override;
void setIncludeFile(FileDef *fd,const QCString &incName,bool local,bool force) override;
void insertMember(MemberDef *) override;
void insertUsedFile(const FileDef *) override;
bool addExample(const QCString &anchor,const QCString &name, const QCString &file) override;
void mergeCategory(ClassDef *category) override;
void setFileDef(FileDef *fd) override;
void setModuleDef(ModuleDef *mod) override;
void setSubGrouping(bool enabled) override;
void setProtection(Protection p) override;
void setGroupDefForAllMembers(GroupDef *g,Grouping::GroupPri_t pri,const QCString &fileName,int startLine,bool hasDocs) override;
void addInnerCompound(Definition *d) override;
void addUsedClass(ClassDef *cd,const QCString &accessName,Protection prot) override;
void addUsedByClass(ClassDef *cd,const QCString &accessName,Protection prot) override;
void setIsStatic(bool b) override;
void setCompoundType(CompoundType t) override;
void setClassName(const QCString &name) override;
void setClassSpecifier(TypeSpecifier spec) override;
void addQualifiers(const StringVector &qualifiers) override;
void setTemplateArguments(const ArgumentList &al) override;
void setTemplateBaseClassNames(const TemplateNameMap &templateNames) override;
void setTemplateMaster(const ClassDef *tm) override;
void setImplicitTemplateInstance(bool b) override;
void setTypeConstraints(const ArgumentList &al) override;
void addMembersToTemplateInstance(const ClassDef *cd,const ArgumentList &templateArguments,const QCString &templSpec) override;
void makeTemplateArgument(bool b=TRUE) override;
void setCategoryOf(ClassDef *cd) override;
void setUsedOnly(bool b) override;
void setTagLessReference(const ClassDef *cd) override;
void setMetaData(const QCString &md) override;
void findSectionsInDocumentation() override;
void addMembersToMemberGroup() override;
void addListReferences() override;
void addTypeConstraints() override;
void computeAnchors() override;
void mergeMembers() override;
void sortMemberLists() override;
void distributeMemberGroupDocumentation() override;
void writeDocumentation(OutputList &ol) const override;
void writeDocumentationForInnerClasses(OutputList &ol) const override;
void writeMemberPages(OutputList &ol) const override;
void writeMemberList(OutputList &ol) const override;
void writeDeclaration(OutputList &ol,const MemberDef *md,bool inGroup,int indentLevel,
const ClassDef *inheritedFrom,const QCString &inheritId) const override;
void writeQuickMemberLinks(OutputList &ol,const MemberDef *md) const override;
void writeSummaryLinks(OutputList &ol) const override;
void reclassifyMember(MemberDefMutable *md,MemberType t) override;
void writeInlineDocumentation(OutputList &ol) const override;
void writeDeclarationLink(OutputList &ol,bool &found,
const QCString &header,bool localNames) const override;
void removeMemberFromLists(MemberDef *md) override;
void setAnonymousEnumType() override;
void countMembers() override;
void sortAllMembersList() override;
void addGroupedInheritedMembers(OutputList &ol,MemberListType lt,
const ClassDef *inheritedFrom,const QCString &inheritId) const override;
void writeTagFile(TextStream &) const override;
int countMembersIncludingGrouped(MemberListType lt,const ClassDef *inheritedFrom,bool additional) const override;
int countMemberDeclarations(MemberListType lt,const ClassDef *inheritedFrom,
MemberListType lt2,bool invert,bool showAlways,ClassDefSet &visitedClasses) const override;
void writeMemberDeclarations(OutputList &ol,ClassDefSet &visitedClasses,
MemberListType lt,const QCString &title,
const QCString &subTitle=QCString(),
bool showInline=FALSE,const ClassDef *inheritedFrom=nullptr,
MemberListType lt2=MemberListType::Invalid(),bool invert=FALSE,bool showAlways=FALSE) const override;
void setRequiresClause(const QCString &req) override;
// inheritance graph related members
CLASS_GRAPH_t hasInheritanceGraph() const override;
void overrideInheritanceGraph(CLASS_GRAPH_t e) override;
// collaboration graph related members
bool hasCollaborationGraph() const override;
void overrideCollaborationGraph(bool e) override;
private:
int countInheritedByNodes() const;
int countInheritsNodes() const;
int countInheritanceNodes() const;
void addUsedInterfaceClasses(MemberDef *md,const QCString &typeStr);
void showUsedFiles(OutputList &ol) const;
void writeDocumentationContents(OutputList &ol,const QCString &pageTitle) const;
void internalInsertMember(MemberDef *md,Protection prot,bool addToAllList);
void addMemberToList(MemberListType lt,MemberDef *md,bool isBrief);
void writeInheritedMemberDeclarations(OutputList &ol,ClassDefSet &visitedClasses,
MemberListType lt,MemberListType lt2,const QCString &title,
const ClassDef *inheritedFrom,bool invert,
bool showAlways) const;
void writeMemberDocumentation(OutputList &ol,MemberListType lt,const QCString &title,bool showInline=FALSE) const;
void writeSimpleMemberDocumentation(OutputList &ol,MemberListType lt) const;
void writePlainMemberDeclaration(OutputList &ol,MemberListType lt,bool inGroup,
int indentLevel,const ClassDef *inheritedFrom,const QCString &inheritId) const;
void writeBriefDescription(OutputList &ol,bool exampleFlag) const;
void writeDetailedDescription(OutputList &ol,const QCString &pageType,bool exampleFlag,
const QCString &title,const QCString &anchor=QCString()) const;
void writeIncludeFiles(OutputList &ol) const;
void writeIncludeFilesForSlice(OutputList &ol) const;
void writeInheritanceGraph(OutputList &ol) const;
void writeCollaborationGraph(OutputList &ol) const;
void writeMemberGroups(OutputList &ol,bool showInline=FALSE) const;
void writeNestedClasses(OutputList &ol,const QCString &title) const;
void writeInlineClasses(OutputList &ol) const;
void startMemberDeclarations(OutputList &ol) const;
void endMemberDeclarations(OutputList &ol) const;
void startMemberDocumentation(OutputList &ol) const;
void endMemberDocumentation(OutputList &ol) const;
void writeAuthorSection(OutputList &ol) const;
void writeMoreLink(OutputList &ol,const QCString &anchor) const;
void writeDetailedDocumentationBody(OutputList &ol) const;
int countAdditionalInheritedMembers() const;
void writeAdditionalInheritedMembers(OutputList &ol) const;
void addClassAttributes(OutputList &ol) const;
int countInheritedDecMembers(MemberListType lt,
const ClassDef *inheritedFrom,bool invert,bool showAlways,
ClassDefSet &visitedClasses) const;
void getTitleForMemberListType(MemberListType type,
QCString &title,QCString &subtitle) const;
void addTypeConstraint(const QCString &typeConstraint,const QCString &type);
void writeTemplateSpec(OutputList &ol,const Definition *d,
const QCString &type,SrcLangExt lang) const;
void mergeMembersFromBaseClasses(bool mergeVirtualBaseClass);
// PIMPL idiom
class IMPL;
std::unique_ptr<IMPL> m_impl;
};
std::unique_ptr<ClassDef> createClassDef(
const QCString &fileName,int startLine,int startColumn,
const QCString &name,ClassDef::CompoundType ct,
const QCString &ref,const QCString &fName,
bool isSymbol,bool isJavaEnum)
{
return std::make_unique<ClassDefImpl>(fileName,startLine,startColumn,name,ct,ref,fName,isSymbol,isJavaEnum);
}
//-----------------------------------------------------------------------------
class ClassDefAliasImpl : public DefinitionAliasMixin<ClassDef>
{
public:
ClassDefAliasImpl(const Definition *newScope,const ClassDef *cd)
: DefinitionAliasMixin(newScope,cd) { init(); }
~ClassDefAliasImpl() override { deinit(); }
NON_COPYABLE(ClassDefAliasImpl)
DefType definitionType() const override { return TypeClass; }
const ClassDef *getCdAlias() const { return toClassDef(getAlias()); }
std::unique_ptr<ClassDef> deepCopy(const QCString &name) const override {
return createClassDefAlias(getScope(),getCdAlias());
}
void moveTo(Definition *) override {}
CodeSymbolType codeSymbolType() const override
{ return getCdAlias()->codeSymbolType(); }
QCString getOutputFileBase() const override
{ return getCdAlias()->getOutputFileBase(); }
QCString getInstanceOutputFileBase() const override
{ return getCdAlias()->getInstanceOutputFileBase(); }
QCString getSourceFileBase() const override
{ return getCdAlias()->getSourceFileBase(); }
QCString getReference() const override
{ return getCdAlias()->getReference(); }
bool isReference() const override
{ return getCdAlias()->isReference(); }
bool isLocal() const override
{ return getCdAlias()->isLocal(); }
ClassLinkedRefMap getClasses() const override
{ return getCdAlias()->getClasses(); }
bool hasDocumentation() const override
{ return getCdAlias()->hasDocumentation(); }
bool hasDetailedDescription() const override
{ return getCdAlias()->hasDetailedDescription(); }
QCString collaborationGraphFileName() const override
{ return getCdAlias()->collaborationGraphFileName(); }
QCString inheritanceGraphFileName() const override
{ return getCdAlias()->inheritanceGraphFileName(); }
QCString displayName(bool includeScope=TRUE) const override
{ return makeDisplayName(this,includeScope); }
CompoundType compoundType() const override
{ return getCdAlias()->compoundType(); }
QCString compoundTypeString() const override
{ return getCdAlias()->compoundTypeString(); }
const BaseClassList &baseClasses() const override
{ return getCdAlias()->baseClasses(); }
const BaseClassList &subClasses() const override
{ return getCdAlias()->subClasses(); }
const MemberNameInfoLinkedMap &memberNameInfoLinkedMap() const override
{ return getCdAlias()->memberNameInfoLinkedMap(); }
Protection protection() const override
{ return getCdAlias()->protection(); }
bool isLinkableInProject() const override
{ return getCdAlias()->isLinkableInProject(); }
bool isLinkable() const override
{ return getCdAlias()->isLinkable(); }
bool isVisibleInHierarchy() const override
{ return getCdAlias()->isVisibleInHierarchy(); }
bool visibleInParentsDeclList() const override
{ return getCdAlias()->visibleInParentsDeclList(); }
const ArgumentList &templateArguments() const override
{ return getCdAlias()->templateArguments(); }
FileDef *getFileDef() const override
{ return getCdAlias()->getFileDef(); }
ModuleDef *getModuleDef() const override
{ return getCdAlias()->getModuleDef(); }
const MemberDef *getMemberByName(const QCString &s) const override
{ return getCdAlias()->getMemberByName(s); }
int isBaseClass(const ClassDef *bcd,bool followInstances,const QCString &templSpec) const override
{ return getCdAlias()->isBaseClass(bcd,followInstances,templSpec); }
bool isSubClass(ClassDef *bcd,int level=0) const override
{ return getCdAlias()->isSubClass(bcd,level); }
bool isAccessibleMember(const MemberDef *md) const override
{ return getCdAlias()->isAccessibleMember(md); }
const TemplateInstanceList &getTemplateInstances() const override
{ return getCdAlias()->getTemplateInstances(); }
const ClassDef *templateMaster() const override
{ return getCdAlias()->templateMaster(); }
bool isTemplate() const override
{ return getCdAlias()->isTemplate(); }
const IncludeInfo *includeInfo() const override
{ return getCdAlias()->includeInfo(); }
const UsesClassList &usedImplementationClasses() const override
{ return getCdAlias()->usedImplementationClasses(); }
const UsesClassList &usedByImplementationClasses() const override
{ return getCdAlias()->usedByImplementationClasses(); }
const ConstraintClassList &templateTypeConstraints() const override
{ return getCdAlias()->templateTypeConstraints(); }
bool isTemplateArgument() const override
{ return getCdAlias()->isTemplateArgument(); }
const Definition *findInnerCompound(const QCString &name) const override
{ return getCdAlias()->findInnerCompound(name); }
ArgumentLists getTemplateParameterLists() const override
{ return getCdAlias()->getTemplateParameterLists(); }
QCString qualifiedNameWithTemplateParameters(
const ArgumentLists *actualParams=nullptr,uint32_t *actualParamIndex=nullptr) const override
{ return makeQualifiedNameWithTemplateParameters(this,actualParams,actualParamIndex); }
bool isAbstract() const override
{ return getCdAlias()->isAbstract(); }
bool isObjectiveC() const override
{ return getCdAlias()->isObjectiveC(); }
bool isFortran() const override
{ return getCdAlias()->isFortran(); }
bool isCSharp() const override
{ return getCdAlias()->isCSharp(); }
bool isFinal() const override
{ return getCdAlias()->isFinal(); }
bool isSealed() const override
{ return getCdAlias()->isSealed(); }
bool isPublished() const override
{ return getCdAlias()->isPublished(); }
bool isExtension() const override
{ return getCdAlias()->isExtension(); }
bool isForwardDeclared() const override
{ return getCdAlias()->isForwardDeclared(); }
bool isInterface() const override
{ return getCdAlias()->isInterface(); }
ClassDef *categoryOf() const override
{ return getCdAlias()->categoryOf(); }
QCString className() const override
{ return getCdAlias()->className(); }
MemberList *getMemberList(MemberListType lt) const override
{ return getCdAlias()->getMemberList(lt); }
const MemberLists &getMemberLists() const override
{ return getCdAlias()->getMemberLists(); }
const MemberGroupList &getMemberGroups() const override
{ return getCdAlias()->getMemberGroups(); }
const TemplateNameMap &getTemplateBaseClassNames() const override
{ return getCdAlias()->getTemplateBaseClassNames(); }
bool isUsedOnly() const override
{ return getCdAlias()->isUsedOnly(); }
QCString anchor() const override
{ return getCdAlias()->anchor(); }
bool isEmbeddedInOuterScope() const override
{ return getCdAlias()->isEmbeddedInOuterScope(); }
bool isSimple() const override
{ return getCdAlias()->isSimple(); }
const ClassDef *tagLessReference() const override
{ return getCdAlias()->tagLessReference(); }
const MemberDef *isSmartPointer() const override
{ return getCdAlias()->isSmartPointer(); }
bool isJavaEnum() const override
{ return getCdAlias()->isJavaEnum(); }
QCString title() const override
{ return getCdAlias()->title(); }
QCString generatedFromFiles() const override
{ return getCdAlias()->generatedFromFiles(); }
const FileList &usedFiles() const override
{ return getCdAlias()->usedFiles(); }
const ArgumentList &typeConstraints() const override
{ return getCdAlias()->typeConstraints(); }
const ExampleList &getExamples() const override
{ return getCdAlias()->getExamples(); }
bool hasExamples() const override
{ return getCdAlias()->hasExamples(); }
QCString getMemberListFileName() const override
{ return getCdAlias()->getMemberListFileName(); }
bool subGrouping() const override
{ return getCdAlias()->subGrouping(); }
bool isSliceLocal() const override
{ return getCdAlias()->isSliceLocal(); }
bool hasNonReferenceSuperClass() const override
{ return getCdAlias()->hasNonReferenceSuperClass(); }
QCString requiresClause() const override
{ return getCdAlias()->requiresClause(); }
StringVector getQualifiers() const override
{ return getCdAlias()->getQualifiers(); }
bool containsOverload(const MemberDef *md) const override
{ return getCdAlias()->containsOverload(md); }
int countMembersIncludingGrouped(MemberListType lt,const ClassDef *inheritedFrom,bool additional) const override
{ return getCdAlias()->countMembersIncludingGrouped(lt,inheritedFrom,additional); }
int countMemberDeclarations(MemberListType lt,const ClassDef *inheritedFrom,
MemberListType lt2,bool invert,bool showAlways,ClassDefSet &visitedClasses) const override
{ return getCdAlias()->countMemberDeclarations(lt,inheritedFrom,lt2,invert,showAlways,visitedClasses); }
void writeDeclarationLink(OutputList &ol,bool &found,
const QCString &header,bool localNames) const override
{ getCdAlias()->writeDeclarationLink(ol,found,header,localNames); }
ClassDef *insertTemplateInstance(const QCString &fileName,int startLine,int startColumn,
const QCString &templSpec,bool &freshInstance) const override
{ return getCdAlias()->insertTemplateInstance(fileName,startLine,startColumn,templSpec,freshInstance); }
bool isImplicitTemplateInstance() const override
{ return getCdAlias()->isImplicitTemplateInstance(); }
void writeDocumentation(OutputList &ol) const override
{ getCdAlias()->writeDocumentation(ol); }
void writeDocumentationForInnerClasses(OutputList &ol) const override
{ getCdAlias()->writeDocumentationForInnerClasses(ol); }
void writeMemberPages(OutputList &ol) const override
{ getCdAlias()->writeMemberPages(ol); }
void writeMemberList(OutputList &ol) const override
{ getCdAlias()->writeMemberList(ol); }
void writeDeclaration(OutputList &ol,const MemberDef *md,bool inGroup,
int indentLevel, const ClassDef *inheritedFrom,const QCString &inheritId) const override
{ getCdAlias()->writeDeclaration(ol,md,inGroup,indentLevel,inheritedFrom,inheritId); }
void writeQuickMemberLinks(OutputList &ol,const MemberDef *md) const override
{ getCdAlias()->writeQuickMemberLinks(ol,md); }
void writeSummaryLinks(OutputList &ol) const override
{ getCdAlias()->writeSummaryLinks(ol); }
void writeInlineDocumentation(OutputList &ol) const override
{ getCdAlias()->writeInlineDocumentation(ol); }
void writeTagFile(TextStream &ol) const override
{ getCdAlias()->writeTagFile(ol); }
void writeMemberDeclarations(OutputList &ol,ClassDefSet &visitedClasses,
MemberListType lt,const QCString &title,
const QCString &subTitle=QCString(),
bool showInline=FALSE,const ClassDef *inheritedFrom=nullptr,
MemberListType lt2=MemberListType::Invalid(),bool invert=FALSE,bool showAlways=FALSE) const override
{ getCdAlias()->writeMemberDeclarations(ol,visitedClasses,lt,title,subTitle,showInline,inheritedFrom,lt2,invert,showAlways); }
void addGroupedInheritedMembers(OutputList &ol,MemberListType lt,
const ClassDef *inheritedFrom,const QCString &inheritId) const override
{ getCdAlias()->addGroupedInheritedMembers(ol,lt,inheritedFrom,inheritId); }
void updateBaseClasses(const BaseClassList &) override {}
void updateSubClasses(const BaseClassList &) override {}
};
std::unique_ptr<ClassDef> createClassDefAlias(const Definition *newScope,const ClassDef *cd)
{
auto acd = std::make_unique<ClassDefAliasImpl>(newScope,cd);
//printf("cd name=%s localName=%s qualifiedName=%s qualifiedNameWith=%s displayName()=%s\n",
// qPrint(acd->name()),qPrint(acd->localName()),qPrint(acd->qualifiedName()),
// qPrint(acd->qualifiedNameWithTemplateParameters()),qPrint(acd->displayName()));
return acd;
}
//-----------------------------------------------------------------------------
/** Private data associated with a ClassDef object. */
class ClassDefImpl::IMPL
{
public:
void init(const QCString &defFileName, const QCString &name,
const QCString &ctStr, const QCString &fName);
std::unique_ptr<ClassDefImpl::IMPL> deepCopy() const;
/*! file name that forms the base for the output file containing the
* class documentation. For compatibility with Qt (e.g. links via tag
* files) this name cannot be derived from the class name directly.
*/
QCString fileName;
/*! file name used for the list of all members */
QCString memberListFileName;
/*! file name used for the collaboration diagram */
QCString collabFileName;
/*! file name used for the inheritance graph */
QCString inheritFileName;
/*! Include information about the header file should be included
* in the documentation. 0 by default, set by setIncludeFile().
*/
std::unique_ptr<IncludeInfo> incInfo;
/*! List of base class (or super-classes) from which this class derives
* directly.
*/
BaseClassList inherits;
/*! List of sub-classes that directly derive from this class
*/
BaseClassList inheritedBy;
/*! Namespace this class is part of
* (this is the inner most namespace in case of nested namespaces)
*/
//NamespaceDef *nspace = nullptr;
/*! File this class is defined in */
FileDef *fileDef = nullptr;
/*! Module this class is defined in */
ModuleDef *moduleDef = nullptr;
/*! List of all members (including inherited members) */
MemberNameInfoLinkedMap allMemberNameInfoLinkedMap;
/*! Template arguments of this class */
ArgumentList tempArgs;
/*! Type constraints for template parameters */
ArgumentList typeConstraints;
/*! Files that were used for generating the class documentation. */
FileList files;
/*! Examples that use this class */
ExampleList examples;
/*! Holds the kind of "class" this is. */
ClassDef::CompoundType compType;
/*! The protection level in which this class was found.
* Typically Public, but for nested classes this can also be Protected
* or Private.
*/
Protection prot;
/*! The inner classes contained in this class. Will be 0 if there are
* no inner classes.
*/
ClassLinkedRefMap innerClasses;
/* classes for the collaboration diagram */
UsesClassList usesImplClassList;
UsesClassList usedByImplClassList;
ConstraintClassList constraintClassList;
/*! Template instances that exists of this class, the key in the
* dictionary is the template argument list.
*/
TemplateInstanceList templateInstances;
TemplateNameMap templBaseClassNames;
/*! The class this class is an instance of. */
const ClassDef *templateMaster = nullptr;
/*! local class name which could be a typedef'ed alias name. */
QCString className;
/*! If this class is a Objective-C category, then this points to the
* class which is extended.
*/
ClassDef *categoryOf = nullptr;
MemberLists memberLists;
/* user defined member groups */
MemberGroupList memberGroups;
/*! Is this an abstract class? */
bool isAbstract = false;
/*! Is the class part of an unnamed namespace? */
bool isStatic = false;
/*! TRUE if classes members are merged with those of the base classes. */
bool membersMerged = false;
/*! TRUE if the class is defined in a source file rather than a header file. */
bool isLocal = false;
bool isTemplArg = false;
/*! Does this class group its user-grouped members
* as a sub-section of the normal (public/protected/..)
* groups?
*/
bool subGrouping = false;
/** Reason of existence is a "use" relation */
bool usedOnly = false;
/** List of titles to use for the summary */
StringSet vhdlSummaryTitles;
/** Is this a simple (non-nested) C structure? */
bool isSimple = false;
/** Does this class overloaded the -> operator? */
const MemberDef *arrowOperator = nullptr;
const ClassDef *tagLessRef = nullptr;
/** Does this class represent a Java style enum? */
bool isJavaEnum = false;
TypeSpecifier spec;
QCString metaData;
/** C++20 requires clause */
QCString requiresClause;
StringVector qualifiers;
bool hasCollaborationGraph = false;
CLASS_GRAPH_t typeInheritanceGraph = CLASS_GRAPH_t::NO;
bool implicitTemplateInstance = false;
};
void ClassDefImpl::IMPL::init(const QCString &defFileName, const QCString &name,
const QCString &ctStr, const QCString &fName)
{
if (!fName.isEmpty())
{
fileName=stripExtension(fName);
}
else
{
fileName=ctStr+name;
}
prot=Protection::Public;
//nspace=nullptr;
fileDef=nullptr;
moduleDef=nullptr;
subGrouping=Config_getBool(SUBGROUPING);
templateMaster =nullptr;
isAbstract = FALSE;
isStatic = FALSE;
isTemplArg = FALSE;
membersMerged = FALSE;
categoryOf = nullptr;
usedOnly = FALSE;
isSimple = Config_getBool(INLINE_SIMPLE_STRUCTS);
arrowOperator = nullptr;
tagLessRef = nullptr;
spec=TypeSpecifier();
//QCString ns;
//extractNamespaceName(name,className,ns);
//printf("m_name=%s m_className=%s ns=%s\n",qPrint(m_name),qPrint(m_className),qPrint(ns));
// we cannot use getLanguage at this point, as setLanguage has not been called.
SrcLangExt lang = getLanguageFromFileName(defFileName);
if ((lang==SrcLangExt::Cpp || lang==SrcLangExt::ObjC) && guessSection(defFileName).isSource())
{
isLocal=TRUE;
}
else
{
isLocal=FALSE;
}
hasCollaborationGraph = Config_getBool(COLLABORATION_GRAPH);
typeInheritanceGraph = Config_getEnum(CLASS_GRAPH);
}
//-------------------------------------------------------------------------------------------
// constructs a new class definition
ClassDefImpl::ClassDefImpl(
const QCString &defFileName,int defLine,int defColumn,
const QCString &nm,CompoundType ct,
const QCString &lref,const QCString &fName,
bool isSymbol,bool isJavaEnum)
: DefinitionMixin(defFileName,defLine,defColumn,removeRedundantWhiteSpace(nm),nullptr,nullptr,isSymbol),
m_impl(std::make_unique<IMPL>())
{
setReference(lref);
m_impl->compType = ct;
m_impl->isJavaEnum = isJavaEnum;
QCString compTypeString = getCompoundTypeString(getLanguage(),ct,isJavaEnum);
m_impl->init(defFileName,name(),compTypeString,fName);
m_impl->memberListFileName = convertNameToFile(compTypeString+name()+"-members");
m_impl->collabFileName = convertNameToFile(m_impl->fileName+"_coll_graph");
m_impl->inheritFileName = convertNameToFile(m_impl->fileName+"_inherit_graph");
if (lref.isEmpty())
{
m_impl->fileName = convertNameToFile(m_impl->fileName);
}
}
std::unique_ptr<ClassDefImpl::IMPL> ClassDefImpl::IMPL::deepCopy() const
{
auto result = std::make_unique<ClassDefImpl::IMPL>();
result->memberListFileName = memberListFileName;
result->collabFileName = collabFileName;
result->inheritFileName = inheritFileName;
if (incInfo)
{
result->incInfo = std::make_unique<IncludeInfo>();
*(result->incInfo) = *incInfo;
}
result->inherits = inherits;
result->inheritedBy = inheritedBy;
result->fileDef = fileDef;
result->moduleDef = moduleDef;
result->tempArgs = tempArgs;
result->typeConstraints = typeConstraints;
result->files = files;
result->examples = examples;
result->compType = compType;
result->prot = prot;
result->usesImplClassList = usesImplClassList;
result->usedByImplClassList = usedByImplClassList;
result->constraintClassList = constraintClassList;
result->templateInstances = templateInstances;
result->templBaseClassNames = templBaseClassNames;
result->templateMaster = templateMaster;
result->className = className;
result->categoryOf = categoryOf;
result->isAbstract = isAbstract;
result->isStatic = isStatic;
result->membersMerged = membersMerged;
result->isLocal = isLocal;
result->isTemplArg = isTemplArg;
result->subGrouping = subGrouping;
result->usedOnly = usedOnly;
result->vhdlSummaryTitles = vhdlSummaryTitles;
result->isSimple = isSimple;
result->arrowOperator = arrowOperator;
result->tagLessRef = tagLessRef;
result->isJavaEnum = isJavaEnum;
result->spec = spec;
result->metaData = metaData;
result->requiresClause = requiresClause;
result->qualifiers = qualifiers;
result->hasCollaborationGraph = hasCollaborationGraph;
result->typeInheritanceGraph = typeInheritanceGraph;
return result;
}
std::unique_ptr<ClassDef> ClassDefImpl::deepCopy(const QCString &name) const
{
AUTO_TRACE("name='{}'",name);
auto result = std::make_unique<ClassDefImpl>(
getDefFileName(),getDefLine(),getDefColumn(),name,compoundType(),
std::string(),std::string(),true,m_impl->isJavaEnum);
// copy other members
result->m_impl = m_impl->deepCopy();
// set new file name
QCString compTypeString = getCompoundTypeString(getLanguage(),m_impl->compType,m_impl->isJavaEnum);
result->m_impl->fileName = compTypeString+name;
result->m_impl->memberListFileName = convertNameToFile(compTypeString+name+"-members");
result->m_impl->collabFileName = convertNameToFile(result->m_impl->fileName+"_coll_graph");
result->m_impl->inheritFileName = convertNameToFile(result->m_impl->fileName+"_inherit_graph");
result->m_impl->fileName = convertNameToFile(result->m_impl->fileName);
// deep copy nested classes
for (const auto &innerCd : m_impl->innerClasses)
{
QCString innerName = name+"::"+innerCd->localName();
if (Doxygen::classLinkedMap->find(innerName)==nullptr)
{
auto cd = Doxygen::classLinkedMap->add(innerName,innerCd->deepCopy(innerName));
result->addInnerCompound(cd);
ClassDefMutable *cdm = toClassDefMutable(cd);
if (cdm)
{
cdm->setOuterScope(result.get());
}
}
}
// copy all member list (and make deep copies of members)
for (auto &mni : m_impl->allMemberNameInfoLinkedMap)
{
for (auto &mi : *mni)
{
const MemberDef *md=mi->memberDef();
auto newMd = md->deepCopy();
if (newMd)
{
auto mmd = toMemberDefMutable(newMd.get());
AUTO_TRACE_ADD("Copying member {}",mmd->name());
mmd->moveTo(result.get());
result->internalInsertMember(newMd.get(),newMd->protection(),true);
// also add to the global list (which will own newMd)
MemberName *mn = Doxygen::memberNameLinkedMap->add(newMd->name());
mn->push_back(std::move(newMd));
}
}
}
return result;
}
void ClassDefImpl::moveTo(Definition *scope)
{
//printf("%s::moveTo(%s)\n",qPrint(name()),qPrint(scope->name()));
setOuterScope(scope);
if (scope->definitionType()==Definition::TypeFile)
{
m_impl->fileDef = toFileDef(scope);
}
else if (scope->definitionType()==Definition::TypeModule)
{
m_impl->moduleDef = toModuleDef(scope);
}
}
QCString ClassDefImpl::getMemberListFileName() const
{
return m_impl->memberListFileName;
}
QCString ClassDefImpl::displayName(bool includeScope) const
{
return makeDisplayName(this,includeScope);
}
// inserts a base/super class in the inheritance list
void ClassDefImpl::insertBaseClass(ClassDef *cd,const QCString &n,Protection p,
Specifier s,const QCString &t)
{
//printf("*** insert base class %s into %s\n",qPrint(cd->name()),qPrint(name()));
m_impl->inherits.emplace_back(cd,n,p,s,t);
m_impl->isSimple = FALSE;
}
// inserts a derived/sub class in the inherited-by list
void ClassDefImpl::insertSubClass(ClassDef *cd,Protection p,
Specifier s,const QCString &t)
{
//printf("*** insert sub class %s into %s\n",qPrint(cd->name()),qPrint(name()));
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
if (!extractPrivate && cd->protection()==Protection::Private) return;
m_impl->inheritedBy.emplace_back(cd,QCString(),p,s,t);
m_impl->isSimple = FALSE;
}
void ClassDefImpl::addMembersToMemberGroup()
{
for (auto &ml : m_impl->memberLists)
{
if (!ml->listType().isDetailed())
{
::addMembersToMemberGroup(ml.get(),&m_impl->memberGroups,this);
}
}
// add members inside sections to their groups
for (const auto &mg : m_impl->memberGroups)
{
if (mg->allMembersInSameSection() && m_impl->subGrouping)
{
//printf("addToDeclarationSection(%s)\n",qPrint(mg->header()));
mg->addToDeclarationSection();
}
}
}
// adds new member definition to the class
void ClassDefImpl::internalInsertMember(MemberDef *md,
Protection prot,
bool addToAllList
)
{
AUTO_TRACE("{} name={} isHidden={}",name(),md->name(),md->isHidden());
if (md->isHidden()) return;
if (getLanguage()==SrcLangExt::VHDL)
{
QCString title=theTranslator->trVhdlType(md->getVhdlSpecifiers(),FALSE);
m_impl->vhdlSummaryTitles.insert(title.str());
}
if (1 /*!isReference()*/) // changed to 1 for showing members of external
// classes when HAVE_DOT and UML_LOOK are enabled.
{
bool isSimple=FALSE;
/********************************************/
/* insert member in the declaration section */
/********************************************/
if (md->isRelated() && protectionLevelVisible(prot))
{
addMemberToList(MemberListType::Related(),md,TRUE);
}
else if (md->isFriend())
{
addMemberToList(MemberListType::Friends(),md,TRUE);
}
else
{
switch (md->memberType())
{
case MemberType::Service: // UNO IDL
addMemberToList(MemberListType::Services(),md,TRUE);
break;
case MemberType::Interface: // UNO IDL
addMemberToList(MemberListType::Interfaces(),md,TRUE);
break;
case MemberType::Signal: // Qt specific
addMemberToList(MemberListType::Signals(),md,TRUE);
break;
case MemberType::DCOP: // KDE2 specific
addMemberToList(MemberListType::DcopMethods(),md,TRUE);
break;
case MemberType::Property:
addMemberToList(MemberListType::Properties(),md,TRUE);
break;
case MemberType::Event:
addMemberToList(MemberListType::Events(),md,TRUE);
break;
case MemberType::Slot: // Qt specific
switch (prot)
{
case Protection::Protected:
case Protection::Package: // slots in packages are not possible!
addMemberToList(MemberListType::ProSlots(),md,TRUE);
break;
case Protection::Public:
addMemberToList(MemberListType::PubSlots(),md,TRUE);
break;
case Protection::Private:
addMemberToList(MemberListType::PriSlots(),md,TRUE);
break;
}
break;
default: // any of the other members
if (md->isStatic())
{
if (md->isVariable())
{
switch (prot)
{
case Protection::Protected:
addMemberToList(MemberListType::ProStaticAttribs(),md,TRUE);
break;
case Protection::Package:
addMemberToList(MemberListType::PacStaticAttribs(),md,TRUE);
break;
case Protection::Public:
addMemberToList(MemberListType::PubStaticAttribs(),md,TRUE);
break;
case Protection::Private:
addMemberToList(MemberListType::PriStaticAttribs(),md,TRUE);
break;
}
}
else // function
{
switch (prot)
{
case Protection::Protected:
addMemberToList(MemberListType::ProStaticMethods(),md,TRUE);
break;
case Protection::Package:
addMemberToList(MemberListType::PacStaticMethods(),md,TRUE);
break;
case Protection::Public:
addMemberToList(MemberListType::PubStaticMethods(),md,TRUE);
break;
case Protection::Private:
addMemberToList(MemberListType::PriStaticMethods(),md,TRUE);
break;
}
}
}
else // not static
{
if (md->isVariable())
{
switch (prot)
{
case Protection::Protected:
addMemberToList(MemberListType::ProAttribs(),md,TRUE);
break;
case Protection::Package:
addMemberToList(MemberListType::PacAttribs(),md,TRUE);
break;
case Protection::Public:
addMemberToList(MemberListType::PubAttribs(),md,TRUE);
isSimple=TRUE;
break;
case Protection::Private:
addMemberToList(MemberListType::PriAttribs(),md,TRUE);
break;
}
}
else if (md->isTypedef() || md->isEnumerate() || md->isEnumValue())
{
switch (prot)
{
case Protection::Protected:
addMemberToList(MemberListType::ProTypes(),md,TRUE);
break;
case Protection::Package:
addMemberToList(MemberListType::PacTypes(),md,TRUE);
break;
case Protection::Public:
addMemberToList(MemberListType::PubTypes(),md,TRUE);
isSimple=!md->isEnumerate() &&
!md->isEnumValue() &&
QCString(md->typeString()).find(")(")==-1; // func ptr typedef
break;
case Protection::Private:
addMemberToList(MemberListType::PriTypes(),md,TRUE);
break;
}
}
else // member function
{
switch (prot)
{
case Protection::Protected:
addMemberToList(MemberListType::ProMethods(),md,TRUE);
break;
case Protection::Package:
addMemberToList(MemberListType::PacMethods(),md,TRUE);
break;
case Protection::Public:
addMemberToList(MemberListType::PubMethods(),md,TRUE);
break;
case Protection::Private:
addMemberToList(MemberListType::PriMethods(),md,TRUE);
break;
}
}
}
break;
}
}
if (!isSimple) // not a simple field -> not a simple struct
{
m_impl->isSimple = FALSE;
}
//printf("adding %s simple=%d total_simple=%d\n",qPrint(name()),isSimple,m_impl->isSimple);
/*******************************************************/
/* insert member in the detailed documentation section */
/*******************************************************/
if ((md->isRelated() && protectionLevelVisible(prot)) || md->isFriend())
{
addMemberToList(MemberListType::RelatedMembers(),md,FALSE);
}
else if (md->isFunction() &&
md->protection()==Protection::Private &&
(md->virtualness()!=Specifier::Normal || md->isOverride() || md->isFinal()) &&
Config_getBool(EXTRACT_PRIV_VIRTUAL))
{
addMemberToList(MemberListType::FunctionMembers(),md,FALSE);
}
else
{
switch (md->memberType())
{
case MemberType::Service: // UNO IDL
addMemberToList(MemberListType::ServiceMembers(),md,FALSE);
break;
case MemberType::Interface: // UNO IDL
addMemberToList(MemberListType::InterfaceMembers(),md,FALSE);
break;
case MemberType::Property:
addMemberToList(MemberListType::PropertyMembers(),md,FALSE);
break;
case MemberType::Event:
addMemberToList(MemberListType::EventMembers(),md,FALSE);
break;
case MemberType::Signal: // fall through
case MemberType::DCOP:
addMemberToList(MemberListType::FunctionMembers(),md,FALSE);
break;
case MemberType::Slot:
if (protectionLevelVisible(prot))
{
addMemberToList(MemberListType::FunctionMembers(),md,FALSE);
}
break;
default: // any of the other members
if (protectionLevelVisible(prot))
{
switch (md->memberType())
{
case MemberType::Typedef:
addMemberToList(MemberListType::TypedefMembers(),md,FALSE);
break;
case MemberType::Enumeration:
addMemberToList(MemberListType::EnumMembers(),md,FALSE);
break;
case MemberType::EnumValue:
addMemberToList(MemberListType::EnumValMembers(),md,FALSE);
break;
case MemberType::Function:
if (md->isConstructor() || md->isDestructor())
{
m_impl->memberLists.get(MemberListType::Constructors(),MemberListContainer::Class)->push_back(md);
}
else
{
addMemberToList(MemberListType::FunctionMembers(),md,FALSE);
}
break;
case MemberType::Variable:
addMemberToList(MemberListType::VariableMembers(),md,FALSE);
break;
case MemberType::Define:
warn(md->getDefFileName(),md->getDefLine()-1,"A define (%s) cannot be made a member of %s",
qPrint(md->name()), qPrint(this->name()));
break;
default:
err("Unexpected member type '%s' found!\n",qPrint(md->memberTypeName()));
}
}
break;
}
}
/*************************************************/
/* insert member in the appropriate member group */
/*************************************************/
// Note: this must be done AFTER inserting the member in the
// regular groups
//addMemberToGroup(md,groupId);
}
if (md->virtualness()==Specifier::Pure)
{
m_impl->isAbstract=true;
}
if (md->name()=="operator->")
{
m_impl->arrowOperator=md;
}
if (addToAllList &&
!(Config_getBool(HIDE_FRIEND_COMPOUNDS) &&
md->isFriend() &&
(QCString(md->typeString())=="friend class" ||
QCString(md->typeString())=="friend struct" ||
QCString(md->typeString())=="friend union")))
{
//printf("=======> adding member %s to class %s\n",qPrint(md->name()),qPrint(name()));
MemberNameInfo *mni = m_impl->allMemberNameInfoLinkedMap.add(md->name());
mni->push_back(std::make_unique<MemberInfo>(md,prot,md->virtualness(),false,false));
}
}
void ClassDefImpl::insertMember(MemberDef *md)
{
internalInsertMember(md,md->protection(),TRUE);
}
// compute the anchors for all members
void ClassDefImpl::computeAnchors()
{
for (auto &ml : m_impl->memberLists)
{
if (!ml->listType().isDetailed())
{
ml->setAnchors();
}
}
for (const auto &mg : m_impl->memberGroups)
{
mg->setAnchors();
}
}
void ClassDefImpl::distributeMemberGroupDocumentation()
{
for (const auto &mg : m_impl->memberGroups)
{
mg->distributeMemberGroupDocumentation();
}
}
void ClassDefImpl::findSectionsInDocumentation()
{
docFindSections(briefDescription(),this,docFile());
docFindSections(documentation(),this,docFile());
docFindSections(inbodyDocumentation(),this,docFile());
for (const auto &mg : m_impl->memberGroups)
{
mg->findSectionsInDocumentation(this);
}
for (auto &ml : m_impl->memberLists)
{
if (!ml->listType().isDetailed())
{
ml->findSectionsInDocumentation(this);
}
}
}
// add a file name to the used files set
void ClassDefImpl::insertUsedFile(const FileDef *fd)
{
if (fd==nullptr) return;
auto it = std::find(m_impl->files.begin(),m_impl->files.end(),fd);
if (it==m_impl->files.end())
{
m_impl->files.push_back(fd);
}
for (const auto &ti : m_impl->templateInstances)
{
ClassDefMutable *cdm = toClassDefMutable(ti.classDef);
if (cdm)
{
cdm->insertUsedFile(fd);
}
}
}
static void writeInheritanceSpecifier(OutputList &ol,const BaseClassDef &bcd)
{
if (bcd.prot!=Protection::Public || bcd.virt!=Specifier::Normal)
{
ol.startTypewriter();
ol.docify(" [");
StringVector sl;
if (bcd.prot==Protection::Protected) sl.emplace_back("protected");
else if (bcd.prot==Protection::Private) sl.emplace_back("private");
if (bcd.virt==Specifier::Virtual) sl.emplace_back("virtual");
bool first=true;
for (const auto &s : sl)
{
if (!first) ol.docify(", ");
ol.docify(s.c_str());
first=false;
}
ol.docify("]");
ol.endTypewriter();
}
}
void ClassDefImpl::setIncludeFile(FileDef *fd,
const QCString &includeName,bool local, bool force)
{
//printf("ClassDefImpl::setIncludeFile(%p,%s,%d,%d)\n",fd,includeName,local,force);
if (!m_impl->incInfo) m_impl->incInfo = std::make_unique<IncludeInfo>();
if ((!includeName.isEmpty() && m_impl->incInfo->includeName.isEmpty()) ||
(fd!=nullptr && m_impl->incInfo->fileDef==nullptr)
)
{
//printf("Setting file info\n");
m_impl->incInfo->fileDef = fd;
m_impl->incInfo->includeName = includeName;
m_impl->incInfo->kind = local ? IncludeKind::IncludeLocal : IncludeKind::IncludeSystem;
}
if (force && !includeName.isEmpty())
{
m_impl->incInfo->includeName = includeName;
m_impl->incInfo->kind = local ? IncludeKind::IncludeLocal : IncludeKind::IncludeSystem;
}
}
// TODO: fix this: a nested template class can have multiple outer templates
//ArgumentList *ClassDefImpl::outerTemplateArguments() const
//{
// int ti;
// ClassDef *pcd=nullptr;
// int pi=0;
// if (m_impl->tempArgs) return m_impl->tempArgs;
// // find the outer most class scope
// while ((ti=name().find("::",pi))!=-1 &&
// (pcd=getClass(name().left(ti)))==0
// ) pi=ti+2;
// if (pcd)
// {
// return pcd->templateArguments();
// }
// return nullptr;
//}
static void searchTemplateSpecs(/*in*/ const Definition *d,
/*out*/ ArgumentLists &result,
/*out*/ QCString &name,
/*in*/ SrcLangExt lang)
{
if (d->definitionType()==Definition::TypeClass)
{
if (d->getOuterScope())
{
searchTemplateSpecs(d->getOuterScope(),result,name,lang);
}
const ClassDef *cd=toClassDef(d);
if (!name.isEmpty()) name+="::";
QCString clName = d->localName();
if (clName.endsWith("-p"))
{
clName = clName.left(clName.length()-2);
}
name+=clName;
bool isSpecialization = d->localName().find('<')!=-1;
if (!cd->templateArguments().empty())
{
result.push_back(cd->templateArguments());
if (!isSpecialization)
{
name+=tempArgListToString(cd->templateArguments(),lang);
}
}
}
else
{
name+=d->qualifiedName();
}
}
void ClassDefImpl::writeTemplateSpec(OutputList &ol,const Definition *d,
const QCString &type,SrcLangExt lang) const
{
ArgumentLists specs;
QCString name;
searchTemplateSpecs(d,specs,name,lang);
if (!specs.empty()) // class has template scope specifiers
{
ol.startCompoundTemplateParams();
for (const ArgumentList &al : specs)
{
ol.docify("template<");
auto it = al.begin();
while (it!=al.end())
{
Argument a = *it;
linkifyText(TextGeneratorOLImpl(ol), // out
d, // scope
getFileDef(), // fileScope
this, // self
a.type, // text
FALSE // autoBreak
);
if (!a.name.isEmpty())
{
ol.docify(" ");
ol.docify(a.name);
}
if (a.defval.length()!=0)
{
ol.docify(" = ");
ol.docify(a.defval);
}
++it;
if (it!=al.end()) ol.docify(", ");
}
ol.docify(">");
ol.lineBreak();
}
if (!m_impl->requiresClause.isEmpty())
{
ol.docify("requires ");
linkifyText(TextGeneratorOLImpl(ol), // out
d, // scope
getFileDef(), // fileScope
this, // self
m_impl->requiresClause, // text
FALSE // autoBreak
);
ol.lineBreak();
}
ol.docify(type.lower()+" "+name);
ol.endCompoundTemplateParams();
}
}
void ClassDefImpl::writeBriefDescription(OutputList &ol,bool exampleFlag) const
{
if (hasBriefDescription())
{
ol.startParagraph();
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Man);
ol.writeString(" - ");
ol.popGeneratorState();
ol.generateDoc(briefFile(),briefLine(),this,nullptr,
briefDescription(),TRUE,FALSE,QCString(),
TRUE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
ol.pushGeneratorState();
ol.disable(OutputType::RTF);
ol.writeString(" \n");
ol.enable(OutputType::RTF);
ol.popGeneratorState();
if (hasDetailedDescription() || exampleFlag)
{
writeMoreLink(ol,anchor());
}
ol.endParagraph();
}
ol.writeSynopsis();
}
void ClassDefImpl::writeDetailedDocumentationBody(OutputList &ol) const
{
bool repeatBrief = Config_getBool(REPEAT_BRIEF);
ol.startTextBlock();
if (getLanguage()==SrcLangExt::Cpp)
{
writeTemplateSpec(ol,this,compoundTypeString(),getLanguage());
}
// repeat brief description
if (!briefDescription().isEmpty() && repeatBrief)
{
ol.generateDoc(briefFile(),briefLine(),this,nullptr,briefDescription(),FALSE,FALSE,
QCString(),FALSE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
}
if (!briefDescription().isEmpty() && repeatBrief &&
!documentation().isEmpty())
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.writeString("\n\n");
ol.popGeneratorState();
}
// write documentation
if (!documentation().isEmpty())
{
ol.generateDoc(docFile(),docLine(),this,nullptr,documentation(),TRUE,FALSE,
QCString(),FALSE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
}
// write type constraints
writeTypeConstraints(ol,this,m_impl->typeConstraints);
// write examples
if (hasExamples())
{
ol.startExamples();
ol.startDescForItem();
writeExamples(ol,m_impl->examples);
ol.endDescForItem();
ol.endExamples();
}
writeSourceDef(ol);
ol.endTextBlock();
}
bool ClassDefImpl::hasDetailedDescription() const
{
bool repeatBrief = Config_getBool(REPEAT_BRIEF);
bool sourceBrowser = Config_getBool(SOURCE_BROWSER);
return ((!briefDescription().isEmpty() && repeatBrief) ||
!documentation().isEmpty() ||
(sourceBrowser && getStartBodyLine()!=-1 && getBodyDef()));
}
// write the detailed description for this class
void ClassDefImpl::writeDetailedDescription(OutputList &ol, const QCString &/*pageType*/, bool exampleFlag,
const QCString &title,const QCString &anchor) const
{
if (hasDetailedDescription() || exampleFlag)
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.writeRuler();
ol.popGeneratorState();
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.writeAnchor(QCString(),anchor.isEmpty() ? QCString("details") : anchor);
ol.popGeneratorState();
if (!anchor.isEmpty())
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.disable(OutputType::Man);
ol.writeAnchor(getOutputFileBase(),anchor);
ol.popGeneratorState();
}
ol.startGroupHeader();
ol.parseText(title);
ol.endGroupHeader();
writeDetailedDocumentationBody(ol);
}
else
{
//writeTemplateSpec(ol,this,pageType);
}
}
QCString ClassDefImpl::generatedFromFiles() const
{
QCString result;
SrcLangExt lang = getLanguage();
size_t numFiles = m_impl->files.size();
if (lang==SrcLangExt::Fortran)
{
result = theTranslator->trGeneratedFromFilesFortran(
getLanguage()==SrcLangExt::ObjC && m_impl->compType==Interface ? Class : m_impl->compType,
numFiles==1);
}
else if (isJavaEnum())
{
result = theTranslator->trEnumGeneratedFromFiles(numFiles==1);
}
else if (m_impl->compType==Service)
{
result = theTranslator->trServiceGeneratedFromFiles(numFiles==1);
}
else if (m_impl->compType==Singleton)
{
result = theTranslator->trSingletonGeneratedFromFiles(numFiles==1);
}
else
{
result = theTranslator->trGeneratedFromFiles(
getLanguage()==SrcLangExt::ObjC && m_impl->compType==Interface ? Class : m_impl->compType,
numFiles==1);
}
return result;
}
void ClassDefImpl::showUsedFiles(OutputList &ol) const
{
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.writeRuler();
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Docbook);
ol.startParagraph();
ol.parseText(generatedFromFiles());
ol.endParagraph();
ol.popGeneratorState();
ol.disable(OutputType::Docbook);
ol.parseText(generatedFromFiles());
ol.enable(OutputType::Docbook);
bool first=TRUE;
for (const auto &fd : m_impl->files)
{
if (first)
{
first=FALSE;
ol.startItemList();
}
ol.startItemListItem();
QCString path=fd->getPath();
if (Config_getBool(FULL_PATH_NAMES))
{
ol.docify(stripFromPath(path));
}
QCString fname = fd->name();
if (!fd->getVersion().isEmpty()) // append version if available
{
fname += " (" + fd->getVersion() + ")";
}
// for HTML
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
if (fd->generateSourceFile())
{
ol.writeObjectLink(QCString(),fd->getSourceFileBase(),QCString(),fname);
}
else if (fd->isLinkable())
{
ol.writeObjectLink(fd->getReference(),fd->getOutputFileBase(),QCString(),fname);
}
else
{
ol.startBold();
ol.docify(fname);
ol.endBold();
}
ol.popGeneratorState();
// for other output formats
ol.pushGeneratorState();
ol.disable(OutputType::Html);
if (fd->isLinkable())
{
ol.writeObjectLink(fd->getReference(),fd->getOutputFileBase(),QCString(),fname);
}
else
{
ol.docify(fname);
}
ol.popGeneratorState();
ol.endItemListItem();
}
if (!first) ol.endItemList();
ol.popGeneratorState();
}
int ClassDefImpl::countInheritedByNodes() const
{
int count=0;
for (const auto &ibcd : m_impl->inheritedBy)
{
const ClassDef *icd=ibcd.classDef;
if ( icd->isVisibleInHierarchy()) count++;
}
return count;
}
int ClassDefImpl::countInheritsNodes() const
{
int count=0;
for (const auto &ibcd : m_impl->inherits)
{
const ClassDef *icd=ibcd.classDef;
if ( icd->isVisibleInHierarchy()) count++;
}
return count;
}
int ClassDefImpl::countInheritanceNodes() const
{
return countInheritedByNodes()+countInheritsNodes();
}
void ClassDefImpl::writeInheritanceGraph(OutputList &ol) const
{
bool haveDot = Config_getBool(HAVE_DOT);
auto classGraph = m_impl->typeInheritanceGraph;
if (classGraph == CLASS_GRAPH_t::NO) return;
// count direct inheritance relations
int count=countInheritanceNodes();
bool renderDiagram = FALSE;
if (haveDot && (classGraph==CLASS_GRAPH_t::YES || classGraph==CLASS_GRAPH_t::GRAPH))
// write class diagram using dot
{
DotClassGraph inheritanceGraph(this,GraphType::Inheritance);
if (inheritanceGraph.isTooBig())
{
warn_uncond("Inheritance graph for '%s' not generated, too many nodes (%d), threshold is %d. Consider increasing DOT_GRAPH_MAX_NODES.\n",
qPrint(name()), inheritanceGraph.numNodes(), Config_getInt(DOT_GRAPH_MAX_NODES));
}
else if (!inheritanceGraph.isTrivial())
{
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.startDotGraph();
ol.parseText(theTranslator->trClassDiagram(displayName()));
ol.endDotGraph(inheritanceGraph);
ol.popGeneratorState();
renderDiagram = TRUE;
}
}
else if ((classGraph==CLASS_GRAPH_t::YES || classGraph==CLASS_GRAPH_t::GRAPH || classGraph==CLASS_GRAPH_t::BUILTIN) && count>0)
// write class diagram using built-in generator
{
ClassDiagram diagram(this); // create a diagram of this class.
ol.startClassDiagram();
ol.disable(OutputType::Man);
ol.parseText(theTranslator->trClassDiagram(displayName()));
ol.enable(OutputType::Man);
ol.endClassDiagram(diagram,getOutputFileBase(),displayName());
renderDiagram = TRUE;
}
if (renderDiagram) // if we already show the inheritance relations graphically,
// then hide the text version
{
ol.disableAllBut(OutputType::Man);
}
count = countInheritsNodes();
if (count>0)
{
auto replaceFunc = [this,&ol](size_t entryIndex)
{
for (size_t index=0; index<m_impl->inherits.size() ; index++)
{
const BaseClassDef &bcd=m_impl->inherits[index];
const ClassDef *cd=bcd.classDef;
if (cd->isVisibleInHierarchy()) // filter on the class we want to show
{
if (index==entryIndex) // found the requested index
{
// use the class name but with the template arguments as given
// in the inheritance relation
QCString displayName = insertTemplateSpecifierInScope(
cd->displayName(),bcd.templSpecifiers);
if (cd->isLinkable())
{
ol.writeObjectLink(cd->getReference(),
cd->getOutputFileBase(),
cd->anchor(),
displayName);
}
else
{
ol.docify(displayName);
}
return;
}
}
}
};
ol.startParagraph();
writeMarkerList(ol,
theTranslator->trInheritsList(count).str(),
static_cast<size_t>(count),
replaceFunc);
ol.endParagraph();
}
// write subclasses
count = countInheritedByNodes();
if (count>0)
{
auto replaceFunc = [this,&ol](size_t entryIndex)
{
for (size_t index=0; index<m_impl->inheritedBy.size() ; index++)
{
const BaseClassDef &bcd=m_impl->inheritedBy[index];
const ClassDef *cd=bcd.classDef;
if (cd->isVisibleInHierarchy()) // filter on the class we want to show
{
if (index==entryIndex) // found the requested index
{
if (cd->isLinkable())
{
ol.writeObjectLink(cd->getReference(),cd->getOutputFileBase(),cd->anchor(),cd->displayName());
writeInheritanceSpecifier(ol,bcd);
}
else
{
ol.docify(cd->displayName());
}
return;
}
}
}
};
ol.startParagraph();
writeMarkerList(ol,
theTranslator->trInheritedByList(count).str(),
static_cast<size_t>(count),
replaceFunc);
ol.endParagraph();
}
if (renderDiagram)
{
ol.enableAll();
}
}
void ClassDefImpl::writeCollaborationGraph(OutputList &ol) const
{
if (Config_getBool(HAVE_DOT) && m_impl->hasCollaborationGraph /*&& Config_getBool(COLLABORATION_GRAPH)*/)
{
DotClassGraph usageImplGraph(this,GraphType::Collaboration);
if (usageImplGraph.isTooBig())
{
warn_uncond("Collaboration graph for '%s' not generated, too many nodes (%d), threshold is %d. Consider increasing DOT_GRAPH_MAX_NODES.\n",
qPrint(name()), usageImplGraph.numNodes(), Config_getInt(DOT_GRAPH_MAX_NODES));
}
else if (!usageImplGraph.isTrivial())
{
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.startDotGraph();
ol.parseText(theTranslator->trCollaborationDiagram(displayName()));
ol.endDotGraph(usageImplGraph);
ol.popGeneratorState();
}
}
}
void ClassDefImpl::writeIncludeFilesForSlice(OutputList &ol) const
{
if (m_impl->incInfo)
{
QCString nm;
const StringVector &paths = Config_getList(STRIP_FROM_PATH);
if (!paths.empty() && m_impl->incInfo->fileDef)
{
QCString abs = m_impl->incInfo->fileDef->absFilePath();
QCString potential;
size_t length = 0;
for (const auto &s : paths)
{
FileInfo info(s);
if (info.exists())
{
QCString prefix = info.absFilePath();
if (prefix.at(prefix.length() - 1) != '/')
{
prefix += '/';
}
if (prefix.length() > length &&
qstricmp(abs.left(prefix.length()).data(), prefix.data()) == 0) // case insensitive compare
{
length = prefix.length();
potential = abs.right(abs.length() - prefix.length());
}
}
}
if (length > 0)
{
nm = potential;
}
}
if (nm.isEmpty())
{
nm = m_impl->incInfo->includeName;
}
ol.startParagraph();
ol.docify(theTranslator->trDefinedIn()+" ");
ol.startTypewriter();
ol.docify("<");
if (m_impl->incInfo->fileDef)
{
ol.writeObjectLink(QCString(),m_impl->incInfo->fileDef->includeName(),QCString(),nm);
}
else
{
ol.docify(nm);
}
ol.docify(">");
ol.endTypewriter();
ol.endParagraph();
}
// Write a summary of the Slice definition including metadata.
ol.startParagraph();
ol.startTypewriter();
if (!m_impl->metaData.isEmpty())
{
ol.docify(m_impl->metaData);
ol.lineBreak();
}
if (m_impl->spec.isLocal())
{
ol.docify("local ");
}
if (m_impl->spec.isInterface())
{
ol.docify("interface ");
}
else if (m_impl->spec.isStruct())
{
ol.docify("struct ");
}
else if (m_impl->spec.isException())
{
ol.docify("exception ");
}
else
{
ol.docify("class ");
}
ol.docify(stripScope(name()));
if (!m_impl->inherits.empty())
{
if (m_impl->spec.isInterface() || m_impl->spec.isException())
{
ol.docify(" extends ");
bool first=true;
for (const auto &ibcd : m_impl->inherits)
{
if (!first) ol.docify(", ");
ClassDef *icd = ibcd.classDef;
ol.docify(icd->name());
first=false;
}
}
else
{
// Must be a class.
bool implements = false;
for (const auto &ibcd : m_impl->inherits)
{
ClassDef *icd = ibcd.classDef;
if (icd->isInterface())
{
implements = true;
}
else
{
ol.docify(" extends ");
ol.docify(icd->name());
}
}
if (implements)
{
ol.docify(" implements ");
bool first = true;
for (const auto &ibcd : m_impl->inherits)
{
ClassDef *icd = ibcd.classDef;
if (icd->isInterface())
{
if (!first) ol.docify(", ");
first = false;
ol.docify(icd->name());
}
}
}
}
}
ol.docify(" { ... }");
ol.endTypewriter();
ol.endParagraph();
}
void ClassDefImpl::writeIncludeFiles(OutputList &ol) const
{
if (m_impl->incInfo /*&& Config_getBool(SHOW_HEADERFILE)*/)
{
SrcLangExt lang = getLanguage();
QCString nm=m_impl->incInfo->includeName.isEmpty() ?
(m_impl->incInfo->fileDef ?
m_impl->incInfo->fileDef->docName() : QCString()
) :
m_impl->incInfo->includeName;
if (!nm.isEmpty())
{
ol.startParagraph();
ol.startTypewriter();
ol.docify(::includeStatement(lang,m_impl->incInfo->kind));
ol.docify(::includeOpen(lang,m_impl->incInfo->kind));
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.docify(nm);
ol.disableAllBut(OutputType::Html);
ol.enable(OutputType::Html);
if (m_impl->incInfo->fileDef)
{
ol.writeObjectLink(QCString(),m_impl->incInfo->fileDef->includeName(),QCString(),nm);
}
else
{
ol.docify(nm);
}
ol.popGeneratorState();
ol.docify(::includeClose(lang,m_impl->incInfo->kind));
ol.endTypewriter();
ol.endParagraph();
}
}
}
void ClassDefImpl::writeMemberGroups(OutputList &ol,bool showInline) const
{
// write user defined member groups
for (const auto &mg : m_impl->memberGroups)
{
if (!mg->allMembersInSameSection() || !m_impl->subGrouping) // group is in its own section
{
mg->writeDeclarations(ol,this,nullptr,nullptr,nullptr,nullptr,showInline);
}
else // add this group to the corresponding member section
{
//printf("addToDeclarationSection(%s)\n",qPrint(mg->header()));
//mg->addToDeclarationSection();
}
}
}
void ClassDefImpl::writeNestedClasses(OutputList &ol,const QCString &title) const
{
// nested classes
m_impl->innerClasses.writeDeclaration(ol,nullptr,title,TRUE);
}
void ClassDefImpl::writeInlineClasses(OutputList &ol) const
{
m_impl->innerClasses.writeDocumentation(ol,this);
}
void ClassDefImpl::startMemberDocumentation(OutputList &ol) const
{
//printf("%s: ClassDefImpl::startMemberDocumentation()\n",qPrint(name()));
if (Config_getBool(SEPARATE_MEMBER_PAGES))
{
ol.disable(OutputType::Html);
Doxygen::suppressDocWarnings = TRUE;
}
}
void ClassDefImpl::endMemberDocumentation(OutputList &ol) const
{
//printf("%s: ClassDefImpl::endMemberDocumentation()\n",qPrint(name()));
if (Config_getBool(SEPARATE_MEMBER_PAGES))
{
ol.enable(OutputType::Html);
Doxygen::suppressDocWarnings = FALSE;
}
}
void ClassDefImpl::startMemberDeclarations(OutputList &ol) const
{
//printf("%s: ClassDefImpl::startMemberDeclarations()\n",qPrint(name()));
ol.startMemberSections();
}
void ClassDefImpl::endMemberDeclarations(OutputList &ol) const
{
//printf("%s: ClassDefImpl::endMemberDeclarations()\n",qPrint(name()));
bool inlineInheritedMembers = Config_getBool(INLINE_INHERITED_MEMB);
if (!inlineInheritedMembers && countAdditionalInheritedMembers()>0)
{
ol.startMemberHeader("inherited");
ol.parseText(theTranslator->trAdditionalInheritedMembers());
ol.endMemberHeader();
writeAdditionalInheritedMembers(ol);
}
ol.endMemberSections();
}
void ClassDefImpl::writeAuthorSection(OutputList &ol) const
{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Man);
ol.writeString("\n");
ol.startGroupHeader();
ol.parseText(theTranslator->trAuthor(TRUE,TRUE));
ol.endGroupHeader();
ol.parseText(theTranslator->trGeneratedAutomatically(Config_getString(PROJECT_NAME)));
ol.popGeneratorState();
}
void ClassDefImpl::writeSummaryLinks(OutputList &ol) const
{
static bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
bool first=TRUE;
SrcLangExt lang = getLanguage();
if (lang!=SrcLangExt::VHDL)
{
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
if (lde->kind()==LayoutDocEntry::ClassNestedClasses &&
m_impl->innerClasses.declVisible()
)
{
for (const auto &innerCd : m_impl->innerClasses)
{
if (!innerCd->isAnonymous() &&
!innerCd->isExtension() &&
(innerCd->protection()!=Protection::Private || extractPrivate) &&
innerCd->visibleInParentsDeclList()
)
{
const LayoutDocEntrySection *ls = (const LayoutDocEntrySection*)lde.get();
ol.writeSummaryLink(QCString(),"nested-classes",ls->title(lang),first);
first=FALSE;
break;
}
}
}
else if (lde->kind()==LayoutDocEntry::ClassAllMembersLink &&
!m_impl->allMemberNameInfoLinkedMap.empty() &&
!Config_getBool(OPTIMIZE_OUTPUT_FOR_C)
)
{
ol.writeSummaryLink(getMemberListFileName(),"all-members-list",theTranslator->trListOfAllMembers(),first);
first=FALSE;
}
else if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
MemberList * ml = getMemberList(lmd->type);
if (ml && ml->declVisible())
{
ol.writeSummaryLink(QCString(),ml->listType().toLabel(),lmd->title(lang),first);
first=FALSE;
}
}
}
}
}
else // VDHL only
{
for (const auto &s : m_impl->vhdlSummaryTitles)
{
ol.writeSummaryLink(QCString(),convertToId(QCString(s)),QCString(s),first);
first=FALSE;
}
}
if (!first)
{
ol.writeString(" </div>\n");
}
ol.popGeneratorState();
}
void ClassDefImpl::writeTagFile(TextStream &tagFile) const
{
if (!isLinkableInProject() || isArtificial()) return;
tagFile << " <compound kind=\"";
if (isFortran() && (compoundTypeString() == "type"))
tagFile << "struct";
else
tagFile << compoundTypeString();
tagFile << "\"";
if (isObjectiveC()) { tagFile << " objc=\"yes\""; }
tagFile << ">\n";
tagFile << " <name>" << convertToXML(name()) << "</name>\n";
QCString fn = getOutputFileBase();
addHtmlExtensionIfMissing(fn);
tagFile << " <filename>" << convertToXML(fn) << "</filename>\n";
if (!anchor().isEmpty())
{
tagFile << " <anchor>" << convertToXML(anchor()) << "</anchor>\n";
}
QCString idStr = id();
if (!idStr.isEmpty())
{
tagFile << " <clangid>" << convertToXML(idStr) << "</clangid>\n";
}
for (const Argument &a : m_impl->tempArgs)
{
tagFile << " <templarg>" << convertToXML(a.type);
if (!a.name.isEmpty())
{
tagFile << " " << convertToXML(a.name);
}
tagFile << "</templarg>\n";
}
for (const auto &ibcd : m_impl->inherits)
{
ClassDef *cd=ibcd.classDef;
if (cd && cd->isLinkable())
{
tagFile << " <base";
if (ibcd.prot==Protection::Protected)
{
tagFile << " protection=\"protected\"";
}
else if (ibcd.prot==Protection::Private)
{
tagFile << " protection=\"private\"";
}
if (ibcd.virt==Specifier::Virtual)
{
tagFile << " virtualness=\"virtual\"";
}
QCString displayName = insertTemplateSpecifierInScope(
cd->displayName(),ibcd.templSpecifiers);
tagFile << ">" << convertToXML(displayName) << "</base>\n";
}
}
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
switch (lde->kind())
{
case LayoutDocEntry::ClassNestedClasses:
{
for (const auto &innerCd : m_impl->innerClasses)
{
if (innerCd->isLinkableInProject() && innerCd->templateMaster()==nullptr &&
protectionLevelVisible(innerCd->protection()) &&
!innerCd->isEmbeddedInOuterScope()
)
{
tagFile << " <class kind=\"" << innerCd->compoundTypeString() <<
"\">" << convertToXML(innerCd->name()) << "</class>\n";
}
}
}
break;
case LayoutDocEntry::MemberDecl:
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
MemberList * ml = getMemberList(lmd->type);
if (ml)
{
ml->writeTagFile(tagFile);
}
}
}
break;
case LayoutDocEntry::MemberGroups:
{
for (const auto &mg : m_impl->memberGroups)
{
mg->writeTagFile(tagFile);
}
}
break;
default:
break;
}
}
writeDocAnchorsToTagFile(tagFile);
tagFile << " </compound>\n";
}
/** Write class documentation inside another container (i.e. a group) */
void ClassDefImpl::writeInlineDocumentation(OutputList &ol) const
{
bool isSimple = m_impl->isSimple;
ol.addIndexItem(name(),QCString());
//printf("ClassDefImpl::writeInlineDocumentation(%s)\n",qPrint(name()));
// part 1: anchor and title
QCString s = compoundTypeString()+" "+name();
// part 1a
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{ // only HTML only
ol.writeAnchor(QCString(),anchor());
ol.startMemberDoc(QCString(),QCString(),anchor(),name(),1,1,FALSE);
ol.startMemberDocName(FALSE);
ol.parseText(s);
ol.endMemberDocName();
ol.endMemberDoc(FALSE);
ol.writeString("</div>");
ol.startIndent();
}
ol.popGeneratorState();
// part 1b
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.disable(OutputType::Man);
{ // for LaTeX/RTF only
ol.writeAnchor(getOutputFileBase(),anchor());
}
ol.popGeneratorState();
// part 1c
ol.pushGeneratorState();
ol.disable(OutputType::Html);
{
// for LaTeX/RTF/Man
ol.startGroupHeader(1);
ol.parseText(s);
ol.endGroupHeader(1);
}
ol.popGeneratorState();
SrcLangExt lang=getLanguage();
// part 2: the header and detailed description
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
switch (lde->kind())
{
case LayoutDocEntry::BriefDesc:
{
// since we already shown the brief description in the
// declaration part of the container, so we use this to
// show the details on top.
writeDetailedDocumentationBody(ol);
}
break;
case LayoutDocEntry::ClassInheritanceGraph:
writeInheritanceGraph(ol);
break;
case LayoutDocEntry::ClassCollaborationGraph:
writeCollaborationGraph(ol);
break;
case LayoutDocEntry::MemberDeclStart:
if (!isSimple) startMemberDeclarations(ol);
break;
case LayoutDocEntry::MemberDecl:
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
ClassDefSet visitedClasses;
if (!isSimple) writeMemberDeclarations(ol,visitedClasses,lmd->type,lmd->title(lang),lmd->subtitle(lang),TRUE);
}
}
break;
case LayoutDocEntry::MemberGroups:
if (!isSimple) writeMemberGroups(ol,TRUE);
break;
case LayoutDocEntry::MemberDeclEnd:
if (!isSimple) endMemberDeclarations(ol);
break;
case LayoutDocEntry::MemberDefStart:
if (!isSimple) startMemberDocumentation(ol);
break;
case LayoutDocEntry::MemberDef:
{
const LayoutDocEntryMemberDef *lmd = dynamic_cast<const LayoutDocEntryMemberDef*>(lde.get());
if (lmd)
{
if (isSimple)
{
writeSimpleMemberDocumentation(ol,lmd->type);
}
else
{
writeMemberDocumentation(ol,lmd->type,lmd->title(lang),TRUE);
}
}
}
break;
case LayoutDocEntry::MemberDefEnd:
if (!isSimple) endMemberDocumentation(ol);
break;
default:
break;
}
}
// part 3: close the block
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
{ // HTML only
ol.endIndent();
}
ol.popGeneratorState();
}
void ClassDefImpl::writeMoreLink(OutputList &ol,const QCString &anchor) const
{
// TODO: clean up this mess by moving it to
// the output generators...
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
bool rtfHyperlinks = Config_getBool(RTF_HYPERLINKS);
bool usePDFLatex = Config_getBool(USE_PDFLATEX);
// HTML only
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.docify(" ");
ol.startTextLink(getOutputFileBase(),
anchor.isEmpty() ? QCString("details") : anchor);
ol.parseText(theTranslator->trMore());
ol.endTextLink();
ol.popGeneratorState();
if (!anchor.isEmpty())
{
ol.pushGeneratorState();
// LaTeX + RTF
ol.disable(OutputType::Html);
ol.disable(OutputType::Man);
ol.disable(OutputType::Docbook);
if (!(usePDFLatex && pdfHyperlinks))
{
ol.disable(OutputType::Latex);
}
if (!rtfHyperlinks)
{
ol.disable(OutputType::RTF);
}
ol.docify(" ");
ol.startTextLink(getOutputFileBase(), anchor);
ol.parseText(theTranslator->trMore());
ol.endTextLink();
// RTF only
ol.disable(OutputType::Latex);
ol.writeString("\\par");
ol.popGeneratorState();
}
}
bool ClassDefImpl::visibleInParentsDeclList() const
{
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
bool hideUndocClasses = Config_getBool(HIDE_UNDOC_CLASSES);
bool extractLocalClasses = Config_getBool(EXTRACT_LOCAL_CLASSES);
bool linkable = isLinkable();
return (!isAnonymous() && !isExtension() &&
(protection()!=Protection::Private || extractPrivate) &&
(linkable || (!hideUndocClasses && (!isLocal() || extractLocalClasses)))
);
}
void ClassDefImpl::writeDeclarationLink(OutputList &ol,bool &found,const QCString &header,bool localNames) const
{
//bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
//bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
SrcLangExt lang = getLanguage();
if (visibleInParentsDeclList())
{
if (!found) // first class
{
if (sliceOpt)
{
if (compoundType()==Interface)
{
ol.startMemberHeader("interfaces");
}
else if (compoundType()==Struct)
{
ol.startMemberHeader("structs");
}
else if (compoundType()==Exception)
{
ol.startMemberHeader("exceptions");
}
else // compoundType==Class
{
ol.startMemberHeader("nested-classes");
}
}
else // non-Slice optimization: single header for class/struct/..
{
ol.startMemberHeader("nested-classes");
}
if (!header.isEmpty())
{
ol.parseText(header);
}
else if (lang==SrcLangExt::VHDL)
{
ol.parseText(theTranslator->trVhdlType(VhdlSpecifier::ARCHITECTURE,FALSE));
}
else
{
ol.parseText(lang==SrcLangExt::Fortran ?
theTranslator->trDataTypes() :
theTranslator->trCompounds());
}
ol.endMemberHeader();
ol.startMemberList();
found=TRUE;
}
ol.startMemberDeclaration();
ol.startMemberItem(anchor(),OutputGenerator::MemberItemType::Normal);
QCString ctype = compoundTypeString();
QCString cname = displayName(!localNames);
if (lang!=SrcLangExt::VHDL) // for VHDL we swap the name and the type
{
if (isSliceLocal())
{
ol.writeString("local ");
}
ol.writeString(ctype);
ol.writeString(" ");
ol.insertMemberAlign();
}
if (isLinkable())
{
ol.writeObjectLink(getReference(),
getOutputFileBase(),
anchor(),
cname
);
}
else
{
ol.startBold();
ol.docify(cname);
ol.endBold();
}
if (lang==SrcLangExt::VHDL) // now write the type
{
ol.writeString(" ");
ol.insertMemberAlign();
ol.writeString(VhdlDocGen::getProtectionName(VhdlDocGen::convert(protection())));
}
ol.endMemberItem(OutputGenerator::MemberItemType::Normal);
// add the brief description if available
if (!briefDescription().isEmpty() && Config_getBool(BRIEF_MEMBER_DESC))
{
auto parser { createDocParser() };
auto ast { validatingParseDoc(*parser.get(),
briefFile(),briefLine(),this,nullptr,
briefDescription(),FALSE,FALSE,
QCString(),TRUE,FALSE,Config_getBool(MARKDOWN_SUPPORT)) };
if (!ast->isEmpty())
{
ol.startMemberDescription(anchor());
ol.writeDoc(ast.get(),this,nullptr);
if (isLinkableInProject())
{
writeMoreLink(ol,anchor());
}
ol.endMemberDescription();
}
}
ol.endMemberDeclaration(anchor(),QCString());
}
}
void ClassDefImpl::addClassAttributes(OutputList &ol) const
{
StringVector sl;
if (isFinal()) sl.emplace_back("final");
if (isSealed()) sl.emplace_back("sealed");
if (isAbstract()) sl.emplace_back("abstract");
if (isExported()) sl.emplace_back("export");
if (getLanguage()==SrcLangExt::IDL && isPublished()) sl.emplace_back("published");
for (const auto &sx : m_impl->qualifiers)
{
bool alreadyAdded = std::find(sl.begin(), sl.end(), sx) != sl.end();
if (!alreadyAdded)
{
sl.push_back(sx);
}
}
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
if (!sl.empty())
{
ol.startLabels();
size_t i=0;
for (const auto &s : sl)
{
i++;
ol.writeLabel(s.c_str(),i==sl.size());
}
ol.endLabels();
}
ol.popGeneratorState();
}
void ClassDefImpl::writeDocumentationContents(OutputList &ol,const QCString & /*pageTitle*/) const
{
ol.startContents();
QCString pageType = " ";
pageType += compoundTypeString();
bool exampleFlag=hasExamples();
//---------------------------------------- start flexible part -------------------------------
SrcLangExt lang = getLanguage();
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
switch (lde->kind())
{
case LayoutDocEntry::BriefDesc:
writeBriefDescription(ol,exampleFlag);
break;
case LayoutDocEntry::ClassIncludes:
if (lang==SrcLangExt::Slice)
{
writeIncludeFilesForSlice(ol);
}
else
{
writeIncludeFiles(ol);
}
break;
case LayoutDocEntry::ClassInheritanceGraph:
writeInheritanceGraph(ol);
break;
case LayoutDocEntry::ClassCollaborationGraph:
writeCollaborationGraph(ol);
break;
case LayoutDocEntry::ClassAllMembersLink:
//writeAllMembersLink(ol); // this is now part of the summary links
break;
case LayoutDocEntry::MemberDeclStart:
startMemberDeclarations(ol);
break;
case LayoutDocEntry::MemberGroups:
writeMemberGroups(ol);
break;
case LayoutDocEntry::MemberDecl:
{
ClassDefSet visitedClasses;
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
writeMemberDeclarations(ol,visitedClasses,lmd->type,lmd->title(lang),lmd->subtitle(lang));
}
}
break;
case LayoutDocEntry::ClassNestedClasses:
{
const LayoutDocEntrySection *ls = dynamic_cast<const LayoutDocEntrySection*>(lde.get());
if (ls)
{
writeNestedClasses(ol,ls->title(lang));
}
}
break;
case LayoutDocEntry::MemberDeclEnd:
endMemberDeclarations(ol);
break;
case LayoutDocEntry::DetailedDesc:
{
const LayoutDocEntrySection *ls = dynamic_cast<const LayoutDocEntrySection*>(lde.get());
if (ls)
{
writeDetailedDescription(ol,pageType,exampleFlag,ls->title(lang));
}
}
break;
case LayoutDocEntry::MemberDefStart:
startMemberDocumentation(ol);
break;
case LayoutDocEntry::ClassInlineClasses:
writeInlineClasses(ol);
break;
case LayoutDocEntry::MemberDef:
{
const LayoutDocEntryMemberDef *lmd = dynamic_cast<const LayoutDocEntryMemberDef*>(lde.get());
if (lmd)
{
writeMemberDocumentation(ol,lmd->type,lmd->title(lang));
}
}
break;
case LayoutDocEntry::MemberDefEnd:
endMemberDocumentation(ol);
break;
case LayoutDocEntry::ClassUsedFiles:
showUsedFiles(ol);
break;
case LayoutDocEntry::AuthorSection:
writeAuthorSection(ol);
break;
case LayoutDocEntry::NamespaceNestedNamespaces:
case LayoutDocEntry::NamespaceNestedConstantGroups:
case LayoutDocEntry::NamespaceClasses:
case LayoutDocEntry::NamespaceConcepts:
case LayoutDocEntry::NamespaceInterfaces:
case LayoutDocEntry::NamespaceStructs:
case LayoutDocEntry::NamespaceExceptions:
case LayoutDocEntry::NamespaceInlineClasses:
case LayoutDocEntry::ConceptDefinition:
case LayoutDocEntry::FileClasses:
case LayoutDocEntry::FileConcepts:
case LayoutDocEntry::FileInterfaces:
case LayoutDocEntry::FileStructs:
case LayoutDocEntry::FileExceptions:
case LayoutDocEntry::FileNamespaces:
case LayoutDocEntry::FileConstantGroups:
case LayoutDocEntry::FileIncludes:
case LayoutDocEntry::FileIncludeGraph:
case LayoutDocEntry::FileIncludedByGraph:
case LayoutDocEntry::FileSourceLink:
case LayoutDocEntry::FileInlineClasses:
case LayoutDocEntry::GroupClasses:
case LayoutDocEntry::GroupConcepts:
case LayoutDocEntry::GroupModules:
case LayoutDocEntry::GroupInlineClasses:
case LayoutDocEntry::GroupNamespaces:
case LayoutDocEntry::GroupDirs:
case LayoutDocEntry::GroupNestedGroups:
case LayoutDocEntry::GroupFiles:
case LayoutDocEntry::GroupGraph:
case LayoutDocEntry::GroupPageDocs:
case LayoutDocEntry::ModuleExports:
case LayoutDocEntry::ModuleClasses:
case LayoutDocEntry::ModuleConcepts:
case LayoutDocEntry::ModuleUsedFiles:
case LayoutDocEntry::DirSubDirs:
case LayoutDocEntry::DirFiles:
case LayoutDocEntry::DirGraph:
err("Internal inconsistency: member %d should not be part of "
"LayoutDocManager::Class entry list\n",lde->kind());
break;
}
}
ol.endContents();
}
QCString ClassDefImpl::title() const
{
QCString pageTitle;
SrcLangExt lang = getLanguage();
if (lang==SrcLangExt::Fortran)
{
pageTitle = theTranslator->trCompoundReferenceFortran(displayName(),
m_impl->compType,
!m_impl->tempArgs.empty());
}
else if (lang==SrcLangExt::Slice)
{
pageTitle = theTranslator->trCompoundReferenceSlice(displayName(),
m_impl->compType,
isSliceLocal());
}
else if (lang==SrcLangExt::VHDL)
{
pageTitle = theTranslator->trCustomReference(VhdlDocGen::getClassTitle(this));
}
else if (isJavaEnum())
{
pageTitle = theTranslator->trEnumReference(displayName());
}
else if (m_impl->compType==Service)
{
pageTitle = theTranslator->trServiceReference(displayName());
}
else if (m_impl->compType==Singleton)
{
pageTitle = theTranslator->trSingletonReference(displayName());
}
else
{
if (Config_getBool(HIDE_COMPOUND_REFERENCE))
{
pageTitle = displayName();
}
else
{
pageTitle = theTranslator->trCompoundReference(displayName(),
m_impl->compType == Interface && getLanguage()==SrcLangExt::ObjC ? Class : m_impl->compType,
!m_impl->tempArgs.empty());
}
}
return pageTitle;
}
// write all documentation for this class
void ClassDefImpl::writeDocumentation(OutputList &ol) const
{
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
//bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
//bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
QCString pageTitle = title();
HighlightedItem hli = HighlightedItem::None;
if (sliceOpt)
{
if (compoundType()==Interface)
{
hli = HighlightedItem::InterfaceVisible;
}
else if (compoundType()==Struct)
{
hli = HighlightedItem::StructVisible;
}
else if (compoundType()==Exception)
{
hli = HighlightedItem::ExceptionVisible;
}
else
{
hli = HighlightedItem::ClassVisible;
}
}
else
{
hli = HighlightedItem::ClassVisible;
}
startFile(ol,getOutputFileBase(),name(),pageTitle,hli,!generateTreeView);
if (!generateTreeView)
{
if (getOuterScope()!=Doxygen::globalScope)
{
writeNavigationPath(ol);
}
ol.endQuickIndices();
}
startTitle(ol,getOutputFileBase(),this);
ol.parseText(pageTitle);
addClassAttributes(ol);
addGroupListToTitle(ol,this);
endTitle(ol,getOutputFileBase(),displayName());
writeDocumentationContents(ol,pageTitle);
endFileWithNavPath(ol,this);
if (Config_getBool(SEPARATE_MEMBER_PAGES))
{
writeMemberPages(ol);
}
}
void ClassDefImpl::writeMemberPages(OutputList &ol) const
{
///////////////////////////////////////////////////////////////////////////
//// Member definitions on separate pages
///////////////////////////////////////////////////////////////////////////
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
for (const auto &ml : m_impl->memberLists)
{
if (ml->numDocMembers()>ml->numDocEnumValues() && ml->listType().isDetailed())
{
ml->writeDocumentationPage(ol,displayName(),this);
}
}
ol.popGeneratorState();
}
void ClassDefImpl::writeQuickMemberLinks(OutputList &ol,const MemberDef *currentMd) const
{
bool createSubDirs=Config_getBool(CREATE_SUBDIRS);
ol.writeString(" <div class=\"navtab\">\n");
ol.writeString(" <table>\n");
for (auto &mni : m_impl->allMemberNameInfoLinkedMap)
{
for (auto &mi : *mni)
{
const MemberDef *md=mi->memberDef();
if (md->getClassDef()==this && md->isLinkable() && !md->isEnumValue())
{
if (md->isLinkableInProject())
{
if (md==currentMd) // selected item => highlight
{
ol.writeString(" <tr><td class=\"navtabHL\">");
}
else
{
ol.writeString(" <tr><td class=\"navtab\">");
}
ol.writeString("<a class=\"navtab\" ");
ol.writeString("href=\"");
if (createSubDirs) ol.writeString("../../");
QCString url = md->getOutputFileBase();
addHtmlExtensionIfMissing(url);
ol.writeString(url+"#"+md->anchor());
ol.writeString("\">");
ol.writeString(convertToHtml(md->name()));
ol.writeString("</a>");
ol.writeString("</td></tr>\n");
}
}
}
}
ol.writeString(" </table>\n");
ol.writeString(" </div>\n");
}
void ClassDefImpl::writeDocumentationForInnerClasses(OutputList &ol) const
{
// write inner classes after the parent, so the tag files contain
// the definition in proper order!
for (const auto &innerCd : m_impl->innerClasses)
{
if (
innerCd->isLinkableInProject() && innerCd->templateMaster()==nullptr &&
protectionLevelVisible(innerCd->protection()) &&
!innerCd->isEmbeddedInOuterScope()
)
{
msg("Generating docs for nested compound %s...\n",qPrint(innerCd->name()));
innerCd->writeDocumentation(ol);
innerCd->writeMemberList(ol);
}
innerCd->writeDocumentationForInnerClasses(ol);
}
}
// write the list of all (inherited) members for this class
void ClassDefImpl::writeMemberList(OutputList &ol) const
{
bool cOpt = Config_getBool(OPTIMIZE_OUTPUT_FOR_C);
//bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
bool sliceOpt = Config_getBool(OPTIMIZE_OUTPUT_SLICE);
bool generateTreeView = Config_getBool(GENERATE_TREEVIEW);
if (m_impl->allMemberNameInfoLinkedMap.empty() || cOpt) return;
// only for HTML
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
HighlightedItem hli = HighlightedItem::None;
if (sliceOpt)
{
if (compoundType()==Interface)
{
hli = HighlightedItem::InterfaceVisible;
}
else if (compoundType()==Struct)
{
hli = HighlightedItem::StructVisible;
}
else if (compoundType()==Exception)
{
hli = HighlightedItem::ExceptionVisible;
}
else
{
hli = HighlightedItem::ClassVisible;
}
}
else
{
hli = HighlightedItem::ClassVisible;
}
QCString memListFile = getMemberListFileName();
startFile(ol,memListFile,memListFile,theTranslator->trMemberList(),hli,!generateTreeView,getOutputFileBase());
if (!generateTreeView)
{
if (getOuterScope()!=Doxygen::globalScope)
{
writeNavigationPath(ol);
}
ol.endQuickIndices();
}
startTitle(ol,QCString());
ol.parseText(displayName()+" "+theTranslator->trMemberList());
endTitle(ol,QCString(),QCString());
ol.startContents();
ol.startParagraph();
ol.parseText(theTranslator->trThisIsTheListOfAllMembers());
ol.docify(" ");
ol.writeObjectLink(getReference(),getOutputFileBase(),anchor(),displayName());
ol.parseText(theTranslator->trIncludingInheritedMembers());
ol.endParagraph();
//ol.startItemList();
bool first = true; // to prevent empty table
int idx=0;
for (auto &mni : m_impl->allMemberNameInfoLinkedMap)
{
for (auto &mi : *mni)
{
const MemberDef *md=mi->memberDef();
const ClassDef *cd=md->getClassDef();
Protection prot = mi->prot();
Specifier virt=md->virtualness();
//printf("%s: Member %s of class %s md->protection()=%d mi->prot=%d prot=%d inherited=%d\n",
// qPrint(name()),qPrint(md->name()),qPrint(cd->name()),md->protection(),mi->prot,prot,mi->inherited);
if (cd && !md->name().isEmpty() && !md->isAnonymous())
{
bool memberWritten=FALSE;
if (cd->isLinkable() && md->isLinkable())
// create a link to the documentation
{
QCString name=mi->ambiguityResolutionScope()+md->name();
//ol.writeListItem();
if (first)
{
ol.writeString("<table class=\"directory\">\n");
first = false;
}
ol.writeString(" <tr");
if ((idx&1)==0) ol.writeString(" class=\"even\""); else ol.writeString(" class=\"odd\"");
idx++;
ol.writeString("><td class=\"entry\">");
if (cd->isObjectiveC())
{
if (md->isObjCMethod())
{
if (md->isStatic())
ol.writeString("+ </td><td>");
else
ol.writeString("- </td><td>");
}
else
ol.writeString("</td><td class=\"entry\">");
}
if (md->isObjCMethod())
{
ol.writeObjectLink(md->getReference(),
md->getOutputFileBase(),
md->anchor(),md->name());
}
else
{
//Definition *bd = md->getGroupDef();
//if (bd==nullptr) bd=cd;
ol.writeObjectLink(md->getReference(),
md->getOutputFileBase(),
md->anchor(),name);
if ( md->isFunction() || md->isSignal() || md->isSlot() ||
(md->isFriend() && !md->argsString().isEmpty()))
ol.docify(md->argsString());
else if (md->isEnumerate())
ol.parseText(" "+theTranslator->trEnumName());
else if (md->isEnumValue())
ol.parseText(" "+theTranslator->trEnumValue());
else if (md->isTypedef())
ol.docify(" typedef");
else if (md->isFriend() && md->typeString()=="friend class")
ol.docify(" class");
//ol.writeString("\n");
}
ol.writeString("</td>");
memberWritten=TRUE;
}
else if (!cd->isArtificial() &&
!Config_getBool(HIDE_UNDOC_MEMBERS) &&
(protectionLevelVisible(md->protection()) || md->isFriend())
) // no documentation,
// generate link to the class instead.
{
//ol.writeListItem();
if (first)
{
ol.writeString("<table class=\"directory\">\n");
first = false;
}
ol.writeString(" <tr bgcolor=\"#f0f0f0\"");
if ((idx&1)==0) ol.writeString(" class=\"even\""); else ol.writeString(" class=\"odd\"");
idx++;
ol.writeString("><td class=\"entry\">");
if (cd->isObjectiveC())
{
if (md->isObjCMethod())
{
if (md->isStatic())
ol.writeString("+ </td><td class=\"entry\">");
else
ol.writeString("- </td><td class=\"entry\">");
}
else
ol.writeString("</td><td class=\"entry\">");
}
ol.startBold();
ol.docify(md->name());
ol.endBold();
if (!md->isObjCMethod())
{
if ( md->isFunction() || md->isSignal() || md->isSlot() )
ol.docify(md->argsString());
else if (md->isEnumerate())
ol.parseText(" "+theTranslator->trEnumName());
else if (md->isEnumValue())
ol.parseText(" "+theTranslator->trEnumValue());
else if (md->isTypedef())
ol.docify(" typedef");
}
ol.writeString(" (");
ol.parseText(theTranslator->trDefinedIn()+" ");
if (cd->isLinkable())
{
ol.writeObjectLink(
cd->getReference(),
cd->getOutputFileBase(),
cd->anchor(),
cd->displayName());
}
else
{
ol.startBold();
ol.docify(cd->displayName());
ol.endBold();
}
ol.writeString(")");
ol.writeString("</td>");
memberWritten=TRUE;
}
if (memberWritten)
{
ol.writeString("<td class=\"entry\">");
ol.writeObjectLink(cd->getReference(),
cd->getOutputFileBase(),
cd->anchor(),
md->category() ?
md->category()->displayName() :
cd->displayName());
ol.writeString("</td>");
ol.writeString("<td class=\"entry\">");
}
SrcLangExt lang = md->getLanguage();
if (
(prot!=Protection::Public || (virt!=Specifier::Normal && getLanguage()!=SrcLangExt::ObjC) ||
md->isFriend() || md->isRelated() || md->isExplicit() ||
md->isMutable() || (md->isInline() && Config_getBool(INLINE_INFO)) ||
md->isSignal() || md->isSlot() ||
(getLanguage()==SrcLangExt::IDL &&
(md->isOptional() || md->isAttribute() || md->isUNOProperty())) ||
md->isStatic() || lang==SrcLangExt::VHDL
)
&& memberWritten)
{
StringVector sl;
if (lang==SrcLangExt::VHDL)
{
sl.push_back(theTranslator->trVhdlType(md->getVhdlSpecifiers(),TRUE).str()); //append vhdl type
}
else if (md->isFriend()) sl.emplace_back("friend");
else if (md->isRelated()) sl.emplace_back("related");
else
{
if (Config_getBool(INLINE_INFO) && md->isInline())
sl.emplace_back("inline");
if (md->isExplicit()) sl.emplace_back("explicit");
if (md->isMutable()) sl.emplace_back("mutable");
if (prot==Protection::Protected) sl.emplace_back("protected");
else if (prot==Protection::Private) sl.emplace_back("private");
else if (prot==Protection::Package) sl.emplace_back("package");
if (virt==Specifier::Virtual && getLanguage()!=SrcLangExt::ObjC)
sl.emplace_back("virtual");
else if (virt==Specifier::Pure) sl.emplace_back("pure virtual");
if (md->isStatic()) sl.emplace_back("static");
if (md->isSignal()) sl.emplace_back("signal");
if (md->isSlot()) sl.emplace_back("slot");
// this is the extra member page
if (md->isOptional()) sl.emplace_back("optional");
if (md->isAttribute()) sl.emplace_back("attribute");
if (md->isUNOProperty()) sl.emplace_back("property");
if (md->isReadonly()) sl.emplace_back("readonly");
if (md->isBound()) sl.emplace_back("bound");
if (md->isRemovable()) sl.emplace_back("removable");
if (md->isConstrained()) sl.emplace_back("constrained");
if (md->isTransient()) sl.emplace_back("transient");
if (md->isMaybeVoid()) sl.emplace_back("maybevoid");
if (md->isMaybeDefault()) sl.emplace_back("maybedefault");
if (md->isMaybeAmbiguous()) sl.emplace_back("maybeambiguous");
}
bool firstSpan=true;
for (const auto &s : sl)
{
if (!firstSpan)
{
ol.writeString("</span><span class=\"mlabel\">");
}
else
{
ol.writeString("<span class=\"mlabel\">");
firstSpan=false;
}
ol.docify(s.c_str());
}
if (!firstSpan) ol.writeString("</span>");
}
if (memberWritten)
{
ol.writeString("</td>");
ol.writeString("</tr>\n");
}
}
}
}
//ol.endItemList();
if (!first) ol.writeString("</table>");
endFile(ol);
ol.popGeneratorState();
}
// add a reference to an example
bool ClassDefImpl::addExample(const QCString &anchor,const QCString &nameStr, const QCString &file)
{
return m_impl->examples.inSort(Example(anchor,nameStr,file));
}
// returns TRUE if this class is used in an example
bool ClassDefImpl::hasExamples() const
{
return !m_impl->examples.empty();
}
void ClassDefImpl::addTypeConstraint(const QCString &typeConstraint,const QCString &type)
{
//printf("addTypeConstraint(%s,%s)\n",qPrint(type),qPrint(typeConstraint));
bool hideUndocRelation = Config_getBool(HIDE_UNDOC_RELATIONS);
if (typeConstraint.isEmpty() || type.isEmpty()) return;
SymbolResolver resolver(getFileDef());
ClassDefMutable *cd = resolver.resolveClassMutable(this,typeConstraint);
if (cd==nullptr && !hideUndocRelation)
{
cd = toClassDefMutable(
Doxygen::hiddenClassLinkedMap->add(typeConstraint,
std::unique_ptr<ClassDef>(
new ClassDefImpl(
getDefFileName(),getDefLine(),
getDefColumn(),
typeConstraint,
ClassDef::Class))));
if (cd)
{
cd->setUsedOnly(TRUE);
cd->setLanguage(getLanguage());
//printf("Adding undocumented constraint '%s' to class %s on type %s\n",
// qPrint(typeConstraint),qPrint(name()),qPrint(type));
}
}
if (cd)
{
auto it = std::find_if(m_impl->constraintClassList.begin(),
m_impl->constraintClassList.end(),
[&cd](const auto &ccd) { return ccd.classDef==cd; });
if (it==m_impl->constraintClassList.end())
{
m_impl->constraintClassList.emplace_back(cd);
it = m_impl->constraintClassList.end()-1;
}
(*it).addAccessor(type);
//printf("Adding constraint '%s' to class %s on type %s\n",
// qPrint(typeConstraint),qPrint(name()),qPrint(type));
}
}
// Java Type Constrains: A<T extends C & I>
void ClassDefImpl::addTypeConstraints()
{
for (const Argument &a : m_impl->tempArgs)
{
if (!a.typeConstraint.isEmpty())
{
QCString typeConstraint;
int i=0,p=0;
while ((i=a.typeConstraint.find('&',p))!=-1) // typeConstraint="A &I" for C<T extends A & I>
{
typeConstraint = a.typeConstraint.mid(p,i-p).stripWhiteSpace();
addTypeConstraint(typeConstraint,a.type);
p=i+1;
}
typeConstraint = a.typeConstraint.right(a.typeConstraint.length()-p).stripWhiteSpace();
addTypeConstraint(typeConstraint,a.type);
}
}
}
// C# Type Constraints: D<T> where T : C, I
void ClassDefImpl::setTypeConstraints(const ArgumentList &al)
{
m_impl->typeConstraints = al;
}
void ClassDefImpl::setTemplateArguments(const ArgumentList &al)
{
m_impl->tempArgs = al;
}
static bool hasNonReferenceSuperClassRec(const ClassDef *cd,int level)
{
bool found=!cd->isReference() && cd->isLinkableInProject() && !cd->isHidden();
if (found)
{
return TRUE; // we're done if this class is not a reference
}
for (const auto &ibcd : cd->subClasses())
{
const ClassDef *bcd=ibcd.classDef;
if (level>256)
{
err("Possible recursive class relation while inside %s and looking for base class %s\n",qPrint(cd->name()),qPrint(bcd->name()));
return FALSE;
}
// recurse into the super class branch
found = found || hasNonReferenceSuperClassRec(bcd,level+1);
if (!found)
{
// look for template instances that might have non-reference super classes
for (const auto &cil : bcd->getTemplateInstances())
{
// recurse into the template instance branch
found = hasNonReferenceSuperClassRec(cil.classDef,level+1);
if (found) break;
}
}
else
{
break;
}
}
return found;
}
/*! Returns \c TRUE iff this class or a class inheriting from this class
* is \e not defined in an external tag file.
*/
bool ClassDefImpl::hasNonReferenceSuperClass() const
{
return hasNonReferenceSuperClassRec(this,0);
}
QCString ClassDefImpl::requiresClause() const
{
return m_impl->requiresClause;
}
void ClassDefImpl::setRequiresClause(const QCString &req)
{
m_impl->requiresClause = req;
}
/*! called from MemberDef::writeDeclaration() to (recursively) write the
* definition of an anonymous struct, union or class.
*/
void ClassDefImpl::writeDeclaration(OutputList &ol,const MemberDef *md,bool inGroup,int indentLevel,
const ClassDef *inheritedFrom,const QCString &inheritId) const
{
//printf("ClassName='%s' inGroup=%d\n",qPrint(name()),inGroup);
ol.docify(compoundTypeString());
QCString cn = displayName(FALSE);
if (!cn.isEmpty())
{
ol.docify(" ");
if (md && isLinkable())
{
ol.writeObjectLink(QCString(),QCString(),md->anchor(),cn);
}
else
{
ol.startBold();
ol.docify(cn);
ol.endBold();
}
}
ol.docify(" {");
ol.endMemberItem(OutputGenerator::MemberItemType::AnonymousStart);
ol.endMemberDeclaration(md ? md->anchor() : QCString(),inheritId);
// write user defined member groups
for (const auto &mg : m_impl->memberGroups)
{
mg->writePlainDeclarations(ol,inGroup,this,nullptr,nullptr,nullptr,nullptr,indentLevel,inheritedFrom,inheritId);
}
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
writePlainMemberDeclaration(ol,lmd->type,inGroup,indentLevel,inheritedFrom,inheritId);
}
}
}
}
/*! a link to this class is possible within this project */
bool ClassDefImpl::isLinkableInProject() const
{
bool extractLocal = Config_getBool(EXTRACT_LOCAL_CLASSES);
bool extractStatic = Config_getBool(EXTRACT_STATIC);
bool hideUndoc = Config_getBool(HIDE_UNDOC_CLASSES);
if (m_impl->templateMaster)
{
return m_impl->templateMaster->isLinkableInProject();
}
else
{
//printf("%s::isLinkableInProject() conditions: artificial=%d hidden=%d anonymous=%d protection=%d local=%d docs=%d static=%d ref=%d\n",
// qPrint(name()),
// !isArtificial(),
// !isHidden(),
// !isAnonymous(),
// m_impl->prot,
// !m_impl->isLocal || extractLocal,
// hasDocumentation() || !hideUndoc,
// !m_impl->isStatic || extractStatic,
// !isReference());
return
!isArtificial() && !isHidden() && /* not hidden */
!isAnonymous() && /* not anonymous */
protectionLevelVisible(m_impl->prot) && /* private/internal */
(!m_impl->isLocal || extractLocal) && /* local */
(hasDocumentation() || !hideUndoc) && /* documented */
(!m_impl->isStatic || extractStatic) && /* static */
!isReference(); /* not an external reference */
}
}
bool ClassDefImpl::isLinkable() const
{
if (m_impl->templateMaster)
{
return m_impl->templateMaster->isLinkable();
}
else
{
return isReference() || isLinkableInProject();
}
}
/*! the class is visible in a class diagram, or class hierarchy */
bool ClassDefImpl::isVisibleInHierarchy() const
{
bool allExternals = Config_getBool(ALLEXTERNALS);
bool hideUndocClasses = Config_getBool(HIDE_UNDOC_CLASSES);
bool extractStatic = Config_getBool(EXTRACT_STATIC);
return // show all classes or a subclass is visible
((allExternals && !isArtificial()) || hasNonReferenceSuperClass()) &&
// and not an anonymous compound
!isAnonymous() &&
// and not privately inherited
protectionLevelVisible(m_impl->prot) &&
// documented or shown anyway or documentation is external
(hasDocumentation() ||
!hideUndocClasses ||
(m_impl->templateMaster && m_impl->templateMaster->hasDocumentation()) ||
isReference()
) &&
// is not part of an unnamed namespace or shown anyway
(!m_impl->isStatic || extractStatic);
}
bool ClassDefImpl::hasDocumentation() const
{
return DefinitionMixin::hasDocumentation();
}
//----------------------------------------------------------------------
// recursive function:
// returns the distance to the base class definition 'bcd' represents an (in)direct base
// class of class definition 'cd' or nullptr if it does not.
int ClassDefImpl::isBaseClass(const ClassDef *bcd, bool followInstances,const QCString &templSpec) const
{
int distance=0;
//printf("isBaseClass(cd=%s) looking for %s templSpec=%s\n",qPrint(name()),qPrint(bcd->name()),qPrint(templSpec));
for (const auto &bclass : baseClasses())
{
const ClassDef *ccd = bclass.classDef;
if (!followInstances && ccd->templateMaster())
{
ccd=ccd->templateMaster();
}
if (ccd==bcd && (templSpec.isEmpty() || templSpec==bclass.templSpecifiers))
{
distance=1;
break; // no shorter path possible
}
else
{
int d = ccd->isBaseClass(bcd,followInstances,templSpec);
if (d>256)
{
err("Possible recursive class relation while inside %s and looking for base class %s\n",qPrint(name()),qPrint(bcd->name()));
return 0;
}
else if (d>0) // path found
{
if (distance==0 || d+1<distance) // update if no path found yet or shorter path found
{
distance=d+1;
}
}
}
}
return distance;
}
//----------------------------------------------------------------------
bool ClassDefImpl::isSubClass(ClassDef *cd,int level) const
{
bool found=FALSE;
if (level>256)
{
err("Possible recursive class relation while inside %s and looking for derived class %s\n",qPrint(name()),qPrint(cd->name()));
return FALSE;
}
for (const auto &iscd : subClasses())
{
ClassDef *ccd=iscd.classDef;
found = (ccd==cd) || ccd->isSubClass(cd,level+1);
if (found) break;
}
return found;
}
//----------------------------------------------------------------------------
static bool isStandardFunc(const MemberDef *md)
{
return md->name()=="operator=" || // assignment operator
md->isConstructor() || // constructor
md->isDestructor(); // destructor
}
void ClassDefImpl::mergeMembersFromBaseClasses(bool mergeVirtualBaseClass)
{
SrcLangExt lang = getLanguage();
QCString sep=getLanguageSpecificSeparator(lang,TRUE);
size_t sepLen = sep.length();
bool inlineInheritedMembers = Config_getBool(INLINE_INHERITED_MEMB);
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
//printf(" mergeMembers for %s mergeVirtualBaseClass=%d\n",qPrint(name()),mergeVirtualBaseClass);
// the merge the base members with this class' members
for (const auto &bcd : baseClasses())
{
ClassDefMutable *bClass=toClassDefMutable(bcd.classDef);
if (bClass)
{
const MemberNameInfoLinkedMap &srcMnd = bClass->memberNameInfoLinkedMap();
MemberNameInfoLinkedMap &dstMnd = m_impl->allMemberNameInfoLinkedMap;
for (auto &srcMni : srcMnd)
{
MemberNameInfo *dstMni=dstMnd.find(srcMni->memberName());
if (dstMni)
// a member with that name is already in the class.
// the member may hide or reimplement the one in the sub class
// or there may be another path to the base class that is already
// visited via another branch in the class hierarchy.
{
//printf(" %s hides member name %s\n",qPrint(bClass->name()),qPrint(srcMni->memberName()));
for (auto &srcMi : *srcMni)
{
MemberDef *srcMd = srcMi->memberDef();
bool found=FALSE;
bool ambiguous=FALSE;
bool hidden=FALSE;
const ClassDef *srcCd = srcMd->getClassDef();
for (auto &dstMi : *dstMni)
{
const MemberDef *dstMd = dstMi->memberDef();
if (srcMd!=dstMd) // different members
{
const ClassDef *dstCd = dstMd->getClassDef();
//printf(" Is %s a base class of %s?\n",qPrint(srcCd->name()),qPrint(dstCd->name()));
if (srcCd==dstCd || dstCd->isBaseClass(srcCd,TRUE))
// member is in the same or a base class
{
const ArgumentList &srcAl = srcMd->argumentList();
const ArgumentList &dstAl = dstMd->argumentList();
found=matchArguments2(
srcMd->getOuterScope(),srcMd->getFileDef(),&srcAl,
dstMd->getOuterScope(),dstMd->getFileDef(),&dstAl,
TRUE,getLanguage()
);
//printf(" Yes, matching (%s<->%s): %d\n",
// qPrint(argListToString(srcMd->argumentList())),
// qPrint(argListToString(dstMd->argumentList())),
// found);
hidden = hidden || !found;
}
else // member is in a non base class => multiple inheritance
// using the same base class.
{
//printf(" $$ Existing member %s %s add scope %s\n",
// qPrint(dstMi->ambiguityResolutionScope()),
// qPrint(dstMd->name()),
// qPrint(dstMi->scopePath().left(dstMi->scopePath().find("::")+2)));
QCString scope=dstMi->scopePath().left(dstMi->scopePath().find(sep)+sepLen);
if (scope!=dstMi->ambiguityResolutionScope().left(scope.length()))
{
dstMi->setAmbiguityResolutionScope(scope+dstMi->ambiguityResolutionScope());
}
ambiguous=TRUE;
}
}
else // same members
{
// do not add if base class is virtual or
// if scope paths are equal or
// if base class is an interface (and thus implicitly virtual).
//printf(" same member found srcMi->virt=%d dstMi->virt=%d\n",srcMi->virt(),dstMi->virt());
if ((srcMi->virt()!=Specifier::Normal && dstMi->virt()!=Specifier::Normal) ||
bClass->name()+sep+srcMi->scopePath() == dstMi->scopePath() ||
dstMd->getClassDef()->compoundType()==Interface
)
{
found=TRUE;
}
else // member can be reached via multiple paths in the
// inheritance tree
{
//printf(" $$ Existing member %s %s add scope %s\n",
// qPrint(dstMi->ambiguityResolutionScope()),
// qPrint(dstMd->name()),
// qPrint(dstMi->scopePath().left(dstMi->scopePath().find("::")+2)));
QCString scope=dstMi->scopePath().left(dstMi->scopePath().find(sep)+sepLen);
if (scope!=dstMi->ambiguityResolutionScope().left(scope.length()))
{
dstMi->setAmbiguityResolutionScope(dstMi->ambiguityResolutionScope()+scope);
}
ambiguous=TRUE;
}
}
if (found) break;
}
//printf(" member %s::%s hidden %d ambiguous %d srcMi->ambigClass=%p found=%d\n",
// qPrint(srcCd->name()),qPrint(srcMd->name()),hidden,ambiguous,
// (void*)srcMi->ambigClass(),found);
// TODO: fix the case where a member is hidden by inheritance
// of a member with the same name but with another prototype,
// while there is more than one path to the member in the
// base class due to multiple inheritance. In this case
// it seems that the member is not reachable by prefixing a
// scope name either (according to my compiler). Currently,
// this case is shown anyway.
if (!found && srcMd->protection()!=Protection::Private && !srcMd->isFriend() && srcMi->virtualBaseClass()==mergeVirtualBaseClass)
{
Protection prot = srcMd->protection();
if (bcd.prot==Protection::Protected && prot==Protection::Public)
{
prot = bcd.prot;
}
else if (bcd.prot==Protection::Private)
{
prot = bcd.prot;
}
if (inlineInheritedMembers)
{
if (!isStandardFunc(srcMd))
{
//printf(" %s::insertMember(%s)\n",qPrint(name()),qPrint(srcMd->name()));
internalInsertMember(srcMd,prot,FALSE);
}
}
Specifier virt=srcMi->virt();
if (virt==Specifier::Normal && bcd.virt!=Specifier::Normal) virt=bcd.virt;
bool virtualBaseClass = bcd.virt!=Specifier::Normal;
std::unique_ptr<MemberInfo> newMi = std::make_unique<MemberInfo>(srcMd,prot,virt,TRUE,virtualBaseClass);
newMi->setScopePath(bClass->name()+sep+srcMi->scopePath());
if (ambiguous)
{
//printf("$$ New member %s %s add scope %s::\n",
// qPrint(srcMi->ambiguityResolutionScope),
// qPrint(srcMd->name()),
// qPrint(bClass->name()));
QCString scope=bClass->name()+sep;
if (scope!=srcMi->ambiguityResolutionScope().left(scope.length()))
{
newMi->setAmbiguityResolutionScope(scope+srcMi->ambiguityResolutionScope());
}
}
if (hidden)
{
if (srcMi->ambigClass()==nullptr)
{
newMi->setAmbigClass(bClass);
newMi->setAmbiguityResolutionScope(bClass->name()+sep);
}
else
{
newMi->setAmbigClass(srcMi->ambigClass());
newMi->setAmbiguityResolutionScope(srcMi->ambigClass()->name()+sep);
}
}
dstMni->push_back(std::move(newMi));
}
}
}
else // base class has a member that is not in the sub class => copy
{
//printf(" %s adds member name %s\n",qPrint(bClass->name()),qPrint(srcMni->memberName()));
// create a deep copy of the list (only the MemberInfo's will be
// copied, not the actual MemberDef's)
MemberNameInfo *newMni = dstMnd.add(srcMni->memberName());
// copy the member(s) from the base to the sub class
for (auto &mi : *srcMni)
{
if (mi->virtualBaseClass()==mergeVirtualBaseClass && !mi->memberDef()->isFriend()) // don't inherit friends
{
Protection prot = mi->prot();
if (bcd.prot==Protection::Protected)
{
if (prot==Protection::Public) prot=Protection::Protected;
}
else if (bcd.prot==Protection::Private)
{
prot=Protection::Private;
}
Specifier virt=mi->virt();
bool virtualBaseClass = bcd.virt!=Specifier::Normal || mi->virtualBaseClass();
if (virt==Specifier::Normal && bcd.virt!=Specifier::Normal) virt=bcd.virt;
//printf(" %s::%s: [mi.prot=%d, bcd.prot=%d => prot=%d], [mi.virt=%d, bcd.virt=%d => virt=%d] virtualBase=%d\n",
// qPrint(name()),qPrint(mi->memberDef()->name()),
// mi->prot(),bcd.prot,prot,
// mi->virt(),bcd.virt,virt,
// virtualBaseClass
// );
if (prot!=Protection::Private || extractPrivate)
{
if (inlineInheritedMembers)
{
if (!isStandardFunc(mi->memberDef()))
{
//printf(" %s::insertMember '%s'\n",qPrint(name()),qPrint(mi->memberDef()->name()));
internalInsertMember(mi->memberDef(),prot,FALSE);
}
}
//printf("Adding!\n");
std::unique_ptr<MemberInfo> newMi = std::make_unique<MemberInfo>(mi->memberDef(),prot,virt,TRUE,virtualBaseClass);
newMi->setScopePath(bClass->name()+sep+mi->scopePath());
newMi->setAmbigClass(mi->ambigClass());
newMi->setAmbiguityResolutionScope(mi->ambiguityResolutionScope());
newMni->push_back(std::move(newMi));
}
}
}
}
}
}
}
}
/*!
* recursively merges the 'all members' lists of a class base
* with that of this class. Must only be called for classes without
* subclasses!
*/
void ClassDefImpl::mergeMembers()
{
if (m_impl->membersMerged) return;
if (getLanguage()==SrcLangExt::Python) return; // python does not have member overloading, see issue 8480
//printf("> %s::mergeMembers()\n",qPrint(name()));
m_impl->membersMerged=TRUE;
// first merge the members of the base class recursively
for (const auto &bcd : baseClasses())
{
ClassDefMutable *bClass=toClassDefMutable(bcd.classDef);
if (bClass)
{
// merge the members in the base class of this inheritance branch first
bClass->mergeMembers();
}
}
// first merge the member that are not inherited via a virtual base class
// (as this can end up reimplemented via multiple paths, see #10717 for examples)
mergeMembersFromBaseClasses(false);
// then process the member that are inherited via a virtual base class to add the
// ones that are not reimplemented via any path
mergeMembersFromBaseClasses(true);
//printf("< %s::mergeMembers()\n",qPrint(name()));
}
//----------------------------------------------------------------------------
/*! Merges the members of a Objective-C category into this class.
*/
void ClassDefImpl::mergeCategory(ClassDef *cat)
{
AUTO_TRACE();
ClassDefMutable *category = toClassDefMutable(cat);
if (category)
{
bool extractLocalMethods = Config_getBool(EXTRACT_LOCAL_METHODS);
bool makePrivate = category->isLocal();
// in case extract local methods is not enabled we don't add the methods
// of the category in case it is defined in the .m file.
if (makePrivate && !extractLocalMethods) return;
bool isExtension = category->isExtension();
category->setCategoryOf(this);
if (isExtension)
{
category->setArtificial(TRUE);
// copy base classes/protocols from extension
for (const auto &bcd : category->baseClasses())
{
insertBaseClass(bcd.classDef,bcd.usedName,bcd.prot,bcd.virt,bcd.templSpecifiers);
// correct bcd.classDef so that they do no longer derive from
// category, but from this class!
BaseClassList scl = bcd.classDef->subClasses();
for (auto &scd : scl)
{
if (scd.classDef==category)
{
scd.classDef=this;
}
}
bcd.classDef->updateSubClasses(scl);
}
}
// make methods private for categories defined in the .m file
//printf("%s::mergeCategory makePrivate=%d\n",qPrint(name()),makePrivate);
const MemberNameInfoLinkedMap &srcMnd = category->memberNameInfoLinkedMap();
MemberNameInfoLinkedMap &dstMnd = m_impl->allMemberNameInfoLinkedMap;
for (auto &srcMni : srcMnd)
{
MemberNameInfo *dstMni=dstMnd.find(srcMni->memberName());
if (dstMni) // method is already defined in the class
{
AUTO_TRACE_ADD("Existing member {}",srcMni->memberName());
const auto &dstMi = dstMni->front();
const auto &srcMi = srcMni->front();
if (srcMi && dstMi)
{
MemberDefMutable *smdm = toMemberDefMutable(srcMi->memberDef());
MemberDefMutable *dmdm = toMemberDefMutable(dstMi->memberDef());
if (smdm && dmdm)
{
combineDeclarationAndDefinition(smdm,dmdm);
dmdm->setCategory(category);
dmdm->setCategoryRelation(smdm);
smdm->setCategoryRelation(dmdm);
}
}
}
else // new method name
{
AUTO_TRACE_ADD("New member {}",srcMni->memberName());
// create a deep copy of the list
MemberNameInfo *newMni = dstMnd.add(srcMni->memberName());
// copy the member(s) from the category to this class
for (auto &mi : *srcMni)
{
//printf("Adding '%s'\n",qPrint(mi->memberDef->name()));
Protection prot = mi->prot();
//if (makePrivate) prot = Private;
auto newMd = mi->memberDef()->deepCopy();
if (newMd)
{
auto mmd = toMemberDefMutable(newMd.get());
AUTO_TRACE_ADD("Copying member {}",mmd->name());
mmd->moveTo(this);
auto newMi=std::make_unique<MemberInfo>(newMd.get(),prot,mi->virt(),mi->inherited(),mi->virtualBaseClass());
newMi->setScopePath(mi->scopePath());
newMi->setAmbigClass(mi->ambigClass());
newMi->setAmbiguityResolutionScope(mi->ambiguityResolutionScope());
newMni->push_back(std::move(newMi));
// also add the newly created member to the global members list
QCString name = newMd->name();
MemberName *mn = Doxygen::memberNameLinkedMap->add(name);
mmd->setCategory(category);
mmd->setCategoryRelation(mi->memberDef());
auto miMmd = toMemberDefMutable(mi->memberDef());
if (miMmd) miMmd->setCategoryRelation(newMd.get());
if (makePrivate || isExtension)
{
mmd->makeImplementationDetail();
}
internalInsertMember(newMd.get(),prot,FALSE);
mn->push_back(std::move(newMd));
}
}
}
}
}
}
//----------------------------------------------------------------------------
void ClassDefImpl::addUsedClass(ClassDef *cd,const QCString &accessName,
Protection prot)
{
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
bool umlLook = Config_getBool(UML_LOOK);
if (prot==Protection::Private && !extractPrivate) return;
//printf("%s::addUsedClass(%s,%s)\n",qPrint(name()),qPrint(cd->name()),accessName);
auto it = std::find_if(m_impl->usesImplClassList.begin(),
m_impl->usesImplClassList.end(),
[&cd](const auto &ucd) { return ucd.classDef==cd; });
if (it==m_impl->usesImplClassList.end())
{
m_impl->usesImplClassList.emplace_back(cd);
//printf("Adding used class %s to class %s via accessor %s\n",
// qPrint(cd->name()),qPrint(name()),accessName);
it = m_impl->usesImplClassList.end()-1;
}
QCString acc = accessName;
if (umlLook)
{
switch(prot)
{
case Protection::Public: acc.prepend("+"); break;
case Protection::Private: acc.prepend("-"); break;
case Protection::Protected: acc.prepend("#"); break;
case Protection::Package: acc.prepend("~"); break;
}
}
(*it).addAccessor(acc);
}
void ClassDefImpl::addUsedByClass(ClassDef *cd,const QCString &accessName,
Protection prot)
{
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
bool umlLook = Config_getBool(UML_LOOK);
if (prot==Protection::Private && !extractPrivate) return;
//printf("%s::addUsedByClass(%s,%s)\n",qPrint(name()),qPrint(cd->name()),accessName);
//
auto it = std::find_if(m_impl->usedByImplClassList.begin(),
m_impl->usedByImplClassList.end(),
[&cd](const auto &ucd) { return ucd.classDef==cd; });
if (it==m_impl->usedByImplClassList.end())
{
m_impl->usedByImplClassList.emplace_back(cd);
//printf("Adding used by class %s to class %s\n",
// qPrint(cd->name()),qPrint(name()));
it = m_impl->usedByImplClassList.end()-1;
}
QCString acc = accessName;
if (umlLook)
{
switch(prot)
{
case Protection::Public: acc.prepend("+"); break;
case Protection::Private: acc.prepend("-"); break;
case Protection::Protected: acc.prepend("#"); break;
case Protection::Package: acc.prepend("~"); break;
}
}
(*it).addAccessor(acc);
}
QCString ClassDefImpl::compoundTypeString() const
{
return getCompoundTypeString(getLanguage(),m_impl->compType,isJavaEnum());
}
QCString ClassDefImpl::getOutputFileBase() const
{
bool inlineGroupedClasses = Config_getBool(INLINE_GROUPED_CLASSES);
bool inlineSimpleClasses = Config_getBool(INLINE_SIMPLE_STRUCTS);
if (!Doxygen::generatingXmlOutput)
{
Definition *scope=nullptr;
if (inlineGroupedClasses && !partOfGroups().empty())
{
// point to the group that embeds this class
return partOfGroups().front()->getOutputFileBase();
}
else if (inlineSimpleClasses && m_impl->isSimple && !partOfGroups().empty())
{
// point to simple struct inside a group
return partOfGroups().front()->getOutputFileBase();
}
else if (inlineSimpleClasses && m_impl->isSimple && (scope=getOuterScope()))
{
if (scope==Doxygen::globalScope && getFileDef() && getFileDef()->isLinkableInProject()) // simple struct embedded in file
{
return getFileDef()->getOutputFileBase();
}
else if (scope->isLinkableInProject()) // simple struct embedded in other container (namespace/group/class)
{
return getOuterScope()->getOutputFileBase();
}
}
}
if (m_impl->templateMaster)
{
// point to the template of which this class is an instance
return m_impl->templateMaster->getOutputFileBase();
}
return m_impl->fileName;
}
QCString ClassDefImpl::getInstanceOutputFileBase() const
{
return m_impl->fileName;
}
QCString ClassDefImpl::getSourceFileBase() const
{
if (m_impl->templateMaster)
{
return m_impl->templateMaster->getSourceFileBase();
}
else
{
return DefinitionMixin::getSourceFileBase();
}
}
void ClassDefImpl::setGroupDefForAllMembers(GroupDef *gd,Grouping::GroupPri_t pri,const QCString &fileName,int startLine,bool hasDocs)
{
gd->addClass(this);
//printf("ClassDefImpl::setGroupDefForAllMembers(%s)\n",qPrint(gd->name()));
for (auto &mni : m_impl->allMemberNameInfoLinkedMap)
{
for (auto &mi : *mni)
{
MemberDefMutable *md = toMemberDefMutable(mi->memberDef());
if (md)
{
md->setGroupDef(gd,pri,fileName,startLine,hasDocs);
gd->insertMember(md,TRUE);
ClassDefMutable *innerClass = toClassDefMutable(md->getClassDefOfAnonymousType());
if (innerClass) innerClass->setGroupDefForAllMembers(gd,pri,fileName,startLine,hasDocs);
}
}
}
}
void ClassDefImpl::addInnerCompound(Definition *d)
{
//printf("**** %s::addInnerCompound(%s)\n",qPrint(name()),qPrint(d->name()));
if (d->definitionType()==Definition::TypeClass) // only classes can be
// nested in classes.
{
m_impl->innerClasses.add(d->localName(),toClassDef(d));
}
}
const Definition *ClassDefImpl::findInnerCompound(const QCString &name) const
{
return m_impl->innerClasses.find(name);
}
ClassDef *ClassDefImpl::insertTemplateInstance(const QCString &fileName,
int startLine, int startColumn, const QCString &templSpec,bool &freshInstance) const
{
freshInstance = FALSE;
auto it = std::find_if(m_impl->templateInstances.begin(),
m_impl->templateInstances.end(),
[&templSpec](const auto &ti) { return templSpec==ti.templSpec; });
ClassDefMutable *templateClass=nullptr;
if (it!=m_impl->templateInstances.end())
{
templateClass = toClassDefMutable((*it).classDef);
}
if (templateClass==nullptr)
{
QCString tcname = removeRedundantWhiteSpace(name()+templSpec);
AUTO_TRACE("New template instance class name='{}' templSpec='{}' inside '{}' hidden={}",
name(),templSpec,name(),isHidden());
ClassDef *foundCd = Doxygen::classLinkedMap->find(tcname);
if (foundCd)
{
return foundCd;
}
templateClass =
toClassDefMutable(
Doxygen::classLinkedMap->add(tcname,
std::unique_ptr<ClassDef>(
new ClassDefImpl(fileName,startLine,startColumn,tcname,ClassDef::Class))));
if (templateClass)
{
templateClass->setTemplateMaster(this);
templateClass->setOuterScope(getOuterScope());
templateClass->setHidden(isHidden());
templateClass->setArtificial(isArtificial());
templateClass->setImplicitTemplateInstance(true);
m_impl->templateInstances.emplace_back(templSpec,templateClass);
// also add nested classes
for (const auto &innerCd : m_impl->innerClasses)
{
QCString innerName = tcname+"::"+innerCd->localName();
ClassDefMutable *innerClass =
toClassDefMutable(
Doxygen::classLinkedMap->add(innerName,
std::unique_ptr<ClassDef>(
new ClassDefImpl(fileName,startLine,startColumn,innerName,ClassDef::Class))));
if (innerClass)
{
templateClass->addInnerCompound(innerClass);
innerClass->setOuterScope(templateClass);
innerClass->setHidden(isHidden());
innerClass->setArtificial(TRUE);
innerClass->setImplicitTemplateInstance(true);
}
}
freshInstance=TRUE;
}
}
return templateClass;
}
void ClassDefImpl::insertExplicitTemplateInstance(ClassDef *templateClass,const QCString &templSpec)
{
m_impl->templateInstances.emplace_back(templSpec,templateClass);
}
void ClassDefImpl::setTemplateBaseClassNames(const TemplateNameMap &templateNames)
{
m_impl->templBaseClassNames = templateNames;
}
const TemplateNameMap &ClassDefImpl::getTemplateBaseClassNames() const
{
return m_impl->templBaseClassNames;
}
void ClassDefImpl::addMembersToTemplateInstance(const ClassDef *cd,const ArgumentList &templateArguments,const QCString &templSpec)
{
//printf("%s::addMembersToTemplateInstance(%s,%s)\n",qPrint(name()),qPrint(cd->name()),templSpec);
for (const auto &mni : cd->memberNameInfoLinkedMap())
{
for (const auto &mi : *mni)
{
auto actualArguments_p = stringToArgumentList(getLanguage(),templSpec);
MemberDef *md = mi->memberDef();
auto imd = md->createTemplateInstanceMember(templateArguments,actualArguments_p);
//printf("%s->setMemberClass(%p)\n",qPrint(imd->name()),this);
auto mmd = toMemberDefMutable(imd.get());
mmd->setMemberClass(this);
mmd->setTemplateMaster(md);
mmd->setDocumentation(md->documentation(),md->docFile(),md->docLine());
mmd->setBriefDescription(md->briefDescription(),md->briefFile(),md->briefLine());
mmd->setInbodyDocumentation(md->inbodyDocumentation(),md->inbodyFile(),md->inbodyLine());
mmd->setMemberSpecifiers(md->getMemberSpecifiers());
mmd->setMemberGroupId(md->getMemberGroupId());
mmd->setArtificial(true);
insertMember(imd.get());
//printf("Adding member=%s %s%s to class %s templSpec %s\n",
// imd->typeString(),qPrint(imd->name()),imd->argsString(),
// qPrint(imd->getClassDef()->name()),templSpec);
// insert imd in the list of all members
//printf("Adding member=%s class=%s\n",qPrint(imd->name()),qPrint(name()));
MemberName *mn = Doxygen::memberNameLinkedMap->add(imd->name());
mn->push_back(std::move(imd));
}
}
// also instantatie members for nested classes
for (const auto &innerCd : cd->getClasses())
{
ClassDefMutable *ncd = toClassDefMutable(m_impl->innerClasses.find(innerCd->localName()));
if (ncd)
{
ncd->addMembersToTemplateInstance(innerCd,cd->templateArguments(),templSpec);
}
}
}
QCString ClassDefImpl::getReference() const
{
if (m_impl->templateMaster)
{
return m_impl->templateMaster->getReference();
}
else
{
return DefinitionMixin::getReference();
}
}
bool ClassDefImpl::isReference() const
{
if (m_impl->templateMaster)
{
return m_impl->templateMaster->isReference();
}
else
{
return DefinitionMixin::isReference();
}
}
ArgumentLists ClassDefImpl::getTemplateParameterLists() const
{
ArgumentLists result;
Definition *d=getOuterScope();
while (d && d->definitionType()==Definition::TypeClass)
{
result.insert(result.begin(),toClassDef(d)->templateArguments());
d = d->getOuterScope();
}
if (!templateArguments().empty())
{
result.push_back(templateArguments());
}
return result;
}
QCString ClassDefImpl::qualifiedNameWithTemplateParameters(
const ArgumentLists *actualParams,uint32_t *actualParamIndex) const
{
return makeQualifiedNameWithTemplateParameters(this,actualParams,actualParamIndex);
}
QCString ClassDefImpl::className() const
{
if (m_impl->className.isEmpty())
{
return localName();
}
else
{
return m_impl->className;
}
}
void ClassDefImpl::setClassName(const QCString &name)
{
m_impl->className = name;
}
void ClassDefImpl::addListReferences()
{
SrcLangExt lang = getLanguage();
if (!isLinkableInProject()) return;
//printf("ClassDef(%s)::addListReferences()\n",qPrint(name()));
{
const RefItemVector &xrefItems = xrefListItems();
addRefItem(xrefItems,
qualifiedName(),
theTranslator->trCompoundType(compoundType(), lang),
getOutputFileBase(),
displayName(),
QCString(),
this
);
}
for (const auto &mg : m_impl->memberGroups)
{
mg->addListReferences(this);
}
for (auto &ml : m_impl->memberLists)
{
if (ml->listType().isDetailed())
{
ml->addListReferences(this);
}
}
}
const MemberDef *ClassDefImpl::getMemberByName(const QCString &name) const
{
const MemberDef *xmd = nullptr;
MemberNameInfo *mni = m_impl->allMemberNameInfoLinkedMap.find(name);
if (mni)
{
const int maxInheritanceDepth = 100000;
int mdist=maxInheritanceDepth;
for (auto &mi : *mni)
{
const ClassDef *mcd=mi->memberDef()->getClassDef();
int m=minClassDistance(this,mcd);
//printf("found member in %s linkable=%d m=%d\n",
// qPrint(mcd->name()),mcd->isLinkable(),m);
if (m<mdist)
{
mdist=m;
xmd=mi->memberDef();
}
}
}
//printf("getMemberByName(%s)=%p\n",qPrint(name),xmd);
return xmd;
}
bool ClassDefImpl::isAccessibleMember(const MemberDef *md) const
{
return md->getClassDef() && isBaseClass(md->getClassDef(),TRUE,QCString());
}
MemberList *ClassDefImpl::getMemberList(MemberListType lt) const
{
for (auto &ml : m_impl->memberLists)
{
if (ml->listType()==lt)
{
return ml.get();
}
}
return nullptr;
}
void ClassDefImpl::addMemberToList(MemberListType lt,MemberDef *md,bool isBrief)
{
AUTO_TRACE("{} md={} lt={} isBrief={}",name(),md->name(),lt,isBrief);
bool sortBriefDocs = Config_getBool(SORT_BRIEF_DOCS);
bool sortMemberDocs = Config_getBool(SORT_MEMBER_DOCS);
const auto &ml = m_impl->memberLists.get(lt,MemberListContainer::Class);
ml->setNeedsSorting((isBrief && sortBriefDocs) || (!isBrief && sortMemberDocs));
ml->push_back(md);
// for members in the declaration lists we set the section, needed for member grouping
if (!ml->listType().isDetailed())
{
MemberDefMutable *mdm = toMemberDefMutable(md);
if (mdm)
{
mdm->setSectionList(this,ml.get());
}
}
}
void ClassDefImpl::sortMemberLists()
{
for (auto &ml : m_impl->memberLists)
{
if (ml->needsSorting()) { ml->sort(); ml->setNeedsSorting(FALSE); }
}
std::stable_sort(m_impl->innerClasses.begin(),
m_impl->innerClasses.end(),
[](const auto &c1,const auto &c2)
{
return Config_getBool(SORT_BY_SCOPE_NAME) ?
qstricmp_sort(c1->name(), c2->name() )<0 :
qstricmp_sort(c1->className(), c2->className())<0 ;
});
}
int ClassDefImpl::countMemberDeclarations(MemberListType lt,const ClassDef *inheritedFrom,
MemberListType lt2,bool invert,bool showAlways,ClassDefSet &visitedClasses) const
{
//printf("%s: countMemberDeclarations for %d and %d\n",qPrint(name()),lt.to_int(),lt2.to_int());
int count=0;
MemberList * ml = getMemberList(lt);
MemberList * ml2 = getMemberList(lt2);
if (getLanguage()!=SrcLangExt::VHDL) // use specific declarations function
{
if (ml)
{
count+=ml->numDecMembers();
//printf("-> ml=%d\n",ml->numDecMembers());
}
if (ml2)
{
count+=ml2->numDecMembers();
//printf("-> ml2=%d\n",ml2->numDecMembers());
}
// also include grouped members that have their own section in the class (see bug 722759)
if (inheritedFrom)
{
for (const auto &mg : m_impl->memberGroups)
{
count+=mg->countGroupedInheritedMembers(lt);
if (!lt2.isInvalid()) count+=mg->countGroupedInheritedMembers(lt2);
}
}
bool inlineInheritedMembers = Config_getBool(INLINE_INHERITED_MEMB);
if (!inlineInheritedMembers) // show inherited members as separate lists
{
count+=countInheritedDecMembers(lt,inheritedFrom,invert,showAlways,visitedClasses);
}
}
//printf("-> %d\n",count);
return count;
}
void ClassDefImpl::setAnonymousEnumType()
{
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
MemberList * ml = getMemberList(lmd->type);
if (ml)
{
ml->setAnonymousEnumType();
}
}
}
else if (lde->kind()==LayoutDocEntry::MemberGroups)
{
for (const auto &mg : m_impl->memberGroups)
{
mg->setAnonymousEnumType();
}
}
}
}
void ClassDefImpl::countMembers()
{
for (auto &ml : m_impl->memberLists)
{
ml->countDecMembers();
ml->countDocMembers();
}
for (const auto &mg : m_impl->memberGroups)
{
mg->countDecMembers();
mg->countDocMembers();
}
}
int ClassDefImpl::countInheritedDecMembers(MemberListType lt,
const ClassDef *inheritedFrom,bool invert,bool showAlways,
ClassDefSet &visitedClasses) const
{
int inhCount = 0;
int count = countMembersIncludingGrouped(lt,inheritedFrom,FALSE);
bool process = count>0;
//printf("%s: countInheritedDecMembers: lt=%d process=%d count=%d invert=%d\n",
// qPrint(name()),lt.to_int(),process,count,invert);
if ((process^invert) || showAlways)
{
for (const auto &ibcd : m_impl->inherits)
{
ClassDefMutable *icd = toClassDefMutable(ibcd.classDef);
MemberListType lt1 = MemberListType::Invalid();
MemberListType lt2 = MemberListType::Invalid();
if (icd && icd->isLinkable())
{
convertProtectionLevel(lt,ibcd.prot,<1,<2);
//printf("%s: convert %d->(%d,%d) prot=%d\n",
// qPrint(icd->name()),lt.to_int(),lt1.to_int(),lt2.to_int(),ibcd.prot);
if (visitedClasses.find(icd)==visitedClasses.end())
{
visitedClasses.insert(icd); // guard for multiple virtual inheritance
if (!lt1.isInvalid())
{
inhCount+=icd->countMemberDeclarations(lt1,inheritedFrom,lt2,FALSE,TRUE,visitedClasses);
}
}
}
}
}
return inhCount;
}
void ClassDefImpl::getTitleForMemberListType(MemberListType type,
QCString &title,QCString &subtitle) const
{
SrcLangExt lang = getLanguage();
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd && lmd->type==type)
{
title = lmd->title(lang);
subtitle = lmd->subtitle(lang);
return;
}
}
}
title="";
subtitle="";
}
int ClassDefImpl::countAdditionalInheritedMembers() const
{
int totalCount=0;
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd && lmd->type!=MemberListType::Friends()) // friendship is not inherited
{
ClassDefSet visited;
totalCount+=countInheritedDecMembers(lmd->type,this,TRUE,FALSE,visited);
}
}
}
//printf("countAdditionalInheritedMembers()=%d\n",totalCount);
return totalCount;
}
void ClassDefImpl::writeAdditionalInheritedMembers(OutputList &ol) const
{
//printf("**** writeAdditionalInheritedMembers()\n");
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Class))
{
if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd && lmd->type!=MemberListType::Friends())
{
ClassDefSet visited;
writeInheritedMemberDeclarations(ol,visited,lmd->type,MemberListType::Invalid(),lmd->title(getLanguage()),this,TRUE,FALSE);
}
}
}
}
int ClassDefImpl::countMembersIncludingGrouped(MemberListType lt,
const ClassDef *inheritedFrom,bool additional) const
{
int count=0;
MemberList *ml = getMemberList(lt);
if (ml)
{
count=ml->countInheritableMembers(inheritedFrom);
}
//printf("%s:countMembersIncludingGrouped: count=%d\n",qPrint(name()),count);
for (const auto &mg : m_impl->memberGroups)
{
bool hasOwnSection = !mg->allMembersInSameSection() ||
!m_impl->subGrouping; // group is in its own section
if ((additional && hasOwnSection) || (!additional && !hasOwnSection))
{
count+=mg->countGroupedInheritedMembers(lt);
}
}
//printf("%s:countMembersIncludingGrouped(lt=%s,%s)=%d\n",
// qPrint(name()),qPrint(lt.to_string()),ml?qPrint(ml->listType().toLabel()):"<none>",count);
return count;
}
void ClassDefImpl::writeInheritedMemberDeclarations(OutputList &ol,ClassDefSet &visitedClasses,
MemberListType lt,MemberListType lt2,const QCString &title,
const ClassDef *inheritedFrom,bool invert,bool showAlways) const
{
int count = countMembersIncludingGrouped(lt,inheritedFrom,FALSE);
bool process = count>0;
//printf("%s: writeInheritedMemberDec: lt=%s process=%d invert=%d always=%d\n",
// qPrint(name()),qPrint(lt.to_string()),process,invert,showAlways);
if ((process^invert) || showAlways)
{
for (const auto &ibcd : m_impl->inherits)
{
ClassDefMutable *icd=toClassDefMutable(ibcd.classDef);
if (icd && icd->isLinkable())
{
MemberListType lt1 = MemberListType::Invalid();
MemberListType lt3 = MemberListType::Invalid();
convertProtectionLevel(lt,ibcd.prot,<1,<3);
if (lt2.isInvalid() && !lt3.isInvalid())
{
lt2=lt3;
}
//printf("%s:convert %s->(%s,%s) prot=%d\n",qPrint(icd->name()),qPrint(lt.to_string()),
// qPrint(lt1.to_string()),qPrint(lt2.to_string()),ibcd.prot);
if (visitedClasses.find(icd)==visitedClasses.end())
{
visitedClasses.insert(icd); // guard for multiple virtual inheritance
if (!lt1.isInvalid())
{
//printf("--> writeMemberDeclarations for type %s\n",qPrint(lt1.to_string()));
icd->writeMemberDeclarations(ol,visitedClasses,lt1,
title,QCString(),FALSE,inheritedFrom,lt2,FALSE,TRUE);
}
}
else
{
//printf("%s: class already visited!\n",qPrint(icd->name()));
}
}
}
}
}
void ClassDefImpl::writeMemberDeclarations(OutputList &ol,ClassDefSet &visitedClasses,
MemberListType lt,const QCString &title,
const QCString &subTitle,bool showInline,const ClassDef *inheritedFrom,MemberListType lt2,
bool invert,bool showAlways) const
{
//printf("%s: ClassDefImpl::writeMemberDeclarations lt=%s lt2=%s\n",qPrint(name()),qPrint(lt.to_string()),qPrint(lt2.to_string()));
MemberList * ml = getMemberList(lt);
MemberList * ml2 = getMemberList(lt2);
if (getLanguage()==SrcLangExt::VHDL) // use specific declarations function
{
static const ClassDef *cdef;
if (cdef!=this)
{ // only one inline link
VhdlDocGen::writeInlineClassLink(this,ol);
cdef=this;
}
if (ml)
{
VhdlDocGen::writeVhdlDeclarations(ml,ol,nullptr,this,nullptr,nullptr,nullptr);
}
}
else
{
//printf("%s::writeMemberDeclarations(%s) ml=%p ml2=%p\n",qPrint(name()),qPrint(title),ml,ml2);
QCString tt = title, st = subTitle;
if (ml)
{
//printf(" writeDeclarations type=%s count=%d\n",qPrint(lt.to_string()),ml->numDecMembers());
ml->writeDeclarations(ol,this,nullptr,nullptr,nullptr,nullptr,tt,st,FALSE,showInline,inheritedFrom,lt,true);
tt.clear();
st.clear();
}
if (ml2)
{
//printf(" writeDeclarations type=%s count=%d\n",qPrint(lt2.to_string()),ml2->numDecMembers());
ml2->writeDeclarations(ol,this,nullptr,nullptr,nullptr,nullptr,tt,st,FALSE,showInline,inheritedFrom,lt,ml==nullptr);
}
bool inlineInheritedMembers = Config_getBool(INLINE_INHERITED_MEMB);
if (!inlineInheritedMembers) // show inherited members as separate lists
{
writeInheritedMemberDeclarations(ol,visitedClasses,lt,lt2,title,
inheritedFrom ? inheritedFrom : this,
invert,showAlways);
}
}
}
void ClassDefImpl::addGroupedInheritedMembers(OutputList &ol,MemberListType lt,
const ClassDef *inheritedFrom,const QCString &inheritId) const
{
//printf("** %s::addGroupedInheritedMembers() inheritId=%s\n",qPrint(name()),qPrint(inheritId));
for (const auto &mg : m_impl->memberGroups)
{
if (!mg->allMembersInSameSection() || !m_impl->subGrouping) // group is in its own section
{
mg->addGroupedInheritedMembers(ol,this,lt,inheritedFrom,inheritId);
}
}
}
void ClassDefImpl::writeMemberDocumentation(OutputList &ol,MemberListType lt,const QCString &title,bool showInline) const
{
//printf("%s: ClassDefImpl::writeMemberDocumentation()\n",qPrint(name()));
MemberList * ml = getMemberList(lt);
if (ml) ml->writeDocumentation(ol,displayName(),this,title,FALSE,showInline);
}
void ClassDefImpl::writeSimpleMemberDocumentation(OutputList &ol,MemberListType lt) const
{
//printf("%s: ClassDefImpl::writeSimpleMemberDocumentation()\n",qPrint(name()));
MemberList * ml = getMemberList(lt);
if (ml) ml->writeSimpleDocumentation(ol,this);
}
void ClassDefImpl::writePlainMemberDeclaration(OutputList &ol,
MemberListType lt,bool inGroup,
int indentLevel,const ClassDef *inheritedFrom,const QCString &inheritId) const
{
//printf("%s: ClassDefImpl::writePlainMemberDeclaration()\n",qPrint(name()));
MemberList * ml = getMemberList(lt);
if (ml)
{
ml->writePlainDeclarations(ol,inGroup,this,nullptr,nullptr,nullptr,nullptr,indentLevel,inheritedFrom,inheritId);
}
}
bool ClassDefImpl::isLocal() const
{
return m_impl->isLocal;
}
ClassLinkedRefMap ClassDefImpl::getClasses() const
{
return m_impl->innerClasses;
}
ClassDefImpl::CompoundType ClassDefImpl::compoundType() const
{
return m_impl->compType;
}
const BaseClassList &ClassDefImpl::baseClasses() const
{
return m_impl->inherits;
}
void ClassDefImpl::updateBaseClasses(const BaseClassList &bcd)
{
m_impl->inherits = bcd;
}
const BaseClassList &ClassDefImpl::subClasses() const
{
return m_impl->inheritedBy;
}
void ClassDefImpl::updateSubClasses(const BaseClassList &bcd)
{
m_impl->inheritedBy = bcd;
}
const MemberNameInfoLinkedMap &ClassDefImpl::memberNameInfoLinkedMap() const
{
return m_impl->allMemberNameInfoLinkedMap;
}
void ClassDefImpl::sortAllMembersList()
{
std::stable_sort(m_impl->allMemberNameInfoLinkedMap.begin(),
m_impl->allMemberNameInfoLinkedMap.end(),
[](const auto &m1,const auto &m2)
{
return qstricmp_sort(m1->memberName(),m2->memberName())<0;
});
}
Protection ClassDefImpl::protection() const
{
return m_impl->prot;
}
const ArgumentList &ClassDefImpl::templateArguments() const
{
return m_impl->tempArgs;
}
FileDef *ClassDefImpl::getFileDef() const
{
return m_impl->fileDef;
}
ModuleDef *ClassDefImpl::getModuleDef() const
{
return m_impl->moduleDef;
}
const TemplateInstanceList &ClassDefImpl::getTemplateInstances() const
{
return m_impl->templateInstances;
}
const ClassDef *ClassDefImpl::templateMaster() const
{
return m_impl->templateMaster;
}
bool ClassDefImpl::isImplicitTemplateInstance() const
{
return m_impl->implicitTemplateInstance;
}
void ClassDefImpl::setImplicitTemplateInstance(bool b)
{
m_impl->implicitTemplateInstance = b;
}
bool ClassDefImpl::isTemplate() const
{
return !m_impl->tempArgs.empty();
}
const IncludeInfo *ClassDefImpl::includeInfo() const
{
return m_impl->incInfo.get();
}
const UsesClassList &ClassDefImpl::usedImplementationClasses() const
{
return m_impl->usesImplClassList;
}
const UsesClassList &ClassDefImpl::usedByImplementationClasses() const
{
return m_impl->usedByImplClassList;
}
const ConstraintClassList &ClassDefImpl::templateTypeConstraints() const
{
return m_impl->constraintClassList;
}
bool ClassDefImpl::isTemplateArgument() const
{
return m_impl->isTemplArg;
}
bool ClassDefImpl::isAbstract() const
{
return m_impl->isAbstract || m_impl->spec.isAbstract();
}
bool ClassDefImpl::isFinal() const
{
return m_impl->spec.isFinal();
}
bool ClassDefImpl::isSealed() const
{
return m_impl->spec.isSealed();
}
bool ClassDefImpl::isPublished() const
{
return m_impl->spec.isPublished();
}
bool ClassDefImpl::isForwardDeclared() const
{
return m_impl->spec.isForwardDecl();
}
bool ClassDefImpl::isInterface() const
{
return m_impl->spec.isInterface();
}
bool ClassDefImpl::isObjectiveC() const
{
return getLanguage()==SrcLangExt::ObjC;
}
bool ClassDefImpl::isFortran() const
{
return getLanguage()==SrcLangExt::Fortran;
}
bool ClassDefImpl::isCSharp() const
{
return getLanguage()==SrcLangExt::CSharp;
}
ClassDef *ClassDefImpl::categoryOf() const
{
return m_impl->categoryOf;
}
const MemberLists &ClassDefImpl::getMemberLists() const
{
return m_impl->memberLists;
}
const MemberGroupList &ClassDefImpl::getMemberGroups() const
{
return m_impl->memberGroups;
}
void ClassDefImpl::setFileDef(FileDef *fd)
{
m_impl->fileDef = fd;
}
void ClassDefImpl::setModuleDef(ModuleDef *mod)
{
m_impl->moduleDef = mod;
}
void ClassDefImpl::setSubGrouping(bool enabled)
{
m_impl->subGrouping = enabled;
}
void ClassDefImpl::setProtection(Protection p)
{
m_impl->prot=p;
if (getLanguage()==SrcLangExt::VHDL && VhdlDocGen::convert(p)==VhdlDocGen::ARCHITECTURECLASS)
{
m_impl->className = name();
}
}
void ClassDefImpl::setIsStatic(bool b)
{
m_impl->isStatic=b;
}
void ClassDefImpl::setCompoundType(CompoundType t)
{
m_impl->compType = t;
}
void ClassDefImpl::setTemplateMaster(const ClassDef *tm)
{
assert(tm!=this);
m_impl->templateMaster=tm;
}
void ClassDefImpl::makeTemplateArgument(bool b)
{
m_impl->isTemplArg = b;
}
void ClassDefImpl::setCategoryOf(ClassDef *cd)
{
m_impl->categoryOf = cd;
}
void ClassDefImpl::setUsedOnly(bool b)
{
m_impl->usedOnly = b;
}
bool ClassDefImpl::isUsedOnly() const
{
return m_impl->usedOnly;
}
bool ClassDefImpl::isSimple() const
{
return m_impl->isSimple;
}
const MemberDef *ClassDefImpl::isSmartPointer() const
{
return m_impl->arrowOperator;
}
void ClassDefImpl::reclassifyMember(MemberDefMutable *md,MemberType t)
{
md->setMemberType(t);
for (auto &ml : m_impl->memberLists)
{
ml->remove(md);
}
insertMember(md);
}
QCString ClassDefImpl::anchor() const
{
QCString anc;
if (isEmbeddedInOuterScope() && !Doxygen::generatingXmlOutput)
{
if (m_impl->templateMaster)
{
// point to the template of which this class is an instance
anc = m_impl->templateMaster->getOutputFileBase();
}
else
{
anc = m_impl->fileName;
}
}
return anc;
}
bool ClassDefImpl::isEmbeddedInOuterScope() const
{
bool inlineGroupedClasses = Config_getBool(INLINE_GROUPED_CLASSES);
bool inlineSimpleClasses = Config_getBool(INLINE_SIMPLE_STRUCTS);
Definition *container = getOuterScope();
bool containerLinkable =
container &&
(
(container==Doxygen::globalScope && getFileDef() && getFileDef()->isLinkableInProject()) || // global class in documented file
container->isLinkableInProject() // class in documented scope
);
// inline because of INLINE_GROUPED_CLASSES=YES ?
bool b1 = (inlineGroupedClasses && !partOfGroups().empty()); // a grouped class
// inline because of INLINE_SIMPLE_STRUCTS=YES ?
bool b2 = (inlineSimpleClasses && m_impl->isSimple && // a simple class
(containerLinkable || // in a documented container
!partOfGroups().empty() // or part of a group
)
);
//printf("%s::isEmbeddedInOuterScope(): inlineGroupedClasses=%d "
// "inlineSimpleClasses=%d partOfGroups()=%p m_impl->isSimple=%d "
// "getOuterScope()=%s b1=%d b2=%d\n",
// qPrint(name()),inlineGroupedClasses,inlineSimpleClasses,
// partOfGroups().pointer(),m_impl->isSimple,getOuterScope()?qPrint(getOuterScope()->name()):"<none>",b1,b2);
return b1 || b2; // either reason will do
}
const ClassDef *ClassDefImpl::tagLessReference() const
{
return m_impl->tagLessRef;
}
void ClassDefImpl::setTagLessReference(const ClassDef *cd)
{
m_impl->tagLessRef = cd;
}
void ClassDefImpl::removeMemberFromLists(MemberDef *md)
{
for (auto &ml : m_impl->memberLists)
{
ml->remove(md);
}
}
bool ClassDefImpl::isJavaEnum() const
{
return m_impl->isJavaEnum;
}
void ClassDefImpl::setClassSpecifier(TypeSpecifier spec)
{
m_impl->spec = spec;
}
void ClassDefImpl::addQualifiers(const StringVector &qualifiers)
{
for (const auto &sx : qualifiers)
{
bool alreadyAdded = std::find(m_impl->qualifiers.begin(), m_impl->qualifiers.end(), sx) != m_impl->qualifiers.end();
if (!alreadyAdded)
{
m_impl->qualifiers.push_back(sx);
}
}
}
StringVector ClassDefImpl::getQualifiers() const
{
return m_impl->qualifiers;
}
bool ClassDefImpl::containsOverload(const MemberDef *md) const
{
AUTO_TRACE("name={}",md->name());
const auto &mni = m_impl->allMemberNameInfoLinkedMap.find(md->name());
if (mni)
{
for (const auto &mi : *mni)
{
const MemberDef *classMd = mi->memberDef();
const ArgumentList &classAl = classMd->argumentList();
const ArgumentList &al = md->argumentList();
bool found = matchArguments2(
classMd->getOuterScope(),classMd->getFileDef(),&classAl,
md->getOuterScope(),md->getFileDef(),&al,
true,getLanguage()
);
if (found)
{
AUTO_TRACE_EXIT("true");
return true;
}
}
}
AUTO_TRACE_EXIT("false");
return false;
}
bool ClassDefImpl::isExtension() const
{
QCString n = name();
int si = n.find('(');
int ei = n.find(')');
bool b = ei>si && n.mid(si+1,ei-si-1).stripWhiteSpace().isEmpty();
return b;
}
const FileList &ClassDefImpl::usedFiles() const
{
return m_impl->files;
}
const ArgumentList &ClassDefImpl::typeConstraints() const
{
return m_impl->typeConstraints;
}
const ExampleList &ClassDefImpl::getExamples() const
{
return m_impl->examples;
}
bool ClassDefImpl::subGrouping() const
{
return m_impl->subGrouping;
}
bool ClassDefImpl::isSliceLocal() const
{
return m_impl->spec.isLocal();
}
void ClassDefImpl::setMetaData(const QCString &md)
{
m_impl->metaData = md;
}
QCString ClassDefImpl::collaborationGraphFileName() const
{
return m_impl->collabFileName;
}
QCString ClassDefImpl::inheritanceGraphFileName() const
{
return m_impl->inheritFileName;
}
void ClassDefImpl::overrideInheritanceGraph(CLASS_GRAPH_t e)
{
m_impl->typeInheritanceGraph=e;
}
CLASS_GRAPH_t ClassDefImpl::hasInheritanceGraph() const
{
return m_impl->typeInheritanceGraph;
}
CodeSymbolType ClassDefImpl::codeSymbolType() const
{
switch (compoundType())
{
case Class: return CodeSymbolType::Class; break;
case Struct: return CodeSymbolType::Struct; break;
case Union: return CodeSymbolType::Union; break;
case Interface: return CodeSymbolType::Interface; break;
case Protocol: return CodeSymbolType::Protocol; break;
case Category: return CodeSymbolType::Category; break;
case Exception: return CodeSymbolType::Exception; break;
case Service: return CodeSymbolType::Service; break;
case Singleton: return CodeSymbolType::Singleton; break;
}
return CodeSymbolType::Class;
}
void ClassDefImpl::overrideCollaborationGraph(bool e)
{
m_impl->hasCollaborationGraph=e;
}
bool ClassDefImpl::hasCollaborationGraph() const
{
return m_impl->hasCollaborationGraph;
}
// --- Cast functions
//
ClassDef *toClassDef(Definition *d)
{
if (d && (typeid(*d)==typeid(ClassDefImpl) || typeid(*d)==typeid(ClassDefAliasImpl)))
{
return static_cast<ClassDef*>(d);
}
else
{
return nullptr;
}
}
ClassDef *toClassDef(DefinitionMutable *md)
{
Definition *d = toDefinition(md);
if (d && typeid(*d)==typeid(ClassDefImpl))
{
return static_cast<ClassDef*>(d);
}
else
{
return nullptr;
}
}
const ClassDef *toClassDef(const Definition *d)
{
if (d && (typeid(*d)==typeid(ClassDefImpl) || typeid(*d)==typeid(ClassDefAliasImpl)))
{
return static_cast<const ClassDef*>(d);
}
else
{
return nullptr;
}
}
ClassDefMutable *toClassDefMutable(Definition *d)
{
if (d && typeid(*d)==typeid(ClassDefImpl))
{
return static_cast<ClassDefMutable*>(d);
}
else
{
return nullptr;
}
}
// --- Helpers
/*! Get a class definition given its name.
* Returns nullptr if the class is not found.
*/
ClassDef *getClass(const QCString &n)
{
if (n.isEmpty()) return nullptr;
return Doxygen::classLinkedMap->find(n);
}
bool classHasVisibleRoot(const BaseClassList &bcl)
{
for (const auto &bcd : bcl)
{
const ClassDef *cd=bcd.classDef;
if (cd->isVisibleInHierarchy()) return true;
if (classHasVisibleRoot(cd->baseClasses())) return true;
}
return false;
}
bool classHasVisibleChildren(const ClassDef *cd)
{
BaseClassList bcl;
if (cd->getLanguage()==SrcLangExt::VHDL) // reverse baseClass/subClass relation
{
if (cd->baseClasses().empty()) return FALSE;
bcl=cd->baseClasses();
}
else
{
if (cd->subClasses().empty()) return FALSE;
bcl=cd->subClasses();
}
for (const auto &bcd : bcl)
{
if (bcd.classDef->isVisibleInHierarchy())
{
return TRUE;
}
}
return FALSE;
}
bool classVisibleInIndex(const ClassDef *cd)
{
bool allExternals = Config_getBool(ALLEXTERNALS);
return (allExternals && cd->isLinkable()) || cd->isLinkableInProject();
}
//----------------------------------------------------------------------
// recursive function that returns the number of branches in the
// inheritance tree that the base class 'bcd' is below the class 'cd'
int minClassDistance(const ClassDef *cd,const ClassDef *bcd,int level)
{
const int maxInheritanceDepth = 100000;
if (bcd->categoryOf()) // use class that is being extended in case of
// an Objective-C category
{
bcd=bcd->categoryOf();
}
if (cd==bcd) return level;
if (level==256)
{
warn_uncond("class %s seem to have a recursive "
"inheritance relation!\n",qPrint(cd->name()));
return -1;
}
int m=maxInheritanceDepth;
for (const auto &bcdi : cd->baseClasses())
{
int mc=minClassDistance(bcdi.classDef,bcd,level+1);
if (mc<m) m=mc;
if (m<0) break;
}
return m;
}
Protection classInheritedProtectionLevel(const ClassDef *cd,const ClassDef *bcd,Protection prot,int level)
{
if (bcd->categoryOf()) // use class that is being extended in case of
// an Objective-C category
{
bcd=bcd->categoryOf();
}
if (cd==bcd)
{
goto exit;
}
if (level==256)
{
err("Internal inconsistency: found class %s seem to have a recursive "
"inheritance relation! Please send a bug report to doxygen@gmail.com\n",qPrint(cd->name()));
}
else if (prot!=Protection::Private)
{
for (const auto &bcdi : cd->baseClasses())
{
Protection baseProt = classInheritedProtectionLevel(bcdi.classDef,bcd,bcdi.prot,level+1);
if (baseProt==Protection::Private) prot=Protection::Private;
else if (baseProt==Protection::Protected) prot=Protection::Protected;
}
}
exit:
//printf("classInheritedProtectionLevel(%s,%s)=%d\n",qPrint(cd->name()),qPrint(bcd->name()),prot);
return prot;
}
| 178,690
|
C++
|
.cpp
| 5,037
| 29.070081
| 146
| 0.644406
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,417
|
main.cpp
|
doxygen_doxygen/src/main.cpp
|
/******************************************************************************
*
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include "doxygen.h"
/*! \file
* \brief main entry point for doxygen
*
* This file contains main()
*/
/*! Default main. The idea of separating this from the rest of doxygen,
* is to make it possible to write your own main, with a different
* generateOutput() function for instance.
*/
int main(int argc,char **argv)
{
initDoxygen();
readConfiguration(argc,argv);
checkConfiguration();
adjustConfiguration();
parseInput();
generateOutput();
return 0;
}
| 1,146
|
C++
|
.cpp
| 37
| 28.864865
| 79
| 0.694118
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
28,418
|
searchindex_js.cpp
|
doxygen_doxygen/src/searchindex_js.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2022 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.
*
*/
#include <utility>
#include <algorithm>
#include <cassert>
#include "searchindex_js.h"
#include "doxygen.h"
#include "groupdef.h"
#include "pagedef.h"
#include "namespacedef.h"
#include "classdef.h"
#include "classlist.h"
#include "membername.h"
#include "filename.h"
#include "language.h"
#include "textstream.h"
#include "util.h"
#include "version.h"
#include "message.h"
#include "resourcemgr.h"
#include "indexlist.h"
#include "portable.h"
#include "threadpool.h"
#include "moduledef.h"
#include "section.h"
//-------------------------------------------------------------------------------------------
void SearchTerm::makeTitle()
{
if (std::holds_alternative<const Definition *>(info))
{
const Definition *def = std::get<const Definition *>(info);
Definition::DefType type = def->definitionType();
title = type==Definition::TypeGroup ? filterTitle(toGroupDef(def)->groupTitle()) :
type==Definition::TypePage ? filterTitle(toPageDef(def)->title()) :
def->localName();
}
else if (std::holds_alternative<const SectionInfo *>(info))
{
title = std::get<const SectionInfo *>(info)->title();
}
else
{
assert(false);
}
}
QCString SearchTerm::termEncoded() const
{
TextStream t;
for (size_t i=0;i<word.length();i++)
{
if (isIdJS(word.at(i)))
{
t << word.at(i);
}
else // escape non-identifier characters
{
static const char *hex = "0123456789ABCDEF";
unsigned char uc = static_cast<unsigned char>(word.at(i));
t << '_';
t << hex[uc>>4];
t << hex[uc&0xF];
}
}
return convertUTF8ToLower(t.str());
}
//-------------------------------------------------------------------------------------------
//! helper function to simplify the given title string, and fill a list of start positions
//! for the start of each word in the simplified title string.
static void splitSearchTokens(QCString &title,IntVector &indices)
{
if (title.isEmpty()) return;
// simplify title to contain only words with single space as separator
size_t di=0;
bool lastIsSpace=true;
for (size_t si=0; si<title.length(); si++)
{
char c = title.at(si);
if (isId(c) || c==':') // add "word" character
{
title.at(di)=c;
di++;
lastIsSpace=false;
}
else if (!lastIsSpace) // add one separator as space
{
title.at(di)=' ';
di++;
lastIsSpace=true;
}
}
if (di>0 && title.at(di-1)==' ') di--; // strip trailing whitespace
title.resize(di);
// create a list of start positions within title for
// each unique word in order of appearance
int p=0,i=0;
while ((i=title.find(' ',p))!=-1)
{
std::string word = title.mid(p,i-p).str();
indices.push_back(p);
p = i+1;
}
if (p<static_cast<int>(title.length()))
{
std::string word = title.mid(p).str();
indices.push_back(p);
}
}
//-------------------------------------------------------------------------------------------
#define SEARCH_INDEX_ALL 0
#define SEARCH_INDEX_CLASSES 1
#define SEARCH_INDEX_INTERFACES 2
#define SEARCH_INDEX_STRUCTS 3
#define SEARCH_INDEX_EXCEPTIONS 4
#define SEARCH_INDEX_NAMESPACES 5
#define SEARCH_INDEX_FILES 6
#define SEARCH_INDEX_FUNCTIONS 7
#define SEARCH_INDEX_VARIABLES 8
#define SEARCH_INDEX_TYPEDEFS 9
#define SEARCH_INDEX_SEQUENCES 10
#define SEARCH_INDEX_DICTIONARIES 11
#define SEARCH_INDEX_ENUMS 12
#define SEARCH_INDEX_ENUMVALUES 13
#define SEARCH_INDEX_PROPERTIES 14
#define SEARCH_INDEX_EVENTS 15
#define SEARCH_INDEX_RELATED 16
#define SEARCH_INDEX_DEFINES 17
#define SEARCH_INDEX_GROUPS 18
#define SEARCH_INDEX_PAGES 19
#define SEARCH_INDEX_CONCEPTS 20
#define SEARCH_INDEX_MODULES 21
static std::array<SearchIndexInfo,NUM_SEARCH_INDICES> g_searchIndexInfo =
{ {
// index name getText symbolList
{ /* SEARCH_INDEX_ALL */ "all" , []() { return theTranslator->trAll(); }, {} },
{ /* SEARCH_INDEX_CLASSES */ "classes" , []() { return theTranslator->trClasses(); }, {} },
{ /* SEARCH_INDEX_INTERFACES */ "interfaces" , []() { return theTranslator->trSliceInterfaces(); }, {} },
{ /* SEARCH_INDEX_STRUCTS */ "structs" , []() { return theTranslator->trStructs(); }, {} },
{ /* SEARCH_INDEX_EXCEPTIONS */ "exceptions" , []() { return theTranslator->trExceptions(); }, {} },
{ /* SEARCH_INDEX_NAMESPACES */ "namespaces" , []() { return Config_getBool(OPTIMIZE_OUTPUT_SLICE) ?
theTranslator->trModules() :
theTranslator->trNamespace(TRUE,FALSE); }, {} },
{ /* SEARCH_INDEX_FILES */ "files" , []() { return theTranslator->trFile(TRUE,FALSE); }, {} },
{ /* SEARCH_INDEX_FUNCTIONS */ "functions" , []() { return Config_getBool(OPTIMIZE_OUTPUT_SLICE) ?
theTranslator->trOperations() :
theTranslator->trFunctions(); }, {} },
{ /* SEARCH_INDEX_VARIABLES */ "variables" , []() { return Config_getBool(OPTIMIZE_OUTPUT_SLICE) ?
theTranslator->trConstants() :
theTranslator->trVariables(); }, {} },
{ /* SEARCH_INDEX_TYPEDEFS */ "typedefs" , []() { return theTranslator->trTypedefs(); }, {} },
{ /* SEARCH_INDEX_SEQUENCES */ "sequences" , []() { return theTranslator->trSequences(); }, {} },
{ /* SEARCH_INDEX_DICTIONARIES */ "dictionaries", []() { return theTranslator->trDictionaries(); }, {} },
{ /* SEARCH_INDEX_ENUMS */ "enums" , []() { return theTranslator->trEnumerations(); }, {} },
{ /* SEARCH_INDEX_ENUMVALUES */ "enumvalues" , []() { return theTranslator->trEnumerationValues(); }, {} },
{ /* SEARCH_INDEX_PROPERTIES */ "properties" , []() { return theTranslator->trProperties(); }, {} },
{ /* SEARCH_INDEX_EVENTS */ "events" , []() { return theTranslator->trEvents(); }, {} },
{ /* SEARCH_INDEX_RELATED */ "related" , []() { return theTranslator->trFriends(); }, {} },
{ /* SEARCH_INDEX_DEFINES */ "defines" , []() { return theTranslator->trDefines(); }, {} },
{ /* SEARCH_INDEX_GROUPS */ "groups" , []() { return theTranslator->trGroup(TRUE,FALSE); }, {} },
{ /* SEARCH_INDEX_PAGES */ "pages" , []() { return theTranslator->trPage(TRUE,FALSE); }, {} },
{ /* SEARCH_INDEX_CONCEPTS */ "concepts" , []() { return theTranslator->trConcept(true,false); }, {} },
{ /* SEARCH_INDEX_MODULES */ "modules" , []() { return theTranslator->trModule(true,false); }, {} }
} };
static void addMemberToSearchIndex(const MemberDef *md)
{
bool hideFriendCompounds = Config_getBool(HIDE_FRIEND_COMPOUNDS);
bool isLinkable = md->isLinkable();
const ClassDef *cd=nullptr;
const NamespaceDef *nd=nullptr;
const FileDef *fd=nullptr;
const GroupDef *gd=nullptr;
if (isLinkable &&
(
((cd=md->getClassDef()) && cd->isLinkable() && cd->templateMaster()==nullptr) ||
((gd=md->getGroupDef()) && gd->isLinkable())
)
)
{
QCString n = md->name();
if (!n.isEmpty())
{
bool isFriendToHide = hideFriendCompounds &&
(QCString(md->typeString())=="friend class" ||
QCString(md->typeString())=="friend struct" ||
QCString(md->typeString())=="friend union");
if (!(md->isFriend() && isFriendToHide))
{
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(n,md));
}
if (md->isFunction() || md->isSlot() || md->isSignal())
{
g_searchIndexInfo[SEARCH_INDEX_FUNCTIONS].add(SearchTerm(n,md));
}
else if (md->isVariable())
{
g_searchIndexInfo[SEARCH_INDEX_VARIABLES].add(SearchTerm(n,md));
}
else if (md->isSequence())
{
g_searchIndexInfo[SEARCH_INDEX_SEQUENCES].add(SearchTerm(n,md));
}
else if (md->isDictionary())
{
g_searchIndexInfo[SEARCH_INDEX_DICTIONARIES].add(SearchTerm(n,md));
}
else if (md->isTypedef())
{
g_searchIndexInfo[SEARCH_INDEX_TYPEDEFS].add(SearchTerm(n,md));
}
else if (md->isEnumerate())
{
g_searchIndexInfo[SEARCH_INDEX_ENUMS].add(SearchTerm(n,md));
}
else if (md->isEnumValue())
{
g_searchIndexInfo[SEARCH_INDEX_ENUMVALUES].add(SearchTerm(n,md));
}
else if (md->isProperty())
{
g_searchIndexInfo[SEARCH_INDEX_PROPERTIES].add(SearchTerm(n,md));
}
else if (md->isEvent())
{
g_searchIndexInfo[SEARCH_INDEX_EVENTS].add(SearchTerm(n,md));
}
else if (md->isRelated() || md->isForeign() ||
(md->isFriend() && !isFriendToHide))
{
g_searchIndexInfo[SEARCH_INDEX_RELATED].add(SearchTerm(n,md));
}
}
}
else if (isLinkable &&
(((nd=md->getNamespaceDef()) && nd->isLinkable()) ||
((fd=md->getFileDef()) && fd->isLinkable())
)
)
{
QCString n = md->name();
if (!n.isEmpty())
{
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(n,md));
if (md->isFunction())
{
g_searchIndexInfo[SEARCH_INDEX_FUNCTIONS].add(SearchTerm(n,md));
}
else if (md->isVariable())
{
g_searchIndexInfo[SEARCH_INDEX_VARIABLES].add(SearchTerm(n,md));
}
else if (md->isSequence())
{
g_searchIndexInfo[SEARCH_INDEX_SEQUENCES].add(SearchTerm(n,md));
}
else if (md->isDictionary())
{
g_searchIndexInfo[SEARCH_INDEX_DICTIONARIES].add(SearchTerm(n,md));
}
else if (md->isTypedef())
{
g_searchIndexInfo[SEARCH_INDEX_TYPEDEFS].add(SearchTerm(n,md));
}
else if (md->isEnumerate())
{
g_searchIndexInfo[SEARCH_INDEX_ENUMS].add(SearchTerm(n,md));
}
else if (md->isEnumValue())
{
g_searchIndexInfo[SEARCH_INDEX_ENUMVALUES].add(SearchTerm(n,md));
}
else if (md->isDefine())
{
g_searchIndexInfo[SEARCH_INDEX_DEFINES].add(SearchTerm(n,md));
}
}
}
}
//---------------------------------------------------------------------------------------------
void createJavaScriptSearchIndex()
{
// index classes
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkable())
{
QCString n = cd->localName();
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(n,cd.get()));
if (Config_getBool(OPTIMIZE_OUTPUT_SLICE))
{
if (cd->compoundType()==ClassDef::Interface)
{
g_searchIndexInfo[SEARCH_INDEX_INTERFACES].add(SearchTerm(n,cd.get()));
}
else if (cd->compoundType()==ClassDef::Struct)
{
g_searchIndexInfo[SEARCH_INDEX_STRUCTS].add(SearchTerm(n,cd.get()));
}
else if (cd->compoundType()==ClassDef::Exception)
{
g_searchIndexInfo[SEARCH_INDEX_EXCEPTIONS].add(SearchTerm(n,cd.get()));
}
else // cd->compoundType()==ClassDef::Class
{
g_searchIndexInfo[SEARCH_INDEX_CLASSES].add(SearchTerm(n,cd.get()));
}
}
else // non slice optimization: group all types under classes
{
g_searchIndexInfo[SEARCH_INDEX_CLASSES].add(SearchTerm(n,cd.get()));
}
}
}
// index namespaces
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkable())
{
QCString n = nd->name();
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(n,nd.get()));
g_searchIndexInfo[SEARCH_INDEX_NAMESPACES].add(SearchTerm(n,nd.get()));
}
}
// index concepts
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkable())
{
QCString n = cd->name();
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(n,cd.get()));
g_searchIndexInfo[SEARCH_INDEX_CONCEPTS].add(SearchTerm(n,cd.get()));
}
}
// index modules
for (const auto &mod : ModuleManager::instance().modules())
{
if (mod->isLinkable() && mod->isPrimaryInterface())
{
QCString n = mod->name();
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(n,mod.get()));
g_searchIndexInfo[SEARCH_INDEX_MODULES].add(SearchTerm(n,mod.get()));
}
}
// index files
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
QCString n = fd->name();
if (fd->isLinkable())
{
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(n,fd.get()));
g_searchIndexInfo[SEARCH_INDEX_FILES].add(SearchTerm(n,fd.get()));
}
}
}
// index class members
{
// for each member name
for (const auto &mn : *Doxygen::memberNameLinkedMap)
{
// for each member definition
for (const auto &md : *mn)
{
addMemberToSearchIndex(md.get());
}
}
}
// index file/namespace members
{
// for each member name
for (const auto &mn : *Doxygen::functionNameLinkedMap)
{
// for each member definition
for (const auto &md : *mn)
{
addMemberToSearchIndex(md.get());
}
}
}
// index groups
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (gd->isLinkable())
{
QCString title(filterTitle(gd->groupTitle()).str());
IntVector tokenIndices;
splitSearchTokens(title,tokenIndices);
for (int index : tokenIndices)
{
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(title.mid(index),gd.get()));
g_searchIndexInfo[SEARCH_INDEX_GROUPS].add(SearchTerm(title.mid(index),gd.get()));
}
}
}
// index pages
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (pd->isLinkable())
{
QCString title(filterTitle(pd->title()).str());
IntVector tokenIndices;
splitSearchTokens(title,tokenIndices);
for (int index : tokenIndices)
{
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(title.mid(index),pd.get()));
g_searchIndexInfo[SEARCH_INDEX_PAGES].add(SearchTerm(title.mid(index),pd.get()));
}
}
}
// main page
if (Doxygen::mainPage)
{
QCString title(filterTitle(Doxygen::mainPage->title()).str());
IntVector tokenIndices;
splitSearchTokens(title,tokenIndices);
for (int index : tokenIndices)
{
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(title.mid(index),Doxygen::mainPage.get()));
g_searchIndexInfo[SEARCH_INDEX_PAGES].add(SearchTerm(title.mid(index),Doxygen::mainPage.get()));
}
}
// sections
const auto &sm = SectionManager::instance();
for (const auto §ionInfo : sm)
{
if (sectionInfo->level()>0) // level 0 is for page titles
{
QCString title = filterTitle(sectionInfo->title());
IntVector tokenIndices;
splitSearchTokens(title,tokenIndices);
for (int index : tokenIndices)
{
g_searchIndexInfo[SEARCH_INDEX_ALL].add(SearchTerm(title.mid(index),sectionInfo.get()));
}
}
}
// sort all lists
for (auto &sii : g_searchIndexInfo) // for each index
{
for (auto &[name,symList] : sii.symbolMap) // for each symbol in the index
{
// sort the symbols (first on search term, and then on full name)
//
// `std::stable_sort` is used here due to reproducibility issues
// on key collisions
// https://github.com/doxygen/doxygen/issues/10445
std::stable_sort(symList.begin(),
symList.end(),
[](const auto &t1,const auto &t2)
{
int eq = qstricmp_sort(t1.word,t2.word); // search term first
return eq==0 ? qstricmp_sort(t1.title,t2.title)<0 : eq<0; // then full title
});
}
}
}
static void writeJavascriptSearchData(const QCString &searchDirName)
{
std::ofstream t = Portable::openOutputStream(searchDirName+"/searchdata.js");
if (t.is_open())
{
t << "var indexSectionsWithContent =\n";
t << "{\n";
int j=0;
for (const auto &sii : g_searchIndexInfo)
{
if (!sii.symbolMap.empty())
{
if (j>0) t << ",\n";
t << " " << j << ": \"";
std::string previous_letter; // start with value that does not exist in the map
for (const auto &[letter,list] : sii.symbolMap)
{
if (letter != previous_letter)
{
if ( letter == "\"" ) t << "\\"; // add escape for backslash
t << letter;
previous_letter = letter;
}
}
t << "\"";
j++;
}
}
if (j>0) t << "\n";
t << "};\n\n";
t << "var indexSectionNames =\n";
t << "{\n";
j=0;
for (const auto &sii : g_searchIndexInfo)
{
if (!sii.symbolMap.empty())
{
if (j>0) t << ",\n";
t << " " << j << ": \"" << sii.name << "\"";
j++;
}
}
if (j>0) t << "\n";
t << "};\n\n";
t << "var indexSectionLabels =\n";
t << "{\n";
j=0;
for (const auto &sii : g_searchIndexInfo)
{
if (!sii.symbolMap.empty())
{
if (j>0) t << ",\n";
t << " " << j << ": \"" << convertToXML(sii.getText()) << "\"";
j++;
}
}
if (j>0) t << "\n";
t << "};\n\n";
}
}
static void writeJavasScriptSearchDataPage(const QCString &baseName,const QCString &dataFileName,const SearchIndexList &list)
{
auto isDef = [](const SearchTerm::LinkInfo &info)
{
return std::holds_alternative<const Definition *>(info);
};
auto getDef = [&isDef](const SearchTerm::LinkInfo &info)
{
return isDef(info) ? std::get<const Definition *>(info) : nullptr;
};
auto isSection = [](const SearchTerm::LinkInfo &info)
{
return std::holds_alternative<const SectionInfo *>(info);
};
auto getSection = [&isSection](const SearchTerm::LinkInfo &info)
{
return isSection(info) ? std::get<const SectionInfo *>(info) : nullptr;
};
int cnt = 0;
std::ofstream ti = Portable::openOutputStream(dataFileName);
if (!ti.is_open())
{
err("Failed to open file '%s' for writing...\n",qPrint(dataFileName));
return;
}
ti << "var searchData=\n";
// format
// searchData[] = array of items
// searchData[x][0] = id
// searchData[x][1] = [ name + child1 + child2 + .. ]
// searchData[x][1][0] = name as shown
// searchData[x][1][y+1] = info for child y
// searchData[x][1][y+1][0] = url
// searchData[x][1][y+1][1] = 1 => target="_parent"
// searchData[x][1][y+1][1] = 0 => target="_blank"
// searchData[x][1][y+1][2] = scope
ti << "[\n";
bool firstEntry=TRUE;
int childCount=0;
QCString lastWord;
const Definition *prevScope = nullptr;
for (auto it = list.begin(); it!=list.end();)
{
const SearchTerm &term = *it;
const SearchTerm::LinkInfo info = term.info;
const Definition *d = getDef(info);
const SectionInfo *si = getSection(info);
assert(d || si); // either d or si should be valid
QCString word = term.word;
QCString id = term.termEncoded();
++it;
const Definition *scope = d ? d->getOuterScope() : nullptr;
const SearchTerm::LinkInfo next = it!=list.end() ? it->info : SearchTerm::LinkInfo();
const Definition *nextScope = isDef(next) ? getDef(next)->getOuterScope() : nullptr;
const MemberDef *md = toMemberDef(d);
QCString anchor = d ? d->anchor() : si ? si->label() : QCString();
if (word!=lastWord) // this item has a different search word
{
if (!firstEntry)
{
ti << "]]]";
ti << ",\n";
}
firstEntry=FALSE;
ti << " ['" << id << "_" << cnt++ << "',['";
if (next==SearchTerm::LinkInfo() || it->word!=word) // unique result, show title
{
ti << convertToXML(term.title);
}
else // multiple results, show matching word only, expanded list will show title
{
ti << convertToXML(term.word);
}
ti << "',[";
childCount=0;
prevScope=nullptr;
}
if (childCount>0)
{
ti << "],[";
}
QCString fn = d ? d->getOutputFileBase() : si ? si->fileName() : QCString();
QCString ref = d ? d->getReference() : si ? si->ref() : QCString();
addHtmlExtensionIfMissing(fn);
ti << "'" << externalRef("../",ref,TRUE) << fn;
if (!anchor.isEmpty())
{
ti << "#" << anchor;
}
ti << "',";
bool extLinksInWindow = Config_getBool(EXT_LINKS_IN_WINDOW);
if (!extLinksInWindow || ref.isEmpty())
{
ti << "1,";
}
else
{
ti << "0,";
}
if (lastWord!=word && (next==SearchTerm::LinkInfo() || it->word!=word)) // unique search result
{
if (d && d->getOuterScope()!=Doxygen::globalScope)
{
ti << "'" << convertToXML(d->getOuterScope()->name()) << "'";
}
else if (md)
{
const FileDef *fd = md->getBodyDef();
if (fd==nullptr) fd = md->getFileDef();
if (fd)
{
ti << "'" << convertToXML(fd->localName()) << "'";
}
}
else
{
ti << "''";
}
}
else // multiple entries with the same name
{
bool found=FALSE;
bool overloadedFunction = ((prevScope!=nullptr && scope==prevScope) || (scope && scope==nextScope)) &&
md && md->isCallable();
QCString prefix;
if (md) prefix=convertToXML(md->localName());
if (overloadedFunction) // overloaded member function
{
prefix+=convertToXML(md->argsString());
// show argument list to disambiguate overloaded functions
}
else if (md && md->isCallable()) // unique member function
{
prefix+="()"; // only to show it is a callable symbol
}
QCString name;
if (d)
{
switch (d->definitionType())
{
case Definition::TypeClass: name = convertToXML((toClassDef(d))->displayName()); found=true; break;
case Definition::TypeNamespace: name = convertToXML((toNamespaceDef(d))->displayName()); found=true; break;
case Definition::TypeModule: name = convertToXML(d->name()+" "+theTranslator->trModule(false,true)); found=true; break;
case Definition::TypePage: name = convertToXML(filterTitle(toPageDef(d)->title())); found=true; break;
case Definition::TypeGroup: name = convertToXML(filterTitle(toGroupDef(d)->groupTitle())); found=true; break;
default:
if (scope==nullptr || scope==Doxygen::globalScope) // in global scope
{
if (md)
{
const FileDef *fd = md->getBodyDef();
if (fd==nullptr) fd = md->resolveAlias()->getFileDef();
if (fd)
{
if (!prefix.isEmpty()) prefix+=": ";
name = prefix + convertToXML(fd->localName());
found = true;
}
}
}
else if (md && (md->resolveAlias()->getClassDef() || md->resolveAlias()->getNamespaceDef()))
// member in class or namespace scope
{
SrcLangExt lang = md->getLanguage();
name = convertToXML(d->getOuterScope()->qualifiedName()) + getLanguageSpecificSeparator(lang) + prefix;
found = true;
}
else if (scope) // some thing else? -> show scope
{
name = prefix + convertToXML(scope->name());
found = true;
}
break;
}
}
else if (si)
{
name = convertToXML(filterTitle(si->title()));
found = true;
}
if (!found) // fallback
{
name = prefix + "("+theTranslator->trGlobalNamespace()+")";
}
ti << "'" << name << "'";
prevScope = scope;
childCount++;
}
lastWord = word;
}
if (!firstEntry)
{
ti << "]]]\n";
}
ti << "];\n";
Doxygen::indexList->addStyleSheetFile(("search/"+baseName+".js").data());
}
void writeJavaScriptSearchIndex()
{
// write index files
QCString searchDirName = Config_getString(HTML_OUTPUT)+"/search";
std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
if (numThreads>1) // multi threaded version
{
ThreadPool threadPool(numThreads);
std::vector< std::future<int> > results;
for (auto &sii : g_searchIndexInfo)
{
int p=0;
for (const auto &[letter,symList] : sii.symbolMap)
{
QCString baseName;
baseName.sprintf("%s_%x",sii.name.data(),p);
QCString dataFileName = searchDirName + "/"+baseName+".js";
auto &list = symList;
auto processFile = [p,baseName,dataFileName,&list]()
{
writeJavasScriptSearchDataPage(baseName,dataFileName,list);
return p;
};
results.emplace_back(threadPool.queue(processFile));
p++;
}
}
// wait for the results
for (auto &f : results) f.get();
}
else // single threaded version
{
for (auto &sii : g_searchIndexInfo)
{
int p=0;
for (const auto &[letter,symList] : sii.symbolMap)
{
QCString baseName;
baseName.sprintf("%s_%x",sii.name.data(),p);
QCString dataFileName = searchDirName + "/"+baseName+".js";
writeJavasScriptSearchDataPage(baseName,dataFileName,symList);
p++;
}
}
}
writeJavascriptSearchData(searchDirName);
auto &mgr = ResourceMgr::instance();
{
std::ofstream fn = Portable::openOutputStream(searchDirName+"/search.js");
if (fn.is_open())
{
TextStream t(&fn);
t << substitute(mgr.getAsString("search.js"),"$PROJECTID",getProjectId());
}
}
Doxygen::indexList->addStyleSheetFile("search/searchdata.js");
Doxygen::indexList->addStyleSheetFile("search/search.js");
}
//--------------------------------------------------------------------------------------
void SearchIndexInfo::add(const SearchTerm &term)
{
std::string letter = convertUTF8ToLower(getUTF8CharAt(term.word.str(),0));
auto &list = symbolMap[letter]; // creates a new entry if not found
list.push_back(term);
}
const std::array<SearchIndexInfo,NUM_SEARCH_INDICES> &getSearchIndices()
{
return g_searchIndexInfo;
}
| 27,605
|
C++
|
.cpp
| 793
| 28.528373
| 132
| 0.567185
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,419
|
rtfstyle.cpp
|
doxygen_doxygen/src/rtfstyle.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2021 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.
*
*/
#include <string>
#include <fstream>
#include "rtfstyle.h"
#include "message.h"
#include "regex.h"
QCString rtf_title;
QCString rtf_subject;
QCString rtf_comments;
QCString rtf_company;
QCString rtf_logoFilename;
QCString rtf_author;
QCString rtf_manager;
QCString rtf_documentType;
QCString rtf_documentId;
QCString rtf_keywords;
static std::map<std::string,QCString &> g_styleMap =
{
{ "Title", rtf_title },
{ "Subject", rtf_subject },
{ "Comments", rtf_comments },
{ "Company", rtf_company },
{ "LogoFilename", rtf_logoFilename },
{ "Author", rtf_author },
{ "Manager", rtf_manager },
{ "DocumentType", rtf_documentType },
{ "DocumentId", rtf_documentId },
{ "Keywords", rtf_keywords }
};
char rtf_Style_Reset[] = "\\pard\\plain ";
#define RTF_LatexToc(lvl,nest,nxt,pos,twps) \
\
{ "LatexTOC"#lvl, \
"\\s"#nest"\\li"#pos"\\sa"#twps"\\sb"#twps"\\widctlpar\\tqr\\tldot\\tx8640\\adjustright \\fs20\\cgrid ",\
"\\sbasedon0 \\snext"#nxt" LatexTOC "#lvl \
}
#define RTF_ListBullet(lvl,nest,nxt,pos,lvl2) \
{ "ListBullet"#lvl, \
"\\s"#nest"\\fi-360\\li"#pos"\\widctlpar\\jclisttab\\tx"#pos"{\\*\\pn \\pnlvlbody\\ilvl0\\ls"#lvl2"\\pnrnot0\\pndec }\\ls1\\adjustright \\fs20\\cgrid ", \
"\\sbasedon0 \\snext"#nxt" \\sautoupd List Bullet "#lvl \
}
#define RTF_ListEnum(lvl,nest,nxt,pos) \
{ "ListEnum"#lvl, \
"\\s"#nest"\\fi-360\\li"#pos"\\widctlpar\\fs20\\cgrid ", \
"\\sbasedon0 \\snext"#nxt" \\sautoupd List Enum "#lvl \
}
#define RTF_CodeExample(lvl,nest,nxt,pos) \
{ "CodeExample"#lvl, \
"\\s"#nest"\\li"#pos"\\widctlpar\\adjustright \\shading1000\\cbpat8 \\f2\\fs16\\cgrid ", \
"\\sbasedon0 \\snext"#nxt" Code Example "#lvl \
}
#define RTF_ListContinue(lvl,nest,nxt,pos) \
{ "ListContinue"#lvl, \
"\\s"#nest"\\li"#pos"\\sa60\\sb30\\qj\\widctlpar\\qj\\adjustright \\fs20\\cgrid ", \
"\\sbasedon0 \\snext"#nxt" List Continue "#lvl \
}
#define RTF_DescContinue(lvl,nest,nxt,pos) \
{ "DescContinue"#lvl, \
"\\s"#nest"\\li"#pos"\\widctlpar\\ql\\adjustright \\fs20\\cgrid ", \
"\\sbasedon0 \\snext"#nxt" DescContinue "#lvl \
}
Rtf_Style_Default rtf_Style_Default[] =
{
{ "Heading1",
"\\s1\\sb240\\sa60\\keepn\\widctlpar\\adjustright \\b\\f1\\fs36\\kerning36\\cgrid ",
"\\sbasedon0 \\snext0 heading 1"
},
{ "Heading2",
"\\s2\\sb240\\sa60\\keepn\\widctlpar\\adjustright \\b\\f1\\fs28\\kerning28\\cgrid ",
"\\sbasedon0 \\snext0 heading 2"
},
{ "Heading3",
"\\s3\\sb240\\sa60\\keepn\\widctlpar\\adjustright \\b\\f1\\cgrid ",
"\\sbasedon0 \\snext0 heading 3"
},
{ "Heading4",
"\\s4\\sb240\\sa60\\keepn\\widctlpar\\adjustright \\b\\f1\\fs20\\cgrid ",
"\\sbasedon0 \\snext0 heading 4;}{\\*\\cs10 \\additive Default Paragraph Font"
},
{ "Heading5",
"\\s5\\sb90\\sa30\\keepn\\widctlpar\\adjustright \\b\\f1\\fs16\\cgrid ",
"\\sbasedon0 \\snext0 heading 5;}{\\*\\cs10 \\additive Default Paragraph Font"
},
{ "Heading6",
"\\s6\\sb90\\sa30\\keepn\\widctlpar\\adjustright \\b\\f1\\fs12\\cgrid ",
"\\sbasedon0 \\snext0 heading 6;}{\\*\\cs10 \\additive Default Paragraph Font"
},
{ "Title",
"\\s15\\qc\\sb240\\sa60\\widctlpar\\outlinelevel0\\adjustright \\b\\f1\\fs32\\kerning28\\cgrid ",
"\\sbasedon0 \\snext15 Title"
},
{ "SubTitle",
"\\s16\\qc\\sa60\\widctlpar\\outlinelevel1\\adjustright \\f1\\cgrid ",
"\\sbasedon0 \\snext16 Subtitle"
},
{ "BodyText",
"\\s17\\sa60\\sb30\\widctlpar\\qj \\fs22\\cgrid ",
"\\sbasedon0 \\snext17 BodyText"
},
{ "DenseText",
"\\s18\\widctlpar\\fs22\\cgrid ",
"\\sbasedon0 \\snext18 DenseText"
},
{ "Header",
"\\s28\\widctlpar\\tqc\\tx4320\\tqr\\tx8640\\adjustright \\fs20\\cgrid ",
"\\sbasedon0 \\snext28 header"
},
{ "Footer",
"\\s29\\widctlpar\\tqc\\tx4320\\tqr\\tx8640\\qr\\adjustright \\fs20\\cgrid ",
"\\sbasedon0 \\snext29 footer"
},
{ "GroupHeader",
"\\s30\\li360\\sa60\\sb120\\keepn\\widctlpar\\adjustright \\b\\f1\\fs20\\cgrid ",
"\\sbasedon0 \\snext30 GroupHeader"
},
RTF_CodeExample( 0, 40, 41, 0),
RTF_CodeExample( 1, 41, 42, 360),
RTF_CodeExample( 2, 42, 43, 720),
RTF_CodeExample( 3, 43, 44,1080),
RTF_CodeExample( 4, 44, 45,1440),
RTF_CodeExample( 5, 45, 46,1800),
RTF_CodeExample( 6, 46, 47,2160),
RTF_CodeExample( 7, 47, 48,2520),
RTF_CodeExample( 8, 48, 49,2880),
RTF_CodeExample( 9, 49, 50,3240),
RTF_CodeExample(10, 50, 51,3600),
RTF_CodeExample(11, 51, 52,3960),
RTF_CodeExample(12, 52, 53,4320),
RTF_CodeExample(13, 53, 53,4680),
RTF_ListContinue( 0, 60, 61, 0),
RTF_ListContinue( 1, 61, 62, 360),
RTF_ListContinue( 2, 62, 63, 720),
RTF_ListContinue( 3, 63, 64,1080),
RTF_ListContinue( 4, 64, 65,1440),
RTF_ListContinue( 5, 65, 66,1800),
RTF_ListContinue( 6, 66, 67,2160),
RTF_ListContinue( 7, 67, 68,2520),
RTF_ListContinue( 8, 68, 69,2880),
RTF_ListContinue( 9, 69, 70,3240),
RTF_ListContinue(10, 70, 71,3600),
RTF_ListContinue(11, 71, 72,3960),
RTF_ListContinue(12, 72, 73,4320),
RTF_ListContinue(13, 73, 73,4680),
RTF_DescContinue( 0, 80, 81, 0),
RTF_DescContinue( 1, 81, 82, 360),
RTF_DescContinue( 2, 82, 83, 720),
RTF_DescContinue( 3, 83, 84,1080),
RTF_DescContinue( 4, 84, 85,1440),
RTF_DescContinue( 5, 85, 86,1800),
RTF_DescContinue( 6, 86, 87,2160),
RTF_DescContinue( 7, 87, 88,2520),
RTF_DescContinue( 8, 88, 89,2880),
RTF_DescContinue( 9, 89, 90,3240),
RTF_DescContinue(10, 90, 91,3600),
RTF_DescContinue(11, 91, 92,3960),
RTF_DescContinue(12, 92, 93,4320),
RTF_DescContinue(13, 93, 93,4680),
RTF_LatexToc( 0,100,101, 0,30),
RTF_LatexToc( 1,101,102, 360,27),
RTF_LatexToc( 2,102,103, 720,24),
RTF_LatexToc( 3,103,104,1080,21),
RTF_LatexToc( 4,104,105,1440,18),
RTF_LatexToc( 5,105,106,1800,15),
RTF_LatexToc( 6,106,107,2160,12),
RTF_LatexToc( 7,107,108,2520, 9),
RTF_LatexToc( 8,108,109,2880, 6),
RTF_LatexToc( 9,109,110,3240, 3),
RTF_LatexToc(10,110,111,3600, 3),
RTF_LatexToc(11,111,112,3960, 3),
RTF_LatexToc(12,112,113,4320, 3),
RTF_LatexToc(13,113,113,4680, 3),
RTF_ListBullet( 0,120,121, 360, 1),
RTF_ListBullet( 1,121,122, 720, 2),
RTF_ListBullet( 2,122,123,1080, 3),
RTF_ListBullet( 3,123,124,1440, 4),
RTF_ListBullet( 4,124,125,1800, 5),
RTF_ListBullet( 5,125,126,2160, 6),
RTF_ListBullet( 6,126,127,2520, 7),
RTF_ListBullet( 7,127,128,2880, 8),
RTF_ListBullet( 8,128,129,3240, 9),
RTF_ListBullet( 9,129,130,3600,10),
RTF_ListBullet(10,130,131,3960,11),
RTF_ListBullet(11,131,132,4320,12),
RTF_ListBullet(12,132,133,4680,13),
RTF_ListBullet(13,133,133,5040,14),
RTF_ListEnum( 0,140,141, 360),
RTF_ListEnum( 1,141,142, 720),
RTF_ListEnum( 2,142,143,1080),
RTF_ListEnum( 3,143,144,1440),
RTF_ListEnum( 4,144,145,1800),
RTF_ListEnum( 5,145,146,2160),
RTF_ListEnum( 6,146,147,2520),
RTF_ListEnum( 7,147,148,2880),
RTF_ListEnum( 8,148,149,3240),
RTF_ListEnum( 9,149,150,3600),
RTF_ListEnum(10,150,151,3960),
RTF_ListEnum(11,151,152,4320),
RTF_ListEnum(12,152,153,4680),
RTF_ListEnum(13,153,153,5040),
{ nullptr,
nullptr,
nullptr
}
};
#define RTF_ListElement(id,lvl,pos,chr) \
{ id, lvl, \
"\\listlevel\\levelnfc23\\leveljc0\\levelstartat1\\levelfollow0{\\leveltext \\'01\\u"#chr" ?;}{\\levelnumbers;}\\f8\\dbch\\af3\\fi-360\\li"#pos, \
"{\\*\\hyphen2\\hyphlead2\\hyphtrail2\\hyphmax0}\\nowidctlpar\\cf0\\hich\\af0\\langfe2052\\dbch\\af0\\afs24\\lang1081\\loch\\f0\\fs24\\lang1033{\\listtext\\pard\\plain \\hich\\af3\\dbch\\af3\\loch\\f8 \\'01\\u"#chr"\\tab}\\ilvl"#lvl"\\ls"#id" \\li0\\ri0\\lin0\\rin0\\fi-360\\tx"#pos"\\li"#pos"\\ri0\\lin"#pos"\\rin0\\fi-360\\kerning1\\hich\\af4\\dbch\\af5\\rtlch \\ltrch\\loch\\fs20" \
}
Rtf_Table_Default rtf_Table_Default[] =
{
RTF_ListElement( 1,0, 360, 8226),
RTF_ListElement( 1,1, 720, 9702),
RTF_ListElement( 1,2,1080, 9642),
RTF_ListElement( 1,3,1440, 8226),
RTF_ListElement( 1,4,1800, 9702),
RTF_ListElement( 1,5,2160, 9642),
RTF_ListElement( 1,6,2520, 8662),
RTF_ListElement( 1,7,2880, 9702),
RTF_ListElement( 1,8,3600, 9642),
RTF_ListElement( 2,0, 360, 9744),
RTF_ListElement( 2,1, 720, 9744),
RTF_ListElement( 2,2,1080, 9744),
RTF_ListElement( 2,3,1440, 9744),
RTF_ListElement( 2,4,1800, 9744),
RTF_ListElement( 2,5,2160, 9744),
RTF_ListElement( 2,6,2520, 9744),
RTF_ListElement( 2,7,2880, 9744),
RTF_ListElement( 2,8,3600, 9744),
RTF_ListElement( 3,0, 360, 9746),
RTF_ListElement( 3,1, 720, 9746),
RTF_ListElement( 3,2,1080, 9746),
RTF_ListElement( 3,3,1440, 9746),
RTF_ListElement( 3,4,1800, 9746),
RTF_ListElement( 3,5,2160, 9746),
RTF_ListElement( 3,6,2520, 9746),
RTF_ListElement( 3,7,2880, 9746),
RTF_ListElement( 3,8,3600, 9746),
{ 0,
0,
nullptr,
nullptr
}
};
static const reg::Ex s_clause(R"(\\s(\d+)\s*)"); // match, e.g. '\s30' and capture '30'
StyleData::StyleData(const std::string &reference, const std::string &definition)
{
reg::Match match;
if (reg::search(reference,match,s_clause))
{
m_index = static_cast<int>(std::stoul(match[1].str()));
}
else // error
{
m_index = 0;
}
m_reference = reference;
m_definition = definition;
}
bool StyleData::setStyle(const std::string &command, const std::string &styleName)
{
reg::Match match;
if (!reg::search(command,match,s_clause))
{
err("Style sheet '%s' contains no '\\s' clause.\n{%s}\n", styleName.c_str(), command.c_str());
return false;
}
m_index = static_cast<int>(std::stoul(match[1].str()));
size_t index = command.find("\\sbasedon");
if (index!=std::string::npos)
{
m_reference = command.substr(0,index);
m_definition = command.substr(index);
}
return true;
}
void loadStylesheet(const QCString &name, StyleDataMap& map)
{
std::ifstream file(name.str());
if (!file.is_open())
{
err("Can't open RTF style sheet file %s. Using defaults.\n",qPrint(name));
return;
}
msg("Loading RTF style sheet %s...\n",qPrint(name));
uint32_t lineNr=1;
for (std::string line ; getline(file,line) ; ) // for each line
{
if (line.empty() || line[0]=='#') continue; // skip blanks & comments
static const reg::Ex assignment_splitter(R"(\s*=\s*)");
reg::Match match;
if (reg::search(line,match,assignment_splitter))
{
std::string key = match.prefix().str();
std::string value = match.suffix().str();
auto it = map.find(key);
if (it!=map.end())
{
StyleData& styleData = it->second;
styleData.setStyle(value,key);
}
else
{
warn(name,lineNr,"Unknown style sheet name %s ignored.",key.data());
}
}
else
{
warn(name,lineNr,"Assignment of style sheet name expected line='%s'!",line.c_str());
}
lineNr++;
}
}
StyleDataMap rtf_Style;
void loadExtensions(const QCString &name)
{
std::ifstream file(name.str());
if (!file.is_open())
{
err("Can't open RTF extensions file %s. Using defaults.\n",qPrint(name));
return;
}
msg("Loading RTF extensions %s...\n",qPrint(name));
uint32_t lineNr=1;
for (std::string line ; getline(file,line) ; ) // for each line
{
if (line.empty() || line[0]=='#') continue; // skip blanks & comments
static const reg::Ex assignment_splitter(R"(\s*=\s*)");
reg::Match match;
if (reg::search(line,match,assignment_splitter))
{
std::string key = match.prefix().str();
std::string value = match.suffix().str();
auto it = g_styleMap.find(key);
if (it!=g_styleMap.end())
{
it->second = value;
}
else
{
warn(name,lineNr,"Ignoring unknown extension key '%s'...",key.c_str());
}
}
else
{
warn(name,lineNr,"Assignment of style sheet name expected!");
}
lineNr++;
}
}
| 13,540
|
C++
|
.cpp
| 363
| 33.479339
| 389
| 0.593241
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,420
|
perlmodgen.cpp
|
doxygen_doxygen/src/perlmodgen.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2022 by Dimitri van Heesch.
* Authors: Dimitri van Heesch, Miguel Lobo.
*
* 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.
*
*/
#include <stdlib.h>
#include <stack>
#include "perlmodgen.h"
#include "docparser.h"
#include "docnode.h"
#include "message.h"
#include "doxygen.h"
#include "pagedef.h"
#include "memberlist.h"
#include "arguments.h"
#include "config.h"
#include "groupdef.h"
#include "classdef.h"
#include "classlist.h"
#include "filename.h"
#include "membername.h"
#include "namespacedef.h"
#include "membergroup.h"
#include "section.h"
#include "util.h"
#include "htmlentity.h"
#include "emoji.h"
#include "dir.h"
#include "portable.h"
#include "moduledef.h"
#include "construct.h"
#define PERLOUTPUT_MAX_INDENTATION 40
class PerlModOutputStream
{
public:
std::ostream *m_t = nullptr;
PerlModOutputStream(std::ostream &t) : m_t(&t) { }
void add(char c);
void add(const QCString &s);
void add(int n);
void add(unsigned int n);
};
void PerlModOutputStream::add(char c)
{
*m_t << c;
}
void PerlModOutputStream::add(const QCString &s)
{
*m_t << s;
}
void PerlModOutputStream::add(int n)
{
*m_t << n;
}
void PerlModOutputStream::add(unsigned int n)
{
*m_t << n;
}
class PerlModOutput
{
public:
bool m_pretty;
inline PerlModOutput(bool pretty)
: m_pretty(pretty), m_stream(nullptr), m_indentation(false), m_blockstart(true)
{
m_spaces[0] = 0;
}
virtual ~PerlModOutput() { reset(); }
NON_COPYABLE(PerlModOutput)
void reset() { m_stream=nullptr; }
inline void setPerlModOutputStream(PerlModOutputStream *os) { m_stream = os; }
//inline PerlModOutput &openSave() { iopenSave(); return *this; }
//inline PerlModOutput &closeSave(QCString &s) { icloseSave(s); return *this; }
inline PerlModOutput &continueBlock()
{
if (m_blockstart)
m_blockstart = false;
else
m_stream->add(',');
indent();
return *this;
}
inline PerlModOutput &add(char c) { m_stream->add(c); return *this; }
inline PerlModOutput &add(const QCString &s) { m_stream->add(s); return *this; }
inline PerlModOutput &add(QCString &s) { m_stream->add(s); return *this; }
inline PerlModOutput &add(int n) { m_stream->add(n); return *this; }
inline PerlModOutput &add(unsigned int n) { m_stream->add(n); return *this; }
PerlModOutput &addQuoted(const QCString &s) { iaddQuoted(s); return *this; }
inline PerlModOutput &indent()
{
if (m_pretty) {
m_stream->add('\n');
m_stream->add(m_spaces);
}
return *this;
}
inline PerlModOutput &open(char c, const QCString &s = QCString()) { iopen(c, s); return *this; }
inline PerlModOutput &close(char c = 0) { iclose(c); return *this; }
inline PerlModOutput &addField(const QCString &s) { iaddField(s); return *this; }
inline PerlModOutput &addFieldQuotedChar(const QCString &field, char content)
{
iaddFieldQuotedChar(field, content); return *this;
}
inline PerlModOutput &addFieldQuotedString(const QCString &field, const QCString &content)
{
iaddFieldQuotedString(field, content); return *this;
}
inline PerlModOutput &addFieldBoolean(const QCString &field, bool content)
{
return addFieldQuotedString(field, content ? "yes" : "no");
}
inline PerlModOutput &openList(const QCString &s = QCString()) { open('[', s); return *this; }
inline PerlModOutput &closeList() { close(']'); return *this; }
inline PerlModOutput &openHash(const QCString &s = QCString() ) { open('{', s); return *this; }
inline PerlModOutput &closeHash() { close('}'); return *this; }
protected:
//void iopenSave();
//void icloseSave(QCString &);
void incIndent();
void decIndent();
void iaddQuoted(const QCString &);
void iaddFieldQuotedChar(const QCString &, char);
void iaddFieldQuotedString(const QCString &, const QCString &);
void iaddField(const QCString &);
void iopen(char, const QCString &);
void iclose(char);
private:
PerlModOutputStream *m_stream;
int m_indentation;
bool m_blockstart;
//std::stack<PerlModOutputStream*> m_saved;
char m_spaces[PERLOUTPUT_MAX_INDENTATION * 2 + 2];
};
//void PerlModOutput::iopenSave()
//{
// m_saved.push(m_stream);
// m_stream = new PerlModOutputStream();
//}
//void PerlModOutput::icloseSave(QCString &s)
//{
// s = m_stream->m_s;
// delete m_stream;
// m_stream = m_saved.top();
// m_saved.pop();
//}
void PerlModOutput::incIndent()
{
if (m_indentation < PERLOUTPUT_MAX_INDENTATION)
{
char *s = &m_spaces[m_indentation * 2];
*s++ = ' '; *s++ = ' '; *s = 0;
}
m_indentation++;
}
void PerlModOutput::decIndent()
{
m_indentation--;
if (m_indentation < PERLOUTPUT_MAX_INDENTATION)
m_spaces[m_indentation * 2] = 0;
}
void PerlModOutput::iaddQuoted(const QCString &str)
{
if (str.isEmpty()) return;
const char *s = str.data();
char c = 0;
while ((c = *s++) != 0)
{
if ((c == '\'') || (c == '\\'))
{
m_stream->add('\\');
}
m_stream->add(c);
}
}
void PerlModOutput::iaddField(const QCString &s)
{
continueBlock();
m_stream->add(s);
m_stream->add(m_pretty ? " => " : "=>");
}
void PerlModOutput::iaddFieldQuotedChar(const QCString &field, char content)
{
iaddField(field);
m_stream->add('\'');
if ((content == '\'') || (content == '\\'))
m_stream->add('\\');
m_stream->add(content);
m_stream->add('\'');
}
void PerlModOutput::iaddFieldQuotedString(const QCString &field, const QCString &content)
{
if (content == nullptr)
return;
iaddField(field);
m_stream->add('\'');
iaddQuoted(content);
m_stream->add('\'');
}
void PerlModOutput::iopen(char c, const QCString &s)
{
if (s != nullptr)
iaddField(s);
else
continueBlock();
m_stream->add(c);
incIndent();
m_blockstart = true;
}
void PerlModOutput::iclose(char c)
{
decIndent();
indent();
if (c != 0)
m_stream->add(c);
m_blockstart = false;
}
/*! @brief Concrete visitor implementation for PerlMod output. */
class PerlModDocVisitor : public DocVisitor
{
public:
PerlModDocVisitor(PerlModOutput &);
void finish();
//--------------------------------------
// visitor functions for leaf nodes
//--------------------------------------
void operator()(const DocWord &);
void operator()(const DocLinkedWord &);
void operator()(const DocWhiteSpace &);
void operator()(const DocSymbol &);
void operator()(const DocEmoji &);
void operator()(const DocURL &);
void operator()(const DocLineBreak &);
void operator()(const DocHorRuler &);
void operator()(const DocStyleChange &);
void operator()(const DocVerbatim &);
void operator()(const DocAnchor &);
void operator()(const DocInclude &);
void operator()(const DocIncOperator &);
void operator()(const DocFormula &);
void operator()(const DocIndexEntry &);
void operator()(const DocSimpleSectSep &);
void operator()(const DocCite &);
void operator()(const DocSeparator &);
//--------------------------------------
// visitor functions for compound nodes
//--------------------------------------
void operator()(const DocAutoList &);
void operator()(const DocAutoListItem &);
void operator()(const DocPara &) ;
void operator()(const DocRoot &);
void operator()(const DocSimpleSect &);
void operator()(const DocTitle &);
void operator()(const DocSimpleList &);
void operator()(const DocSimpleListItem &);
void operator()(const DocSection &);
void operator()(const DocHtmlList &);
void operator()(const DocHtmlListItem &);
void operator()(const DocHtmlDescList &);
void operator()(const DocHtmlDescTitle &);
void operator()(const DocHtmlDescData &);
void operator()(const DocHtmlTable &);
void operator()(const DocHtmlRow &);
void operator()(const DocHtmlCell &);
void operator()(const DocHtmlCaption &);
void operator()(const DocInternal &);
void operator()(const DocHRef &);
void operator()(const DocHtmlSummary &);
void operator()(const DocHtmlDetails &);
void operator()(const DocHtmlHeader &);
void operator()(const DocImage &);
void operator()(const DocDotFile &);
void operator()(const DocMscFile &);
void operator()(const DocDiaFile &);
void operator()(const DocPlantUmlFile &);
void operator()(const DocLink &);
void operator()(const DocRef &);
void operator()(const DocSecRefItem &);
void operator()(const DocSecRefList &);
void operator()(const DocParamSect &);
void operator()(const DocParamList &);
void operator()(const DocXRefItem &);
void operator()(const DocInternalRef &);
void operator()(const DocText &);
void operator()(const DocHtmlBlockQuote &);
void operator()(const DocVhdlFlow &);
void operator()(const DocParBlock &);
private:
template<class T>
void visitChildren(const T &t)
{
for (const auto &child : t.children())
{
std::visit(*this, child);
}
}
//--------------------------------------
// helper functions
//--------------------------------------
void addLink(const QCString &ref, const QCString &file,
const QCString &anchor);
void enterText();
void leaveText();
void openItem(const QCString &);
void closeItem();
void singleItem(const QCString &);
void openSubBlock(const QCString & = QCString());
void closeSubBlock();
//--------------------------------------
// state variables
//--------------------------------------
PerlModOutput &m_output;
bool m_textmode;
bool m_textblockstart;
QCString m_other;
};
PerlModDocVisitor::PerlModDocVisitor(PerlModOutput &output)
: m_output(output), m_textmode(false), m_textblockstart(FALSE)
{
m_output.openList("doc");
}
void PerlModDocVisitor::finish()
{
leaveText();
m_output.closeList()
.add(m_other);
}
void PerlModDocVisitor::addLink(const QCString &,const QCString &file,const QCString &anchor)
{
QCString link = file;
if (!anchor.isEmpty())
(link += "_1") += anchor;
m_output.addFieldQuotedString("link", link);
}
void PerlModDocVisitor::openItem(const QCString &name)
{
leaveText();
m_output.openHash().addFieldQuotedString("type", name);
}
void PerlModDocVisitor::closeItem()
{
leaveText();
m_output.closeHash();
}
void PerlModDocVisitor::enterText()
{
if (m_textmode)
return;
openItem("text");
m_output.addField("content").add('\'');
m_textmode = true;
}
void PerlModDocVisitor::leaveText()
{
if (!m_textmode)
return;
m_textmode = false;
m_output
.add('\'')
.closeHash();
}
void PerlModDocVisitor::singleItem(const QCString &name)
{
openItem(name);
closeItem();
}
void PerlModDocVisitor::openSubBlock(const QCString &s)
{
leaveText();
m_output.openList(s);
m_textblockstart = true;
}
void PerlModDocVisitor::closeSubBlock()
{
leaveText();
m_output.closeList();
}
//void PerlModDocVisitor::openOther()
//{
// Using a secondary text stream will corrupt the perl file. Instead of
// printing doc => [ data => [] ], it will print doc => [] data => [].
/*
leaveText();
m_output.openSave();
*/
//}
//void PerlModDocVisitor::closeOther()
//{
// Using a secondary text stream will corrupt the perl file. Instead of
// printing doc => [ data => [] ], it will print doc => [] data => [].
/*
QCString other;
leaveText();
m_output.closeSave(other);
m_other += other;
*/
//}
void PerlModDocVisitor::operator()(const DocWord &w)
{
enterText();
m_output.addQuoted(w.word());
}
void PerlModDocVisitor::operator()(const DocLinkedWord &w)
{
openItem("url");
addLink(w.ref(), w.file(), w.anchor());
m_output.addFieldQuotedString("content", w.word());
closeItem();
}
void PerlModDocVisitor::operator()(const DocWhiteSpace &)
{
enterText();
m_output.add(' ');
}
void PerlModDocVisitor::operator()(const DocSymbol &sy)
{
const HtmlEntityMapper::PerlSymb *res = HtmlEntityMapper::instance().perl(sy.symbol());
const char *accent=nullptr;
if (res->symb)
{
switch (res->type)
{
case HtmlEntityMapper::Perl_string:
enterText();
m_output.add(res->symb);
break;
case HtmlEntityMapper::Perl_char:
enterText();
m_output.add(res->symb[0]);
break;
case HtmlEntityMapper::Perl_symbol:
leaveText();
openItem("symbol");
m_output.addFieldQuotedString("symbol", res->symb);
closeItem();
break;
default:
switch(res->type)
{
case HtmlEntityMapper::Perl_umlaut:
accent = "umlaut";
break;
case HtmlEntityMapper::Perl_acute:
accent = "acute";
break;
case HtmlEntityMapper::Perl_grave:
accent = "grave";
break;
case HtmlEntityMapper::Perl_circ:
accent = "circ";
break;
case HtmlEntityMapper::Perl_slash:
accent = "slash";
break;
case HtmlEntityMapper::Perl_tilde:
accent = "tilde";
break;
case HtmlEntityMapper::Perl_cedilla:
accent = "cedilla";
break;
case HtmlEntityMapper::Perl_ring:
accent = "ring";
break;
default:
break;
}
leaveText();
if (accent)
{
openItem("accent");
m_output
.addFieldQuotedString("accent", accent)
.addFieldQuotedChar("letter", res->symb[0]);
closeItem();
}
break;
}
}
else
{
err("perl: non supported HTML-entity found: %s\n",HtmlEntityMapper::instance().html(sy.symbol(),TRUE));
}
}
void PerlModDocVisitor::operator()(const DocEmoji &sy)
{
enterText();
const char *name = EmojiEntityMapper::instance().name(sy.index());
if (name)
{
m_output.add(name);
}
else
{
m_output.add(sy.name());
}
}
void PerlModDocVisitor::operator()(const DocURL &u)
{
openItem("url");
m_output.addFieldQuotedString("content", u.url());
closeItem();
}
void PerlModDocVisitor::operator()(const DocLineBreak &)
{
singleItem("linebreak");
}
void PerlModDocVisitor::operator()(const DocHorRuler &)
{
singleItem("hruler");
}
void PerlModDocVisitor::operator()(const DocStyleChange &s)
{
const char *style = nullptr;
switch (s.style())
{
case DocStyleChange::Bold: style = "bold"; break;
case DocStyleChange::S: style = "s"; break;
case DocStyleChange::Strike: style = "strike"; break;
case DocStyleChange::Del: style = "del"; break;
case DocStyleChange::Underline: style = "underline"; break;
case DocStyleChange::Ins: style = "ins"; break;
case DocStyleChange::Italic: style = "italic"; break;
case DocStyleChange::Code: style = "code"; break;
case DocStyleChange::Subscript: style = "subscript"; break;
case DocStyleChange::Superscript: style = "superscript"; break;
case DocStyleChange::Center: style = "center"; break;
case DocStyleChange::Small: style = "small"; break;
case DocStyleChange::Cite: style = "cite"; break;
case DocStyleChange::Preformatted: style = "preformatted"; break;
case DocStyleChange::Div: style = "div"; break;
case DocStyleChange::Span: style = "span"; break;
case DocStyleChange::Kbd: style = "kbd"; break;
}
openItem("style");
m_output.addFieldQuotedString("style", style)
.addFieldBoolean("enable", s.enable());
closeItem();
}
void PerlModDocVisitor::operator()(const DocVerbatim &s)
{
const char *type = nullptr;
switch (s.type())
{
case DocVerbatim::Code:
#if 0
m_output.add("<programlisting>");
parseCode(m_ci,s->context(),s->text(),FALSE,0);
m_output.add("</programlisting>");
return;
#endif
case DocVerbatim::JavaDocCode:
case DocVerbatim::JavaDocLiteral:
case DocVerbatim::Verbatim: type = "preformatted"; break;
case DocVerbatim::HtmlOnly: type = "htmlonly"; break;
case DocVerbatim::RtfOnly: type = "rtfonly"; break;
case DocVerbatim::ManOnly: type = "manonly"; break;
case DocVerbatim::LatexOnly: type = "latexonly"; break;
case DocVerbatim::XmlOnly: type = "xmlonly"; break;
case DocVerbatim::DocbookOnly: type = "docbookonly"; break;
case DocVerbatim::Dot: type = "dot"; break;
case DocVerbatim::Msc: type = "msc"; break;
case DocVerbatim::PlantUML: type = "plantuml"; break;
}
openItem(type);
if (s.hasCaption())
{
openSubBlock("caption");
visitChildren(s);
closeSubBlock();
}
m_output.addFieldQuotedString("content", s.text());
closeItem();
}
void PerlModDocVisitor::operator()(const DocAnchor &anc)
{
QCString anchor = anc.file() + "_1" + anc.anchor();
openItem("anchor");
m_output.addFieldQuotedString("id", anchor);
closeItem();
}
void PerlModDocVisitor::operator()(const DocInclude &inc)
{
const char *type = nullptr;
switch (inc.type())
{
case DocInclude::IncWithLines:
return;
case DocInclude::Include:
return;
case DocInclude::DontInclude: return;
case DocInclude::DontIncWithLines: return;
case DocInclude::HtmlInclude: type = "htmlonly"; break;
case DocInclude::LatexInclude: type = "latexonly"; break;
case DocInclude::RtfInclude: type = "rtfonly"; break;
case DocInclude::ManInclude: type = "manonly"; break;
case DocInclude::XmlInclude: type = "xmlonly"; break;
case DocInclude::DocbookInclude: type = "docbookonly"; break;
case DocInclude::VerbInclude: type = "preformatted"; break;
case DocInclude::Snippet: return;
case DocInclude::SnippetWithLines: return;
}
openItem(type);
m_output.addFieldQuotedString("content", inc.text());
closeItem();
}
void PerlModDocVisitor::operator()(const DocIncOperator &)
{
#if 0
//printf("DocIncOperator: type=%d first=%d, last=%d text='%s'\n",
// op.type(),op.isFirst(),op.isLast(),op.text().data());
if (op.isFirst())
{
m_output.add("<programlisting>");
}
if (op.type()!=DocIncOperator::Skip)
{
parseCode(m_ci,op.context(),op.text(),FALSE,0);
}
if (op.isLast())
{
m_output.add("</programlisting>");
}
else
{
m_output.add('\n');
}
#endif
}
void PerlModDocVisitor::operator()(const DocFormula &f)
{
openItem("formula");
QCString id;
id += QCString().setNum(f.id());
m_output.addFieldQuotedString("id", id).addFieldQuotedString("content", f.text());
closeItem();
}
void PerlModDocVisitor::operator()(const DocIndexEntry &)
{
#if 0
m_output.add("<indexentry>"
"<primaryie>");
m_output.addQuoted(ie->entry());
m_output.add("</primaryie>"
"<secondaryie></secondaryie>"
"</indexentry>");
#endif
}
void PerlModDocVisitor::operator()(const DocSimpleSectSep &)
{
}
void PerlModDocVisitor::operator()(const DocCite &cite)
{
openItem("cite");
m_output.addFieldQuotedString("text", cite.text());
closeItem();
}
//--------------------------------------
// visitor functions for compound nodes
//--------------------------------------
void PerlModDocVisitor::operator()(const DocAutoList &l)
{
openItem("list");
m_output.addFieldQuotedString("style", l.isEnumList() ? "ordered" : (l.isCheckedList() ? "check" :"itemized"));
openSubBlock("content");
visitChildren(l);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocAutoListItem &li)
{
openSubBlock();
switch (li.itemNumber())
{
case DocAutoList::Unchecked: // unchecked
m_output.addFieldQuotedString("style", "Unchecked");
break;
case DocAutoList::Checked_x: // checked with x
case DocAutoList::Checked_X: // checked with X
m_output.addFieldQuotedString("style", "Checked");
break;
default:
break;
}
visitChildren(li);
closeSubBlock();
}
void PerlModDocVisitor::operator()(const DocPara &p)
{
if (m_textblockstart)
m_textblockstart = false;
else
singleItem("parbreak");
/*
openItem("para");
openSubBlock("content");
*/
visitChildren(p);
/*
closeSubBlock();
closeItem();
*/
}
void PerlModDocVisitor::operator()(const DocRoot &r)
{
visitChildren(r);
}
void PerlModDocVisitor::operator()(const DocSimpleSect &s)
{
const char *type = nullptr;
switch (s.type())
{
case DocSimpleSect::See: type = "see"; break;
case DocSimpleSect::Return: type = "return"; break;
case DocSimpleSect::Author: type = "author"; break;
case DocSimpleSect::Authors: type = "authors"; break;
case DocSimpleSect::Version: type = "version"; break;
case DocSimpleSect::Since: type = "since"; break;
case DocSimpleSect::Date: type = "date"; break;
case DocSimpleSect::Note: type = "note"; break;
case DocSimpleSect::Warning: type = "warning"; break;
case DocSimpleSect::Pre: type = "pre"; break;
case DocSimpleSect::Post: type = "post"; break;
case DocSimpleSect::Copyright: type = "copyright"; break;
case DocSimpleSect::Invar: type = "invariant"; break;
case DocSimpleSect::Remark: type = "remark"; break;
case DocSimpleSect::Attention: type = "attention"; break;
case DocSimpleSect::Important: type = "important"; break;
case DocSimpleSect::User: type = "par"; break;
case DocSimpleSect::Rcs: type = "rcs"; break;
case DocSimpleSect::Unknown:
err("unknown simple section found\n");
break;
}
leaveText();
m_output.openHash();
//openOther();
openSubBlock(type);
if (s.title())
{
std::visit(*this,*s.title());
}
visitChildren(s);
closeSubBlock();
//closeOther();
m_output.closeHash();
}
void PerlModDocVisitor::operator()(const DocTitle &t)
{
openItem("title");
openSubBlock("content");
visitChildren(t);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocSimpleList &l)
{
openItem("list");
m_output.addFieldQuotedString("style", "itemized");
openSubBlock("content");
visitChildren(l);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocSimpleListItem &li)
{
openSubBlock();
if (li.paragraph())
{
std::visit(*this,*li.paragraph());
}
closeSubBlock();
}
void PerlModDocVisitor::operator()(const DocSection &s)
{
QCString sect = QCString().sprintf("sect%d",s.level());
openItem(sect);
//m_output.addFieldQuotedString("title", s.title());
if (s.title())
{
std::visit(*this,*s.title());
}
openSubBlock("content");
visitChildren(s);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocHtmlList &l)
{
openItem("list");
m_output.addFieldQuotedString("style", (l.type() == DocHtmlList::Ordered) ? "ordered" : "itemized");
for (const auto &opt : l.attribs())
{
if (opt.name=="type")
{
m_output.addFieldQuotedString("list_type", qPrint(opt.value));
}
if (opt.name=="start")
{
m_output.addFieldQuotedString("start", qPrint(opt.value));
}
}
openSubBlock("content");
visitChildren(l);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocHtmlListItem &l)
{
for (const auto &opt : l.attribs())
{
if (opt.name=="value")
{
m_output.addFieldQuotedString("item_value", qPrint(opt.value));
}
}
openSubBlock();
visitChildren(l);
closeSubBlock();
}
void PerlModDocVisitor::operator()(const DocHtmlDescList &dl)
{
#if 0
m_output.add("<variablelist>\n");
#endif
visitChildren(dl);
#if 0
m_output.add("</variablelist>\n");
#endif
}
void PerlModDocVisitor::operator()(const DocHtmlDescTitle &dt)
{
#if 0
m_output.add("<varlistentry><term>");
#endif
visitChildren(dt);
#if 0
m_output.add("</term></varlistentry>\n");
#endif
}
void PerlModDocVisitor::operator()(const DocHtmlDescData &dd)
{
#if 0
m_output.add("<listitem>");
#endif
visitChildren(dd);
#if 0
m_output.add("</listitem>\n");
#endif
}
void PerlModDocVisitor::operator()(const DocHtmlTable &t)
{
#if 0
m_output.add("<table rows=\""); m_output.add(t.numRows());
m_output.add("\" cols=\""); m_output.add(t.numCols()); m_output.add("\">");
#endif
if (t.caption())
{
std::visit(*this,*t.caption());
}
visitChildren(t);
#if 0
m_output.add("</table>\n");
#endif
}
void PerlModDocVisitor::operator()(const DocHtmlRow &r)
{
#if 0
m_output.add("<row>\n");
#endif
visitChildren(r);
#if 0
m_output.add("</row>\n");
#endif
}
void PerlModDocVisitor::operator()(const DocHtmlCell &c)
{
#if 0
if (c.isHeading()) m_output.add("<entry thead=\"yes\">"); else m_output.add("<entry thead=\"no\">");
#endif
visitChildren(c);
#if 0
m_output.add("</entry>");
#endif
}
void PerlModDocVisitor::operator()(const DocHtmlCaption &c)
{
#if 0
m_output.add("<caption>");
#endif
visitChildren(c);
#if 0
m_output.add("</caption>\n");
#endif
}
void PerlModDocVisitor::operator()(const DocInternal &i)
{
#if 0
m_output.add("<internal>");
#endif
visitChildren(i);
#if 0
m_output.add("</internal>");
#endif
}
void PerlModDocVisitor::operator()(const DocHRef &href)
{
#if 0
m_output.add("<ulink url=\""); m_output.add(href.url()); m_output.add("\">");
#endif
visitChildren(href);
#if 0
m_output.add("</ulink>");
#endif
}
void PerlModDocVisitor::operator()(const DocHtmlSummary &summary)
{
openItem("summary");
openSubBlock("content");
visitChildren(summary);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocHtmlDetails &details)
{
openItem("details");
auto summary = details.summary();
if (summary)
{
std::visit(*this,*summary);
}
openSubBlock("content");
visitChildren(details);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocHtmlHeader &header)
{
#if 0
m_output.add("<sect"); m_output.add(header.level()); m_output.add(">");
#endif
visitChildren(header);
#if 0
m_output.add("</sect"); m_output.add(header.level()); m_output.add(">\n");
#endif
}
void PerlModDocVisitor::operator()(const DocImage &img)
{
#if 0
m_output.add("<image type=\"");
switch(img.type())
{
case DocImage::Html: m_output.add("html"); break;
case DocImage::Latex: m_output.add("latex"); break;
case DocImage::Rtf: m_output.add("rtf"); break;
}
m_output.add("\"");
QCString baseName=img.name();
int i;
if ((i=baseName.findRev('/'))!=-1 || (i=baseName.findRev('\\'))!=-1)
{
baseName=baseName.right(baseName.length()-i-1);
}
m_output.add(" name=\""); m_output.add(baseName); m_output.add("\"");
if (!img.width().isEmpty())
{
m_output.add(" width=\"");
m_output.addQuoted(img.width());
m_output.add("\"");
}
else if (!img.height().isEmpty())
{
m_output.add(" height=\"");
m_output.addQuoted(img.height());
m_output.add("\"");
}
m_output.add(">");
#endif
visitChildren(img);
#if 0
m_output.add("</image>");
#endif
}
void PerlModDocVisitor::operator()(const DocDotFile &df)
{
#if 0
m_output.add("<dotfile name=\""); m_output.add(df->file()); m_output.add("\">");
#endif
visitChildren(df);
#if 0
m_output.add("</dotfile>");
#endif
}
void PerlModDocVisitor::operator()(const DocMscFile &df)
{
#if 0
m_output.add("<mscfile name=\""); m_output.add(df->file()); m_output.add("\">");
#endif
visitChildren(df);
#if 0
m_output.add("<mscfile>");
#endif
}
void PerlModDocVisitor::operator()(const DocDiaFile &df)
{
#if 0
m_output.add("<diafile name=\""); m_output.add(df->file()); m_output.add("\">");
#endif
visitChildren(df);
#if 0
m_output.add("</diafile>");
#endif
}
void PerlModDocVisitor::operator()(const DocPlantUmlFile &df)
{
#if 0
m_output.add("<plantumlfile name=\""); m_output.add(df->file()); m_output.add("\">");
#endif
visitChildren(df);
#if 0
m_output.add("</plantumlfile>");
#endif
}
void PerlModDocVisitor::operator()(const DocLink &lnk)
{
openItem("link");
addLink(lnk.ref(), lnk.file(), lnk.anchor());
visitChildren(lnk);
closeItem();
}
void PerlModDocVisitor::operator()(const DocRef &ref)
{
openItem("ref");
if (!ref.hasLinkText())
m_output.addFieldQuotedString("text", ref.targetTitle());
openSubBlock("content");
visitChildren(ref);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocSecRefItem &ref)
{
#if 0
m_output.add("<tocitem id=\""); m_output.add(ref->file()); m_output.add("_1"); m_output.add(ref->anchor()); m_output.add("\">");
#endif
visitChildren(ref);
#if 0
m_output.add("</tocitem>");
#endif
}
void PerlModDocVisitor::operator()(const DocSecRefList &l)
{
#if 0
m_output.add("<toclist>");
#endif
visitChildren(l);
#if 0
m_output.add("</toclist>");
#endif
}
void PerlModDocVisitor::operator()(const DocParamSect &s)
{
leaveText();
const char *type = nullptr;
switch(s.type())
{
case DocParamSect::Param: type = "params"; break;
case DocParamSect::RetVal: type = "retvals"; break;
case DocParamSect::Exception: type = "exceptions"; break;
case DocParamSect::TemplateParam: type = "templateparam"; break;
case DocParamSect::Unknown:
err("unknown parameter section found\n");
break;
}
m_output.openHash();
//openOther();
openSubBlock(type);
visitChildren(s);
closeSubBlock();
//closeOther();
m_output.closeHash();
}
void PerlModDocVisitor::operator()(const DocSeparator &)
{
}
void PerlModDocVisitor::operator()(const DocParamList &pl)
{
leaveText();
m_output.openHash().openList("parameters");
for (const auto ¶m : pl.parameters())
{
QCString name;
const DocWord *word = std::get_if<DocWord>(¶m);
const DocLinkedWord *linkedWord = std::get_if<DocLinkedWord>(¶m);
if (word)
{
name = word->word();
}
else if (linkedWord)
{
name = linkedWord->word();
}
QCString dir = "";
const DocParamSect *sect = std::get_if<DocParamSect>(pl.parent());
if (sect && sect->hasInOutSpecifier())
{
if (pl.direction()!=DocParamSect::Unspecified)
{
if (pl.direction()==DocParamSect::In)
{
dir = "in";
}
else if (pl.direction()==DocParamSect::Out)
{
dir = "out";
}
else if (pl.direction()==DocParamSect::InOut)
{
dir = "in,out";
}
}
}
m_output.openHash()
.addFieldQuotedString("name", name).addFieldQuotedString("dir", dir)
.closeHash();
}
m_output.closeList()
.openList("doc");
for (const auto &par : pl.paragraphs())
{
std::visit(*this,par);
}
leaveText();
m_output.closeList()
.closeHash();
}
void PerlModDocVisitor::operator()(const DocXRefItem &x)
{
#if 0
m_output.add("<xrefsect id=\"");
m_output.add(x->file()); m_output.add("_1"); m_output.add(x->anchor());
m_output.add("\">");
m_output.add("<xreftitle>");
m_output.addQuoted(x->title());
m_output.add("</xreftitle>");
m_output.add("<xrefdescription>");
#endif
if (x.title().isEmpty()) return;
openItem("xrefitem");
openSubBlock("content");
visitChildren(x);
if (x.title().isEmpty()) return;
closeSubBlock();
closeItem();
#if 0
m_output.add("</xrefdescription>");
m_output.add("</xrefsect>");
#endif
}
void PerlModDocVisitor::operator()(const DocInternalRef &ref)
{
openItem("ref");
addLink(QCString(),ref.file(),ref.anchor());
openSubBlock("content");
visitChildren(ref);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocText &t)
{
visitChildren(t);
}
void PerlModDocVisitor::operator()(const DocHtmlBlockQuote &q)
{
openItem("blockquote");
openSubBlock("content");
visitChildren(q);
closeSubBlock();
closeItem();
}
void PerlModDocVisitor::operator()(const DocVhdlFlow &)
{
}
void PerlModDocVisitor::operator()(const DocParBlock &pb)
{
visitChildren(pb);
}
static void addTemplateArgumentList(const ArgumentList &al,PerlModOutput &output,const QCString &)
{
if (!al.hasParameters()) return;
output.openList("template_parameters");
for (const Argument &a : al)
{
output.openHash();
if (!a.type.isEmpty())
output.addFieldQuotedString("type", a.type);
if (!a.name.isEmpty())
output.addFieldQuotedString("declaration_name", a.name)
.addFieldQuotedString("definition_name", a.name);
if (!a.defval.isEmpty())
output.addFieldQuotedString("default", a.defval);
output.closeHash();
}
output.closeList();
}
static void addTemplateList(const ClassDef *cd,PerlModOutput &output)
{
addTemplateArgumentList(cd->templateArguments(),output,cd->name());
}
static void addTemplateList(const ConceptDef *cd,PerlModOutput &output)
{
addTemplateArgumentList(cd->getTemplateParameterList(),output,cd->name());
}
static void addPerlModDocBlock(PerlModOutput &output,
const QCString &name,
const QCString &fileName,
int lineNr,
const Definition *scope,
const MemberDef *md,
const QCString &text)
{
QCString stext = text.stripWhiteSpace();
if (stext.isEmpty())
{
output.addField(name).add("{}");
}
else
{
auto parser { createDocParser() };
auto ast { validatingParseDoc(*parser.get(),
fileName,lineNr,scope,md,stext,FALSE,FALSE,
QCString(),FALSE,FALSE,Config_getBool(MARKDOWN_SUPPORT)) };
output.openHash(name);
auto astImpl = dynamic_cast<const DocNodeAST*>(ast.get());
if (astImpl)
{
PerlModDocVisitor visitor(output);
std::visit(visitor,astImpl->root);
visitor.finish();
}
output.closeHash();
}
}
static const char *getProtectionName(Protection prot)
{
switch (prot)
{
case Protection::Public: return "public";
case Protection::Protected: return "protected";
case Protection::Private: return "private";
case Protection::Package: return "package";
}
return nullptr;
}
static const char *getVirtualnessName(Specifier virt)
{
switch(virt)
{
case Specifier::Normal: return "non_virtual";
case Specifier::Virtual: return "virtual";
case Specifier::Pure: return "pure_virtual";
}
return nullptr;
}
static QCString pathDoxyfile;
static QCString pathDoxyExec;
void setPerlModDoxyfile(const QCString &qs)
{
pathDoxyfile = qs;
pathDoxyExec = Dir::currentDirPath();
}
class PerlModGenerator
{
public:
PerlModOutput m_output;
QCString pathDoxyStructurePM;
QCString pathDoxyDocsTex;
QCString pathDoxyFormatTex;
QCString pathDoxyLatexTex;
QCString pathDoxyLatexDVI;
QCString pathDoxyLatexPDF;
QCString pathDoxyStructureTex;
QCString pathDoxyDocsPM;
QCString pathDoxyLatexPL;
QCString pathDoxyLatexStructurePL;
QCString pathDoxyRules;
QCString pathMakefile;
inline PerlModGenerator(bool pretty) : m_output(pretty) { }
void generatePerlModForMember(const MemberDef *md, const Definition *);
void generatePerlUserDefinedSection(const Definition *d, const MemberGroupList &mgl);
void generatePerlModSection(const Definition *d, MemberList *ml,
const QCString &name, const QCString &header=QCString());
void addListOfAllMembers(const ClassDef *cd);
void addIncludeInfo(const IncludeInfo *ii);
void generatePerlModForClass(const ClassDef *cd);
void generatePerlModForConcept(const ConceptDef *cd);
void generatePerlModForModule(const ModuleDef *mod);
void generatePerlModForNamespace(const NamespaceDef *nd);
void generatePerlModForFile(const FileDef *fd);
void generatePerlModForGroup(const GroupDef *gd);
void generatePerlModForPage(PageDef *pi);
bool createOutputFile(std::ofstream &f, const QCString &s);
bool createOutputDir(Dir &perlModDir);
bool generateDoxyLatexTex();
bool generateDoxyFormatTex();
bool generateDoxyStructurePM();
bool generateDoxyLatexPL();
bool generateDoxyLatexStructurePL();
bool generateDoxyRules();
bool generateMakefile();
bool generatePerlModOutput();
void generate();
};
void PerlModGenerator::generatePerlModForMember(const MemberDef *md,const Definition *)
{
// + declaration/definition arg lists
// + reimplements
// + reimplementedBy
// + exceptions
// + const/volatile specifiers
// - examples
// - source definition
// - source references
// - source referenced by
// - body code
// - template arguments
// (templateArguments(), definitionTemplateParameterLists())
QCString memType;
QCString name;
bool isFunc=FALSE;
switch (md->memberType())
{
case MemberType::Define: memType="define"; break;
case MemberType::EnumValue: memType="enumvalue"; break;
case MemberType::Property: memType="property"; break;
case MemberType::Variable: memType="variable"; break;
case MemberType::Typedef: memType="typedef"; break;
case MemberType::Enumeration: memType="enum"; break;
case MemberType::Function: memType="function"; isFunc=TRUE; break;
case MemberType::Signal: memType="signal"; isFunc=TRUE; break;
case MemberType::Friend: memType="friend"; isFunc=TRUE; break;
case MemberType::DCOP: memType="dcop"; isFunc=TRUE; break;
case MemberType::Slot: memType="slot"; isFunc=TRUE; break;
case MemberType::Event: memType="event"; break;
case MemberType::Interface: memType="interface"; break;
case MemberType::Service: memType="service"; break;
case MemberType::Sequence: memType="sequence"; break;
case MemberType::Dictionary: memType="dictionary"; break;
}
bool isFortran = md->getLanguage()==SrcLangExt::Fortran;
name = md->name();
if (md->isAnonymous()) name = "__unnamed" + name.right(name.length() - 1)+"__";
m_output.openHash()
.addFieldQuotedString("kind", memType)
.addFieldQuotedString("name", name)
.addFieldQuotedString("virtualness", getVirtualnessName(md->virtualness()))
.addFieldQuotedString("protection", getProtectionName(md->protection()))
.addFieldBoolean("static", md->isStatic());
addPerlModDocBlock(m_output,"brief",md->getDefFileName(),md->getDefLine(),md->getOuterScope(),md,md->briefDescription());
addPerlModDocBlock(m_output,"detailed",md->getDefFileName(),md->getDefLine(),md->getOuterScope(),md,md->documentation());
if (md->memberType()!=MemberType::Define &&
md->memberType()!=MemberType::Enumeration)
m_output.addFieldQuotedString("type", md->typeString());
const ArgumentList &al = md->argumentList();
if (isFunc) //function
{
m_output.addFieldBoolean("const", al.constSpecifier())
.addFieldBoolean("volatile", al.volatileSpecifier());
m_output.openList("parameters");
const ArgumentList &declAl = md->declArgumentList();
if (!declAl.empty())
{
auto defIt = al.begin();
for (const Argument &a : declAl)
{
const Argument *defArg = nullptr;
if (defIt!=al.end())
{
defArg = &(*defIt);
++defIt;
}
m_output.openHash();
if (!a.name.isEmpty())
m_output.addFieldQuotedString("declaration_name", a.name);
if (defArg && !defArg->name.isEmpty() && defArg->name!=a.name)
m_output.addFieldQuotedString("definition_name", defArg->name);
if (isFortran && defArg && !defArg->type.isEmpty())
m_output.addFieldQuotedString("type", defArg->type);
else if (!a.type.isEmpty())
m_output.addFieldQuotedString("type", a.type);
if (!a.array.isEmpty())
m_output.addFieldQuotedString("array", a.array);
if (!a.defval.isEmpty())
m_output.addFieldQuotedString("default_value", a.defval);
if (!a.attrib.isEmpty())
m_output.addFieldQuotedString("attributes", a.attrib);
m_output.closeHash();
}
}
m_output.closeList();
}
else if (md->memberType()==MemberType::Define &&
md->argsString()!=nullptr) // define
{
m_output.openList("parameters");
for (const Argument &a : al)
{
m_output.openHash()
.addFieldQuotedString("name", a.type)
.closeHash();
}
m_output.closeList();
}
else if (md->argsString()!=nullptr)
{
m_output.addFieldQuotedString("arguments", md->argsString());
}
if (!md->initializer().isEmpty())
m_output.addFieldQuotedString("initializer", md->initializer());
if (!md->excpString().isEmpty())
m_output.addFieldQuotedString("exceptions", md->excpString());
if (md->memberType()==MemberType::Enumeration) // enum
{
const MemberVector &enumFields = md->enumFieldList();
m_output.addFieldQuotedString("type", md->enumBaseType());
if (!enumFields.empty())
{
m_output.openList("values");
for (const auto &emd : enumFields)
{
m_output.openHash()
.addFieldQuotedString("name", emd->name());
if (!emd->initializer().isEmpty())
m_output.addFieldQuotedString("initializer", emd->initializer());
addPerlModDocBlock(m_output,"brief",emd->getDefFileName(),emd->getDefLine(),emd->getOuterScope(),emd,emd->briefDescription());
addPerlModDocBlock(m_output,"detailed",emd->getDefFileName(),emd->getDefLine(),emd->getOuterScope(),emd,emd->documentation());
m_output.closeHash();
}
m_output.closeList();
}
}
if (md->memberType() == MemberType::Variable && !md->bitfieldString().isEmpty())
{
QCString bitfield = md->bitfieldString();
if (bitfield.at(0) == ':') bitfield = bitfield.mid(1);
m_output.addFieldQuotedString("bitfield", bitfield);
}
const MemberDef *rmd = md->reimplements();
if (rmd)
m_output.openHash("reimplements")
.addFieldQuotedString("name", rmd->name())
.closeHash();
const MemberVector &rbml = md->reimplementedBy();
if (!rbml.empty())
{
m_output.openList("reimplemented_by");
for (const auto &rbmd : rbml)
m_output.openHash()
.addFieldQuotedString("name", rbmd->name())
.closeHash();
m_output.closeList();
}
m_output.closeHash();
}
void PerlModGenerator::generatePerlModSection(const Definition *d,
MemberList *ml,const QCString &name,const QCString &header)
{
if (ml==nullptr) return; // empty list
m_output.openHash(name);
if (!header.isEmpty())
m_output.addFieldQuotedString("header", header);
m_output.openList("members");
for (const auto &md : *ml)
{
generatePerlModForMember(md,d);
}
m_output.closeList()
.closeHash();
}
void PerlModGenerator::addListOfAllMembers(const ClassDef *cd)
{
m_output.openList("all_members");
for (auto &mni : cd->memberNameInfoLinkedMap())
{
for (auto &mi : *mni)
{
const MemberDef *md=mi->memberDef();
const ClassDef *mcd=md->getClassDef();
m_output.openHash()
.addFieldQuotedString("name", md->name())
.addFieldQuotedString("virtualness", getVirtualnessName(md->virtualness()))
.addFieldQuotedString("protection", getProtectionName(mi->prot()));
if (!mi->ambiguityResolutionScope().isEmpty())
m_output.addFieldQuotedString("ambiguity_scope", mi->ambiguityResolutionScope());
m_output.addFieldQuotedString("scope", mcd->name())
.closeHash();
}
}
m_output.closeList();
}
void PerlModGenerator::generatePerlUserDefinedSection(const Definition *d, const MemberGroupList &mgl)
{
if (!mgl.empty())
{
m_output.openList("user_defined");
for (const auto &mg : mgl)
{
m_output.openHash();
if (!mg->header().isEmpty())
{
m_output.addFieldQuotedString("header", mg->header());
}
if (!mg->members().empty())
{
m_output.openList("members");
for (const auto &md : mg->members())
{
generatePerlModForMember(md, d);
}
m_output.closeList();
}
m_output.closeHash();
}
m_output.closeList();
}
}
void PerlModGenerator::addIncludeInfo(const IncludeInfo *ii)
{
if (ii)
{
QCString nm = ii->includeName;
if (nm.isEmpty() && ii->fileDef) nm = ii->fileDef->docName();
if (!nm.isEmpty())
{
m_output.openHash("includes");
m_output.addFieldBoolean("local", ii->kind==IncludeKind::IncludeLocal || ii->kind==IncludeKind::ImportLocal)
.addFieldQuotedString("name", nm)
.closeHash();
}
}
}
void PerlModGenerator::generatePerlModForClass(const ClassDef *cd)
{
// + brief description
// + detailed description
// + template argument list(s)
// - include file
// + member groups
// + inheritance diagram
// + list of direct super classes
// + list of direct sub classes
// + list of inner classes
// + collaboration diagram
// + list of all members
// + user defined member sections
// + standard member sections
// + detailed member documentation
// - examples using the class
if (cd->isReference()) return; // skip external references.
if (cd->isAnonymous()) return; // skip anonymous compounds.
if (cd->templateMaster()!=nullptr) return; // skip generated template instances.
m_output.openHash()
.addFieldQuotedString("name", cd->name());
/* DGA: fix # #7547 Perlmod does not generate "kind" information to discriminate struct/union */
m_output.addFieldQuotedString("kind", cd->compoundTypeString());
if (!cd->baseClasses().empty())
{
m_output.openList("base");
for (const auto &bcd : cd->baseClasses())
{
m_output.openHash()
.addFieldQuotedString("name", bcd.classDef->displayName())
.addFieldQuotedString("virtualness", getVirtualnessName(bcd.virt))
.addFieldQuotedString("protection", getProtectionName(bcd.prot))
.closeHash();
}
m_output.closeList();
}
if (!cd->subClasses().empty())
{
m_output.openList("derived");
for (const auto &bcd : cd->subClasses())
{
m_output.openHash()
.addFieldQuotedString("name", bcd.classDef->displayName())
.addFieldQuotedString("virtualness", getVirtualnessName(bcd.virt))
.addFieldQuotedString("protection", getProtectionName(bcd.prot))
.closeHash();
}
m_output.closeList();
}
{
m_output.openList("inner");
for (const auto &icd : cd->getClasses())
m_output.openHash()
.addFieldQuotedString("name", icd->name())
.closeHash();
m_output.closeList();
}
addIncludeInfo(cd->includeInfo());
addTemplateList(cd,m_output);
addListOfAllMembers(cd);
generatePerlUserDefinedSection(cd, cd->getMemberGroups());
generatePerlModSection(cd,cd->getMemberList(MemberListType::PubTypes()),"public_typedefs");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PubMethods()),"public_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PubAttribs()),"public_members");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PubSlots()),"public_slots");
generatePerlModSection(cd,cd->getMemberList(MemberListType::Signals()),"signals");
generatePerlModSection(cd,cd->getMemberList(MemberListType::DcopMethods()),"dcop_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::Properties()),"properties");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PubStaticMethods()),"public_static_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PubStaticAttribs()),"public_static_members");
generatePerlModSection(cd,cd->getMemberList(MemberListType::ProTypes()),"protected_typedefs");
generatePerlModSection(cd,cd->getMemberList(MemberListType::ProMethods()),"protected_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::ProAttribs()),"protected_members");
generatePerlModSection(cd,cd->getMemberList(MemberListType::ProSlots()),"protected_slots");
generatePerlModSection(cd,cd->getMemberList(MemberListType::ProStaticMethods()),"protected_static_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::ProStaticAttribs()),"protected_static_members");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PriTypes()),"private_typedefs");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PriMethods()),"private_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PriAttribs()),"private_members");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PriSlots()),"private_slots");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PriStaticMethods()),"private_static_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::PriStaticAttribs()),"private_static_members");
generatePerlModSection(cd,cd->getMemberList(MemberListType::Friends()),"friend_methods");
generatePerlModSection(cd,cd->getMemberList(MemberListType::Related()),"related_methods");
addPerlModDocBlock(m_output,"brief",cd->getDefFileName(),cd->getDefLine(),cd,nullptr,cd->briefDescription());
addPerlModDocBlock(m_output,"detailed",cd->getDefFileName(),cd->getDefLine(),cd,nullptr,cd->documentation());
#if 0
DotClassGraph inheritanceGraph(cd,DotClassGraph::Inheritance);
if (!inheritanceGraph.isTrivial())
{
t << " <inheritancegraph>" << endl;
inheritanceGraph.writePerlMod(t);
t << " </inheritancegraph>" << endl;
}
DotClassGraph collaborationGraph(cd,DotClassGraph::Implementation);
if (!collaborationGraph.isTrivial())
{
t << " <collaborationgraph>" << endl;
collaborationGraph.writePerlMod(t);
t << " </collaborationgraph>" << endl;
}
t << " <location file=\""
<< cd->getDefFileName() << "\" line=\""
<< cd->getDefLine() << "\"";
if (cd->getStartBodyLine()!=-1)
{
t << " bodystart=\"" << cd->getStartBodyLine() << "\" bodyend=\""
<< cd->getEndBodyLine() << "\"";
}
t << "/>" << endl;
#endif
m_output.closeHash();
}
void PerlModGenerator::generatePerlModForConcept(const ConceptDef *cd)
{
if (cd->isReference()) return; // skip external references
m_output.openHash()
.addFieldQuotedString("name", cd->name());
addIncludeInfo(cd->includeInfo());
addTemplateList(cd,m_output);
m_output.addFieldQuotedString("initializer", cd->initializer());
addPerlModDocBlock(m_output,"brief",cd->getDefFileName(),cd->getDefLine(),nullptr,nullptr,cd->briefDescription());
addPerlModDocBlock(m_output,"detailed",cd->getDefFileName(),cd->getDefLine(),nullptr,nullptr,cd->documentation());
m_output.closeHash();
}
void PerlModGenerator::generatePerlModForModule(const ModuleDef *mod)
{
// + contained class definitions
// + contained concept definitions
// + member groups
// + normal members
// + brief desc
// + detailed desc
// + location (file_id, line, column)
// - exports
// + used files
if (mod->isReference()) return; // skip external references
m_output.openHash()
.addFieldQuotedString("name", mod->name());
generatePerlUserDefinedSection(mod, mod->getMemberGroups());
if (!mod->getClasses().empty())
{
m_output.openList("classes");
for (const auto &cd : mod->getClasses())
m_output.openHash()
.addFieldQuotedString("name", cd->name())
.closeHash();
m_output.closeList();
}
if (!mod->getConcepts().empty())
{
m_output.openList("concepts");
for (const auto &cd : mod->getConcepts())
m_output.openHash()
.addFieldQuotedString("name", cd->name())
.closeHash();
m_output.closeList();
}
generatePerlModSection(mod,mod->getMemberList(MemberListType::DecTypedefMembers()),"typedefs");
generatePerlModSection(mod,mod->getMemberList(MemberListType::DecEnumMembers()),"enums");
generatePerlModSection(mod,mod->getMemberList(MemberListType::DecFuncMembers()),"functions");
generatePerlModSection(mod,mod->getMemberList(MemberListType::DecVarMembers()),"variables");
addPerlModDocBlock(m_output,"brief",mod->getDefFileName(),mod->getDefLine(),nullptr,nullptr,mod->briefDescription());
addPerlModDocBlock(m_output,"detailed",mod->getDefFileName(),mod->getDefLine(),nullptr,nullptr,mod->documentation());
if (!mod->getUsedFiles().empty())
{
m_output.openList("files");
for (const auto &fd : mod->getUsedFiles())
m_output.openHash()
.addFieldQuotedString("name", fd->name())
.closeHash();
m_output.closeList();
}
m_output.closeHash();
}
void PerlModGenerator::generatePerlModForNamespace(const NamespaceDef *nd)
{
// + contained class definitions
// + contained namespace definitions
// + member groups
// + normal members
// + brief desc
// + detailed desc
// + location
// - files containing (parts of) the namespace definition
if (nd->isReference()) return; // skip external references
m_output.openHash()
.addFieldQuotedString("name", nd->name());
if (!nd->getClasses().empty())
{
m_output.openList("classes");
for (const auto &cd : nd->getClasses())
m_output.openHash()
.addFieldQuotedString("name", cd->name())
.closeHash();
m_output.closeList();
}
if (!nd->getNamespaces().empty())
{
m_output.openList("namespaces");
for (const auto &ind : nd->getNamespaces())
m_output.openHash()
.addFieldQuotedString("name", ind->name())
.closeHash();
m_output.closeList();
}
generatePerlUserDefinedSection(nd, nd->getMemberGroups());
generatePerlModSection(nd,nd->getMemberList(MemberListType::DecDefineMembers()),"defines");
generatePerlModSection(nd,nd->getMemberList(MemberListType::DecProtoMembers()),"prototypes");
generatePerlModSection(nd,nd->getMemberList(MemberListType::DecTypedefMembers()),"typedefs");
generatePerlModSection(nd,nd->getMemberList(MemberListType::DecEnumMembers()),"enums");
generatePerlModSection(nd,nd->getMemberList(MemberListType::DecFuncMembers()),"functions");
generatePerlModSection(nd,nd->getMemberList(MemberListType::DecVarMembers()),"variables");
addPerlModDocBlock(m_output,"brief",nd->getDefFileName(),nd->getDefLine(),nullptr,nullptr,nd->briefDescription());
addPerlModDocBlock(m_output,"detailed",nd->getDefFileName(),nd->getDefLine(),nullptr,nullptr,nd->documentation());
m_output.closeHash();
}
void PerlModGenerator::generatePerlModForFile(const FileDef *fd)
{
// + includes files
// + includedby files
// - include graph
// - included by graph
// - contained class definitions
// - contained namespace definitions
// - member groups
// + normal members
// + brief desc
// + detailed desc
// - source code
// - location
// - number of lines
if (fd->isReference()) return;
m_output.openHash()
.addFieldQuotedString("name", fd->name());
m_output.openList("includes");
for (const auto &inc: fd->includeFileList())
{
m_output.openHash()
.addFieldQuotedString("name", inc.includeName);
if (inc.fileDef && !inc.fileDef->isReference())
{
m_output.addFieldQuotedString("ref", inc.fileDef->getOutputFileBase());
}
m_output.closeHash();
}
m_output.closeList();
m_output.openList("included_by");
for (const auto &inc : fd->includedByFileList())
{
m_output.openHash()
.addFieldQuotedString("name", inc.includeName);
if (inc.fileDef && !inc.fileDef->isReference())
{
m_output.addFieldQuotedString("ref", inc.fileDef->getOutputFileBase());
}
m_output.closeHash();
}
m_output.closeList();
generatePerlUserDefinedSection(fd, fd->getMemberGroups());
generatePerlModSection(fd,fd->getMemberList(MemberListType::DecDefineMembers()),"defines");
generatePerlModSection(fd,fd->getMemberList(MemberListType::DecProtoMembers()),"prototypes");
generatePerlModSection(fd,fd->getMemberList(MemberListType::DecTypedefMembers()),"typedefs");
generatePerlModSection(fd,fd->getMemberList(MemberListType::DecEnumMembers()),"enums");
generatePerlModSection(fd,fd->getMemberList(MemberListType::DecFuncMembers()),"functions");
generatePerlModSection(fd,fd->getMemberList(MemberListType::DecVarMembers()),"variables");
addPerlModDocBlock(m_output,"brief",fd->getDefFileName(),fd->getDefLine(),nullptr,nullptr,fd->briefDescription());
addPerlModDocBlock(m_output,"detailed",fd->getDefFileName(),fd->getDefLine(),nullptr,nullptr,fd->documentation());
m_output.closeHash();
}
void PerlModGenerator::generatePerlModForGroup(const GroupDef *gd)
{
// + members
// + member groups
// + files
// + classes
// + namespaces
// - packages
// + pages
// + child groups
// - examples
// + brief description
// + detailed description
if (gd->isReference()) return; // skip external references
m_output.openHash()
.addFieldQuotedString("name", gd->name())
.addFieldQuotedString("title", gd->groupTitle());
if (!gd->getFiles().empty())
{
m_output.openList("files");
for (const auto &fd : gd->getFiles())
m_output.openHash()
.addFieldQuotedString("name", fd->name())
.closeHash();
m_output.closeList();
}
if (!gd->getClasses().empty())
{
m_output.openList("classes");
for (const auto &cd : gd->getClasses())
m_output.openHash()
.addFieldQuotedString("name", cd->name())
.closeHash();
m_output.closeList();
}
if (!gd->getConcepts().empty())
{
m_output.openList("concepts");
for (const auto &cd : gd->getConcepts())
m_output.openHash()
.addFieldQuotedString("name", cd->name())
.closeHash();
m_output.closeList();
}
if (!gd->getModules().empty())
{
m_output.openList("modules");
for (const auto &mod : gd->getModules())
m_output.openHash()
.addFieldQuotedString("name", mod->name())
.closeHash();
m_output.closeList();
}
if (!gd->getNamespaces().empty())
{
m_output.openList("namespaces");
for (const auto &nd : gd->getNamespaces())
m_output.openHash()
.addFieldQuotedString("name", nd->name())
.closeHash();
m_output.closeList();
}
if (!gd->getPages().empty())
{
m_output.openList("pages");
for (const auto &pd : gd->getPages())
m_output.openHash()
.addFieldQuotedString("title", pd->title())
.closeHash();
m_output.closeList();
}
if (!gd->getSubGroups().empty())
{
m_output.openList("groups");
for (const auto &sgd : gd->getSubGroups())
m_output.openHash()
.addFieldQuotedString("title", sgd->groupTitle())
.closeHash();
m_output.closeList();
}
generatePerlUserDefinedSection(gd, gd->getMemberGroups());
generatePerlModSection(gd,gd->getMemberList(MemberListType::DecDefineMembers()),"defines");
generatePerlModSection(gd,gd->getMemberList(MemberListType::DecProtoMembers()),"prototypes");
generatePerlModSection(gd,gd->getMemberList(MemberListType::DecTypedefMembers()),"typedefs");
generatePerlModSection(gd,gd->getMemberList(MemberListType::DecEnumMembers()),"enums");
generatePerlModSection(gd,gd->getMemberList(MemberListType::DecFuncMembers()),"functions");
generatePerlModSection(gd,gd->getMemberList(MemberListType::DecVarMembers()),"variables");
addPerlModDocBlock(m_output,"brief",gd->getDefFileName(),gd->getDefLine(),nullptr,nullptr,gd->briefDescription());
addPerlModDocBlock(m_output,"detailed",gd->getDefFileName(),gd->getDefLine(),nullptr,nullptr,gd->documentation());
m_output.closeHash();
}
void PerlModGenerator::generatePerlModForPage(PageDef *pd)
{
// + name
// + title
// + documentation
if (pd->isReference()) return;
m_output.openHash()
.addFieldQuotedString("name", pd->name());
const SectionInfo *si = SectionManager::instance().find(pd->name());
if (si)
m_output.addFieldQuotedString("title4", filterTitle(si->title()));
addPerlModDocBlock(m_output,"detailed",pd->docFile(),pd->docLine(),nullptr,nullptr,pd->documentation());
m_output.closeHash();
}
bool PerlModGenerator::generatePerlModOutput()
{
std::ofstream outputFileStream;
if (!createOutputFile(outputFileStream, pathDoxyDocsPM))
return false;
PerlModOutputStream outputStream(outputFileStream);
m_output.setPerlModOutputStream(&outputStream);
m_output.add("$doxydocs=").openHash();
m_output.openList("classes");
for (const auto &cd : *Doxygen::classLinkedMap)
generatePerlModForClass(cd.get());
m_output.closeList();
m_output.openList("concepts");
for (const auto &cd : *Doxygen::conceptLinkedMap)
generatePerlModForConcept(cd.get());
m_output.closeList();
m_output.openList("modules");
for (const auto &mod : ModuleManager::instance().modules())
generatePerlModForModule(mod.get());
m_output.closeList();
m_output.openList("namespaces");
for (const auto &nd : *Doxygen::namespaceLinkedMap)
generatePerlModForNamespace(nd.get());
m_output.closeList();
m_output.openList("files");
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
generatePerlModForFile(fd.get());
}
}
m_output.closeList();
m_output.openList("groups");
for (const auto &gd : *Doxygen::groupLinkedMap)
{
generatePerlModForGroup(gd.get());
}
m_output.closeList();
m_output.openList("pages");
for (const auto &pd : *Doxygen::pageLinkedMap)
{
generatePerlModForPage(pd.get());
}
if (Doxygen::mainPage)
{
generatePerlModForPage(Doxygen::mainPage.get());
}
m_output.closeList();
m_output.closeHash().add(";\n1;\n");
m_output.reset();
return true;
}
bool PerlModGenerator::createOutputFile(std::ofstream &f, const QCString &s)
{
f = Portable::openOutputStream(s);
if (!f.is_open())
{
err("Cannot open file %s for writing!\n", qPrint(s));
return false;
}
return true;
}
bool PerlModGenerator::createOutputDir(Dir &perlModDir)
{
std::string outputDirectory = Config_getString(OUTPUT_DIRECTORY).str();
perlModDir.setPath(outputDirectory+"/perlmod");
if (!perlModDir.exists() && !perlModDir.mkdir(outputDirectory+"/perlmod"))
{
err("Could not create perlmod directory in %s\n",outputDirectory.data());
return false;
}
return true;
}
bool PerlModGenerator::generateDoxyStructurePM()
{
std::ofstream doxyModelPMStream;
if (!createOutputFile(doxyModelPMStream, pathDoxyStructurePM))
return false;
doxyModelPMStream <<
"sub memberlist($) {\n"
" my $prefix = $_[0];\n"
" return\n"
"\t[ \"hash\", $prefix . \"s\",\n"
"\t {\n"
"\t members =>\n"
"\t [ \"list\", $prefix . \"List\",\n"
"\t\t[ \"hash\", $prefix,\n"
"\t\t {\n"
"\t\t kind => [ \"string\", $prefix . \"Kind\" ],\n"
"\t\t name => [ \"string\", $prefix . \"Name\" ],\n"
"\t\t static => [ \"string\", $prefix . \"Static\" ],\n"
"\t\t virtualness => [ \"string\", $prefix . \"Virtualness\" ],\n"
"\t\t protection => [ \"string\", $prefix . \"Protection\" ],\n"
"\t\t type => [ \"string\", $prefix . \"Type\" ],\n"
"\t\t parameters =>\n"
"\t\t [ \"list\", $prefix . \"Params\",\n"
"\t\t\t[ \"hash\", $prefix . \"Param\",\n"
"\t\t\t {\n"
"\t\t\t declaration_name => [ \"string\", $prefix . \"ParamName\" ],\n"
"\t\t\t type => [ \"string\", $prefix . \"ParamType\" ],\n"
"\t\t\t },\n"
"\t\t\t],\n"
"\t\t ],\n"
"\t\t detailed =>\n"
"\t\t [ \"hash\", $prefix . \"Detailed\",\n"
"\t\t\t{\n"
"\t\t\t doc => [ \"doc\", $prefix . \"DetailedDoc\" ],\n"
"\t\t\t return => [ \"doc\", $prefix . \"Return\" ],\n"
"\t\t\t see => [ \"doc\", $prefix . \"See\" ],\n"
"\t\t\t params =>\n"
"\t\t\t [ \"list\", $prefix . \"PDBlocks\",\n"
"\t\t\t [ \"hash\", $prefix . \"PDBlock\",\n"
"\t\t\t\t{\n"
"\t\t\t\t parameters =>\n"
"\t\t\t\t [ \"list\", $prefix . \"PDParams\",\n"
"\t\t\t\t [ \"hash\", $prefix . \"PDParam\",\n"
"\t\t\t\t\t{\n"
"\t\t\t\t\t name => [ \"string\", $prefix . \"PDParamName\" ],\n"
"\t\t\t\t\t},\n"
"\t\t\t\t ],\n"
"\t\t\t\t ],\n"
"\t\t\t\t doc => [ \"doc\", $prefix . \"PDDoc\" ],\n"
"\t\t\t\t},\n"
"\t\t\t ],\n"
"\t\t\t ],\n"
"\t\t\t},\n"
"\t\t ],\n"
"\t\t },\n"
"\t\t],\n"
"\t ],\n"
"\t },\n"
"\t];\n"
"}\n"
"\n"
"$doxystructure =\n"
" [ \"hash\", \"Root\",\n"
" {\n"
"\tfiles =>\n"
"\t [ \"list\", \"Files\",\n"
"\t [ \"hash\", \"File\",\n"
"\t {\n"
"\t\tname => [ \"string\", \"FileName\" ],\n"
"\t\ttypedefs => memberlist(\"FileTypedef\"),\n"
"\t\tvariables => memberlist(\"FileVariable\"),\n"
"\t\tfunctions => memberlist(\"FileFunction\"),\n"
"\t\tdetailed =>\n"
"\t\t [ \"hash\", \"FileDetailed\",\n"
"\t\t {\n"
"\t\t doc => [ \"doc\", \"FileDetailedDoc\" ],\n"
"\t\t },\n"
"\t\t ],\n"
"\t },\n"
"\t ],\n"
"\t ],\n"
"\tpages =>\n"
"\t [ \"list\", \"Pages\",\n"
"\t [ \"hash\", \"Page\",\n"
"\t {\n"
"\t\tname => [ \"string\", \"PageName\" ],\n"
"\t\tdetailed =>\n"
"\t\t [ \"hash\", \"PageDetailed\",\n"
"\t\t {\n"
"\t\t doc => [ \"doc\", \"PageDetailedDoc\" ],\n"
"\t\t },\n"
"\t\t ],\n"
"\t },\n"
"\t ],\n"
"\t ],\n"
"\tclasses =>\n"
"\t [ \"list\", \"Classes\",\n"
"\t [ \"hash\", \"Class\",\n"
"\t {\n"
"\t\tname => [ \"string\", \"ClassName\" ],\n"
"\t\tpublic_typedefs => memberlist(\"ClassPublicTypedef\"),\n"
"\t\tpublic_methods => memberlist(\"ClassPublicMethod\"),\n"
"\t\tpublic_members => memberlist(\"ClassPublicMember\"),\n"
"\t\tprotected_typedefs => memberlist(\"ClassProtectedTypedef\"),\n"
"\t\tprotected_methods => memberlist(\"ClassProtectedMethod\"),\n"
"\t\tprotected_members => memberlist(\"ClassProtectedMember\"),\n"
"\t\tprivate_typedefs => memberlist(\"ClassPrivateTypedef\"),\n"
"\t\tprivate_methods => memberlist(\"ClassPrivateMethod\"),\n"
"\t\tprivate_members => memberlist(\"ClassPrivateMember\"),\n"
"\t\tdetailed =>\n"
"\t\t [ \"hash\", \"ClassDetailed\",\n"
"\t\t {\n"
"\t\t doc => [ \"doc\", \"ClassDetailedDoc\" ],\n"
"\t\t },\n"
"\t\t ],\n"
"\t },\n"
"\t ],\n"
"\t ],\n"
"\tgroups =>\n"
"\t [ \"list\", \"Groups\",\n"
"\t [ \"hash\", \"Group\",\n"
"\t {\n"
"\t\tname => [ \"string\", \"GroupName\" ],\n"
"\t\ttitle => [ \"string\", \"GroupTitle\" ],\n"
"\t\tfiles =>\n"
"\t\t [ \"list\", \"Files\",\n"
"\t\t [ \"hash\", \"File\",\n"
"\t\t {\n"
"\t\t name => [ \"string\", \"Filename\" ]\n"
"\t\t }\n"
"\t\t ],\n"
"\t\t ],\n"
"\t\tclasses =>\n"
"\t\t [ \"list\", \"Classes\",\n"
"\t\t [ \"hash\", \"Class\",\n"
"\t\t {\n"
"\t\t name => [ \"string\", \"Classname\" ]\n"
"\t\t }\n"
"\t\t ],\n"
"\t\t ],\n"
"\t\tnamespaces =>\n"
"\t\t [ \"list\", \"Namespaces\",\n"
"\t\t [ \"hash\", \"Namespace\",\n"
"\t\t {\n"
"\t\t name => [ \"string\", \"NamespaceName\" ]\n"
"\t\t }\n"
"\t\t ],\n"
"\t\t ],\n"
"\t\tpages =>\n"
"\t\t [ \"list\", \"Pages\",\n"
"\t\t [ \"hash\", \"Page\","
"\t\t {\n"
"\t\t title => [ \"string\", \"PageName\" ]\n"
"\t\t }\n"
"\t\t ],\n"
"\t\t ],\n"
"\t\tgroups =>\n"
"\t\t [ \"list\", \"Groups\",\n"
"\t\t [ \"hash\", \"Group\",\n"
"\t\t {\n"
"\t\t title => [ \"string\", \"GroupName\" ]\n"
"\t\t }\n"
"\t\t ],\n"
"\t\t ],\n"
"\t\tfunctions => memberlist(\"GroupFunction\"),\n"
"\t\tdetailed =>\n"
"\t\t [ \"hash\", \"GroupDetailed\",\n"
"\t\t {\n"
"\t\t doc => [ \"doc\", \"GroupDetailedDoc\" ],\n"
"\t\t },\n"
"\t\t ],\n"
"\t }\n"
"\t ],\n"
"\t ],\n"
" },\n"
" ];\n"
"\n"
"1;\n";
return true;
}
bool PerlModGenerator::generateDoxyRules()
{
std::ofstream doxyRulesStream;
if (!createOutputFile(doxyRulesStream, pathDoxyRules))
return false;
bool perlmodLatex = Config_getBool(PERLMOD_LATEX);
QCString prefix = Config_getString(PERLMOD_MAKEVAR_PREFIX);
doxyRulesStream <<
prefix << "DOXY_EXEC_PATH = " << pathDoxyExec << "\n" <<
prefix << "DOXYFILE = " << pathDoxyfile << "\n" <<
prefix << "DOXYDOCS_PM = " << pathDoxyDocsPM << "\n" <<
prefix << "DOXYSTRUCTURE_PM = " << pathDoxyStructurePM << "\n" <<
prefix << "DOXYRULES = " << pathDoxyRules << "\n";
if (perlmodLatex)
doxyRulesStream <<
prefix << "DOXYLATEX_PL = " << pathDoxyLatexPL << "\n" <<
prefix << "DOXYLATEXSTRUCTURE_PL = " << pathDoxyLatexStructurePL << "\n" <<
prefix << "DOXYSTRUCTURE_TEX = " << pathDoxyStructureTex << "\n" <<
prefix << "DOXYDOCS_TEX = " << pathDoxyDocsTex << "\n" <<
prefix << "DOXYFORMAT_TEX = " << pathDoxyFormatTex << "\n" <<
prefix << "DOXYLATEX_TEX = " << pathDoxyLatexTex << "\n" <<
prefix << "DOXYLATEX_DVI = " << pathDoxyLatexDVI << "\n" <<
prefix << "DOXYLATEX_PDF = " << pathDoxyLatexPDF << "\n";
doxyRulesStream <<
"\n"
".PHONY: clean-perlmod\n"
"clean-perlmod::\n"
"\trm -f $(" << prefix << "DOXYSTRUCTURE_PM) \\\n"
"\t$(" << prefix << "DOXYDOCS_PM)";
if (perlmodLatex)
doxyRulesStream <<
" \\\n"
"\t$(" << prefix << "DOXYLATEX_PL) \\\n"
"\t$(" << prefix << "DOXYLATEXSTRUCTURE_PL) \\\n"
"\t$(" << prefix << "DOXYDOCS_TEX) \\\n"
"\t$(" << prefix << "DOXYSTRUCTURE_TEX) \\\n"
"\t$(" << prefix << "DOXYFORMAT_TEX) \\\n"
"\t$(" << prefix << "DOXYLATEX_TEX) \\\n"
"\t$(" << prefix << "DOXYLATEX_PDF) \\\n"
"\t$(" << prefix << "DOXYLATEX_DVI) \\\n"
"\t$(addprefix $(" << prefix << "DOXYLATEX_TEX:tex=),out aux log)";
doxyRulesStream << "\n\n";
doxyRulesStream <<
"$(" << prefix << "DOXYRULES) \\\n"
"$(" << prefix << "DOXYMAKEFILE) \\\n"
"$(" << prefix << "DOXYSTRUCTURE_PM) \\\n"
"$(" << prefix << "DOXYDOCS_PM)";
if (perlmodLatex) {
doxyRulesStream <<
" \\\n"
"$(" << prefix << "DOXYLATEX_PL) \\\n"
"$(" << prefix << "DOXYLATEXSTRUCTURE_PL) \\\n"
"$(" << prefix << "DOXYFORMAT_TEX) \\\n"
"$(" << prefix << "DOXYLATEX_TEX)";
}
doxyRulesStream <<
": \\\n"
"\t$(" << prefix << "DOXYFILE)\n"
"\tcd $(" << prefix << "DOXY_EXEC_PATH) ; doxygen \"$<\"\n";
if (perlmodLatex) {
doxyRulesStream <<
"\n"
"$(" << prefix << "DOXYDOCS_TEX): \\\n"
"$(" << prefix << "DOXYLATEX_PL) \\\n"
"$(" << prefix << "DOXYDOCS_PM)\n"
"\tperl -I\"$(<D)\" \"$<\" >\"$@\"\n"
"\n"
"$(" << prefix << "DOXYSTRUCTURE_TEX): \\\n"
"$(" << prefix << "DOXYLATEXSTRUCTURE_PL) \\\n"
"$(" << prefix << "DOXYSTRUCTURE_PM)\n"
"\tperl -I\"$(<D)\" \"$<\" >\"$@\"\n"
"\n"
"$(" << prefix << "DOXYLATEX_PDF) \\\n"
"$(" << prefix << "DOXYLATEX_DVI): \\\n"
"$(" << prefix << "DOXYLATEX_TEX) \\\n"
"$(" << prefix << "DOXYFORMAT_TEX) \\\n"
"$(" << prefix << "DOXYSTRUCTURE_TEX) \\\n"
"$(" << prefix << "DOXYDOCS_TEX)\n"
"\n"
"$(" << prefix << "DOXYLATEX_PDF): \\\n"
"$(" << prefix << "DOXYLATEX_TEX)\n"
"\tpdflatex -interaction=nonstopmode \"$<\"\n"
"\n"
"$(" << prefix << "DOXYLATEX_DVI): \\\n"
"$(" << prefix << "DOXYLATEX_TEX)\n"
"\tlatex -interaction=nonstopmode \"$<\"\n";
}
return true;
}
bool PerlModGenerator::generateMakefile()
{
std::ofstream makefileStream;
if (!createOutputFile(makefileStream, pathMakefile))
return false;
bool perlmodLatex = Config_getBool(PERLMOD_LATEX);
QCString prefix = Config_getString(PERLMOD_MAKEVAR_PREFIX);
makefileStream <<
".PHONY: default clean" << (perlmodLatex ? " pdf" : "") << "\n"
"default: " << (perlmodLatex ? "pdf" : "clean") << "\n"
"\n"
"include " << pathDoxyRules << "\n"
"\n"
"clean: clean-perlmod\n";
if (perlmodLatex) {
makefileStream <<
"pdf: $(" << prefix << "DOXYLATEX_PDF)\n"
"dvi: $(" << prefix << "DOXYLATEX_DVI)\n";
}
return true;
}
bool PerlModGenerator::generateDoxyLatexStructurePL()
{
std::ofstream doxyLatexStructurePLStream;
if (!createOutputFile(doxyLatexStructurePLStream, pathDoxyLatexStructurePL))
return false;
doxyLatexStructurePLStream <<
"use DoxyStructure;\n"
"\n"
"sub process($) {\n"
"\tmy $node = $_[0];\n"
"\tmy ($type, $name) = @$node[0, 1];\n"
"\tmy $command;\n"
"\tif ($type eq \"string\") { $command = \"String\" }\n"
"\telsif ($type eq \"doc\") { $command = \"Doc\" }\n"
"\telsif ($type eq \"hash\") {\n"
"\t\t$command = \"Hash\";\n"
"\t\tfor my $subnode (values %{$$node[2]}) {\n"
"\t\t\tprocess($subnode);\n"
"\t\t}\n"
"\t}\n"
"\telsif ($type eq \"list\") {\n"
"\t\t$command = \"List\";\n"
"\t\tprocess($$node[2]);\n"
"\t}\n"
"\tprint \"\\\\\" . $command . \"Node{\" . $name . \"}%\\n\";\n"
"}\n"
"\n"
"process($doxystructure);\n";
return true;
}
bool PerlModGenerator::generateDoxyLatexPL()
{
std::ofstream doxyLatexPLStream;
if (!createOutputFile(doxyLatexPLStream, pathDoxyLatexPL))
return false;
doxyLatexPLStream <<
"use DoxyStructure;\n"
"use DoxyDocs;\n"
"\n"
"sub latex_quote($) {\n"
"\tmy $text = $_[0];\n"
"\t$text =~ s/\\\\/\\\\textbackslash /g;\n"
"\t$text =~ s/\\|/\\\\textbar /g;\n"
"\t$text =~ s/</\\\\textless /g;\n"
"\t$text =~ s/>/\\\\textgreater /g;\n"
"\t$text =~ s/~/\\\\textasciitilde /g;\n"
"\t$text =~ s/\\^/\\\\textasciicircum /g;\n"
"\t$text =~ s/[\\$&%#_{}]/\\\\$&/g;\n"
"\tprint $text;\n"
"}\n"
"\n"
"sub generate_doc($) {\n"
"\tmy $doc = $_[0];\n"
"\tfor my $item (@$doc) {\n"
"\t\tmy $type = $$item{type};\n"
"\t\tif ($type eq \"text\") {\n"
"\t\t\tlatex_quote($$item{content});\n"
"\t\t} elsif ($type eq \"parbreak\") {\n"
"\t\t\tprint \"\\n\\n\";\n"
"\t\t} elsif ($type eq \"style\") {\n"
"\t\t\tmy $style = $$item{style};\n"
"\t\t\tif ($$item{enable} eq \"yes\") {\n"
"\t\t\t\tif ($style eq \"bold\") { print '\\bfseries'; }\n"
"\t\t\t\tif ($style eq \"italic\") { print '\\itshape'; }\n"
"\t\t\t\tif ($style eq \"code\") { print '\\ttfamily'; }\n"
"\t\t\t} else {\n"
"\t\t\t\tif ($style eq \"bold\") { print '\\mdseries'; }\n"
"\t\t\t\tif ($style eq \"italic\") { print '\\upshape'; }\n"
"\t\t\t\tif ($style eq \"code\") { print '\\rmfamily'; }\n"
"\t\t\t}\n"
"\t\t\tprint '{}';\n"
"\t\t} elsif ($type eq \"symbol\") {\n"
"\t\t\tmy $symbol = $$item{symbol};\n"
"\t\t\tif ($symbol eq \"copyright\") { print '\\copyright'; }\n"
"\t\t\telsif ($symbol eq \"szlig\") { print '\\ss'; }\n"
"\t\t\tprint '{}';\n"
"\t\t} elsif ($type eq \"accent\") {\n"
"\t\t\tmy ($accent) = $$item{accent};\n"
"\t\t\tif ($accent eq \"umlaut\") { print '\\\"'; }\n"
"\t\t\telsif ($accent eq \"acute\") { print '\\\\\\''; }\n"
"\t\t\telsif ($accent eq \"grave\") { print '\\`'; }\n"
"\t\t\telsif ($accent eq \"circ\") { print '\\^'; }\n"
"\t\t\telsif ($accent eq \"tilde\") { print '\\~'; }\n"
"\t\t\telsif ($accent eq \"cedilla\") { print '\\c'; }\n"
"\t\t\telsif ($accent eq \"ring\") { print '\\r'; }\n"
"\t\t\tprint \"{\" . $$item{letter} . \"}\"; \n"
"\t\t} elsif ($type eq \"list\") {\n"
"\t\t\tmy $env = ($$item{style} eq \"ordered\") ? \"enumerate\" : \"itemize\";\n"
"\t\t\tprint \"\\n\\\\begin{\" . $env .\"}\";\n"
"\t\t \tfor my $subitem (@{$$item{content}}) {\n"
"\t\t\t\tprint \"\\n\\\\item \";\n"
"\t\t\t\tgenerate_doc($subitem);\n"
"\t\t \t}\n"
"\t\t\tprint \"\\n\\\\end{\" . $env .\"}\";\n"
"\t\t} elsif ($type eq \"url\") {\n"
"\t\t\tlatex_quote($$item{content});\n"
"\t\t}\n"
"\t}\n"
"}\n"
"\n"
"sub generate($$) {\n"
"\tmy ($item, $node) = @_;\n"
"\tmy ($type, $name) = @$node[0, 1];\n"
"\tif ($type eq \"string\") {\n"
"\t\tprint \"\\\\\" . $name . \"{\";\n"
"\t\tlatex_quote($item);\n"
"\t\tprint \"}\";\n"
"\t} elsif ($type eq \"doc\") {\n"
"\t\tif (@$item) {\n"
"\t\t\tprint \"\\\\\" . $name . \"{\";\n"
"\t\t\tgenerate_doc($item);\n"
"\t\t\tprint \"}%\\n\";\n"
"\t\t} else {\n"
"#\t\t\tprint \"\\\\\" . $name . \"Empty%\\n\";\n"
"\t\t}\n"
"\t} elsif ($type eq \"hash\") {\n"
"\t\tmy ($key, $value);\n"
"\t\twhile (($key, $subnode) = each %{$$node[2]}) {\n"
"\t\t\tmy $subname = $$subnode[1];\n"
"\t\t\tprint \"\\\\Defcs{field\" . $subname . \"}{\";\n"
"\t\t\tif ($$item{$key}) {\n"
"\t\t\t\tgenerate($$item{$key}, $subnode);\n"
"\t\t\t} else {\n"
"#\t\t\t\t\tprint \"\\\\\" . $subname . \"Empty%\\n\";\n"
"\t\t\t}\n"
"\t\t\tprint \"}%\\n\";\n"
"\t\t}\n"
"\t\tprint \"\\\\\" . $name . \"%\\n\";\n"
"\t} elsif ($type eq \"list\") {\n"
"\t\tmy $index = 0;\n"
"\t\tif (@$item) {\n"
"\t\t\tprint \"\\\\\" . $name . \"{%\\n\";\n"
"\t\t\tfor my $subitem (@$item) {\n"
"\t\t\t\tif ($index) {\n"
"\t\t\t\t\tprint \"\\\\\" . $name . \"Sep%\\n\";\n"
"\t\t\t\t}\n"
"\t\t\t\tgenerate($subitem, $$node[2]);\n"
"\t\t\t\t$index++;\n"
"\t\t\t}\n"
"\t\t\tprint \"}%\\n\";\n"
"\t\t} else {\n"
"#\t\t\tprint \"\\\\\" . $name . \"Empty%\\n\";\n"
"\t\t}\n"
"\t}\n"
"}\n"
"\n"
"generate($doxydocs, $doxystructure);\n";
return true;
}
bool PerlModGenerator::generateDoxyFormatTex()
{
std::ofstream doxyFormatTexStream;
if (!createOutputFile(doxyFormatTexStream, pathDoxyFormatTex))
return false;
doxyFormatTexStream <<
"\\def\\Defcs#1{\\long\\expandafter\\def\\csname#1\\endcsname}\n"
"\\Defcs{Empty}{}\n"
"\\def\\IfEmpty#1{\\expandafter\\ifx\\csname#1\\endcsname\\Empty}\n"
"\n"
"\\def\\StringNode#1{\\Defcs{#1}##1{##1}}\n"
"\\def\\DocNode#1{\\Defcs{#1}##1{##1}}\n"
"\\def\\ListNode#1{\\Defcs{#1}##1{##1}\\Defcs{#1Sep}{}}\n"
"\\def\\HashNode#1{\\Defcs{#1}{}}\n"
"\n"
"\\input{" << pathDoxyStructureTex << "}\n"
"\n"
"\\newbox\\BoxA\n"
"\\dimendef\\DimenA=151\\relax\n"
"\\dimendef\\DimenB=152\\relax\n"
"\\countdef\\ZoneDepth=151\\relax\n"
"\n"
"\\def\\Cs#1{\\csname#1\\endcsname}\n"
"\\def\\Letcs#1{\\expandafter\\let\\csname#1\\endcsname}\n"
"\\def\\Heading#1{\\vskip 4mm\\relax\\textbf{#1}}\n"
"\\def\\See#1{\\begin{flushleft}\\Heading{See also: }#1\\end{flushleft}}\n"
"\n"
"\\def\\Frame#1{\\vskip 3mm\\relax\\fbox{ \\vbox{\\hsize0.95\\hsize\\vskip 1mm\\relax\n"
"\\raggedright#1\\vskip 0.5mm\\relax} }}\n"
"\n"
"\\def\\Zone#1#2#3{%\n"
"\\Defcs{Test#1}{#2}%\n"
"\\Defcs{Emit#1}{#3}%\n"
"\\Defcs{#1}{%\n"
"\\advance\\ZoneDepth1\\relax\n"
"\\Letcs{Mode\\number\\ZoneDepth}0\\relax\n"
"\\Letcs{Present\\number\\ZoneDepth}0\\relax\n"
"\\Cs{Test#1}\n"
"\\expandafter\\if\\Cs{Present\\number\\ZoneDepth}1%\n"
"\\advance\\ZoneDepth-1\\relax\n"
"\\Letcs{Present\\number\\ZoneDepth}1\\relax\n"
"\\expandafter\\if\\Cs{Mode\\number\\ZoneDepth}1%\n"
"\\advance\\ZoneDepth1\\relax\n"
"\\Letcs{Mode\\number\\ZoneDepth}1\\relax\n"
"\\Cs{Emit#1}\n"
"\\advance\\ZoneDepth-1\\relax\\fi\n"
"\\advance\\ZoneDepth1\\relax\\fi\n"
"\\advance\\ZoneDepth-1\\relax}}\n"
"\n"
"\\def\\Member#1#2{%\n"
"\\Defcs{Test#1}{\\Cs{field#1Detailed}\n"
"\\IfEmpty{field#1DetailedDoc}\\else\\Letcs{Present#1}1\\fi}\n"
"\\Defcs{#1}{\\Letcs{Present#1}0\\relax\n"
"\\Cs{Test#1}\\if1\\Cs{Present#1}\\Letcs{Present\\number\\ZoneDepth}1\\relax\n"
"\\if1\\Cs{Mode\\number\\ZoneDepth}#2\\fi\\fi}}\n"
"\n"
"\\def\\TypedefMemberList#1#2{%\n"
"\\Defcs{#1DetailedDoc}##1{\\vskip 5.5mm\\relax##1}%\n"
"\\Defcs{#1Name}##1{\\textbf{##1}}%\n"
"\\Defcs{#1See}##1{\\See{##1}}%\n"
"%\n"
"\\Zone{#1s}{\\Cs{field#1List}}{\\subsubsection{#2}\\Cs{field#1List}}%\n"
"\\Member{#1}{\\Frame{typedef \\Cs{field#1Type} \\Cs{field#1Name}}%\n"
"\\Cs{field#1DetailedDoc}\\Cs{field#1See}\\vskip 5mm\\relax}}%\n"
"\n"
"\\def\\VariableMemberList#1#2{%\n"
"\\Defcs{#1DetailedDoc}##1{\\vskip 5.5mm\\relax##1}%\n"
"\\Defcs{#1Name}##1{\\textbf{##1}}%\n"
"\\Defcs{#1See}##1{\\See{##1}}%\n"
"%\n"
"\\Zone{#1s}{\\Cs{field#1List}}{\\subsubsection{#2}\\Cs{field#1List}}%\n"
"\\Member{#1}{\\Frame{\\Cs{field#1Type}{} \\Cs{field#1Name}}%\n"
"\\Cs{field#1DetailedDoc}\\Cs{field#1See}\\vskip 5mm\\relax}}%\n"
"\n"
"\\def\\FunctionMemberList#1#2{%\n"
"\\Defcs{#1PDParamName}##1{\\textit{##1}}%\n"
"\\Defcs{#1PDParam}{\\Cs{field#1PDParamName}}%\n"
"\\Defcs{#1PDParamsSep}{, }%\n"
"\\Defcs{#1PDBlocksSep}{\\vskip 2mm\\relax}%\n"
"%\n"
"\\Defcs{#1PDBlocks}##1{%\n"
"\\Heading{Parameters:}\\vskip 1.5mm\\relax\n"
"\\DimenA0pt\\relax\n"
"\\Defcs{#1PDBlock}{\\setbox\\BoxA\\hbox{\\Cs{field#1PDParams}}%\n"
"\\ifdim\\DimenA<\\wd\\BoxA\\DimenA\\wd\\BoxA\\fi}%\n"
"##1%\n"
"\\advance\\DimenA3mm\\relax\n"
"\\DimenB\\hsize\\advance\\DimenB-\\DimenA\\relax\n"
"\\Defcs{#1PDBlock}{\\hbox to\\hsize{\\vtop{\\hsize\\DimenA\\relax\n"
"\\Cs{field#1PDParams}}\\hfill\n"
"\\vtop{\\hsize\\DimenB\\relax\\Cs{field#1PDDoc}}}}%\n"
"##1}\n"
"\n"
"\\Defcs{#1ParamName}##1{\\textit{##1}}\n"
"\\Defcs{#1Param}{\\Cs{field#1ParamType}{} \\Cs{field#1ParamName}}\n"
"\\Defcs{#1ParamsSep}{, }\n"
"\n"
"\\Defcs{#1Name}##1{\\textbf{##1}}\n"
"\\Defcs{#1See}##1{\\See{##1}}\n"
"\\Defcs{#1Return}##1{\\Heading{Returns: }##1}\n"
"\\Defcs{field#1Title}{\\Frame{\\Cs{field#1Type}{} \\Cs{field#1Name}(\\Cs{field#1Params})}}%\n"
"%\n"
"\\Zone{#1s}{\\Cs{field#1List}}{\\subsubsection{#2}\\Cs{field#1List}}%\n"
"\\Member{#1}{%\n"
"\\Cs{field#1Title}\\vskip 6mm\\relax\\Cs{field#1DetailedDoc}\n"
"\\Cs{field#1Return}\\Cs{field#1PDBlocks}\\Cs{field#1See}\\vskip 5mm\\relax}}\n"
"\n"
"\\def\\FileDetailed{\\fieldFileDetailedDoc\\par}\n"
"\\def\\ClassDetailed{\\fieldClassDetailedDoc\\par}\n"
"\n"
"\\def\\FileSubzones{\\fieldFileTypedefs\\fieldFileVariables\\fieldFileFunctions}\n"
"\n"
"\\def\\ClassSubzones{%\n"
"\\fieldClassPublicTypedefs\\fieldClassPublicMembers\\fieldClassPublicMethods\n"
"\\fieldClassProtectedTypedefs\\fieldClassProtectedMembers\\fieldClassProtectedMethods\n"
"\\fieldClassPrivateTypedefs\\fieldClassPrivateMembers\\fieldClassPrivateMethods}\n"
"\n"
"\\Member{Page}{\\subsection{\\fieldPageName}\\fieldPageDetailedDoc}\n"
"\n"
"\\TypedefMemberList{FileTypedef}{Typedefs}\n"
"\\VariableMemberList{FileVariable}{Variables}\n"
"\\FunctionMemberList{FileFunction}{Functions}\n"
"\\Zone{File}{\\FileSubzones}{\\subsection{\\fieldFileName}\\fieldFileDetailed\\FileSubzones}\n"
"\n"
"\\TypedefMemberList{ClassPublicTypedef}{Public Typedefs}\n"
"\\TypedefMemberList{ClassProtectedTypedef}{Protected Typedefs}\n"
"\\TypedefMemberList{ClassPrivateTypedef}{Private Typedefs}\n"
"\\VariableMemberList{ClassPublicMember}{Public Members}\n"
"\\VariableMemberList{ClassProtectedMember}{Protected Members}\n"
"\\VariableMemberList{ClassPrivateMember}{Private Members}\n"
"\\FunctionMemberList{ClassPublicMethod}{Public Methods}\n"
"\\FunctionMemberList{ClassProtectedMethod}{Protected Methods}\n"
"\\FunctionMemberList{ClassPrivateMethod}{Private Methods}\n"
"\\Zone{Class}{\\ClassSubzones}{\\subsection{\\fieldClassName}\\fieldClassDetailed\\ClassSubzones}\n"
"\n"
"\\Zone{AllPages}{\\fieldPages}{\\section{Pages}\\fieldPages}\n"
"\\Zone{AllFiles}{\\fieldFiles}{\\section{Files}\\fieldFiles}\n"
"\\Zone{AllClasses}{\\fieldClasses}{\\section{Classes}\\fieldClasses}\n"
"\n"
"\\newlength{\\oldparskip}\n"
"\\newlength{\\oldparindent}\n"
"\\newlength{\\oldfboxrule}\n"
"\n"
"\\ZoneDepth0\\relax\n"
"\\Letcs{Mode0}1\\relax\n"
"\n"
"\\def\\EmitDoxyDocs{%\n"
"\\setlength{\\oldparskip}{\\parskip}\n"
"\\setlength{\\oldparindent}{\\parindent}\n"
"\\setlength{\\oldfboxrule}{\\fboxrule}\n"
"\\setlength{\\parskip}{0cm}\n"
"\\setlength{\\parindent}{0cm}\n"
"\\setlength{\\fboxrule}{1pt}\n"
"\\AllPages\\AllFiles\\AllClasses\n"
"\\setlength{\\parskip}{\\oldparskip}\n"
"\\setlength{\\parindent}{\\oldparindent}\n"
"\\setlength{\\fboxrule}{\\oldfboxrule}}\n";
return true;
}
bool PerlModGenerator::generateDoxyLatexTex()
{
std::ofstream doxyLatexTexStream;
if (!createOutputFile(doxyLatexTexStream, pathDoxyLatexTex))
return false;
doxyLatexTexStream <<
"\\documentclass[a4paper,12pt]{article}\n"
"\\usepackage[latin1]{inputenc}\n"
"\\usepackage[none]{hyphenat}\n"
"\\usepackage[T1]{fontenc}\n"
"\\usepackage{hyperref}\n"
"\\usepackage{times}\n"
"\n"
"\\input{doxyformat}\n"
"\n"
"\\begin{document}\n"
"\\input{" << pathDoxyDocsTex << "}\n"
"\\sloppy\n"
"\\EmitDoxyDocs\n"
"\\end{document}\n";
return true;
}
void PerlModGenerator::generate()
{
// + classes
// + namespaces
// + files
// - packages
// + groups
// + related pages
// - examples
Dir perlModDir;
if (!createOutputDir(perlModDir))
return;
bool perlmodLatex = Config_getBool(PERLMOD_LATEX);
QCString perlModAbsPath = perlModDir.absPath();
pathDoxyDocsPM = perlModAbsPath + "/DoxyDocs.pm";
pathDoxyStructurePM = perlModAbsPath + "/DoxyStructure.pm";
pathMakefile = perlModAbsPath + "/Makefile";
pathDoxyRules = perlModAbsPath + "/doxyrules.make";
if (perlmodLatex) {
pathDoxyStructureTex = perlModAbsPath + "/doxystructure.tex";
pathDoxyFormatTex = perlModAbsPath + "/doxyformat.tex";
pathDoxyLatexTex = perlModAbsPath + "/doxylatex.tex";
pathDoxyLatexDVI = perlModAbsPath + "/doxylatex.dvi";
pathDoxyLatexPDF = perlModAbsPath + "/doxylatex.pdf";
pathDoxyDocsTex = perlModAbsPath + "/doxydocs.tex";
pathDoxyLatexPL = perlModAbsPath + "/doxylatex.pl";
pathDoxyLatexStructurePL = perlModAbsPath + "/doxylatex-structure.pl";
}
if (!(generatePerlModOutput()
&& generateDoxyStructurePM()
&& generateMakefile()
&& generateDoxyRules()))
return;
if (perlmodLatex) {
if (!(generateDoxyLatexStructurePL()
&& generateDoxyLatexPL()
&& generateDoxyLatexTex()
&& generateDoxyFormatTex()))
return;
}
}
void generatePerlMod()
{
PerlModGenerator pmg(Config_getBool(PERLMOD_PRETTY));
pmg.generate();
}
// Local Variables:
// c-basic-offset: 2
// End:
/* This elisp function for XEmacs makes Control-Z transform
the text in the region into a valid C string.
(global-set-key '(control z) (lambda () (interactive)
(save-excursion
(if (< (mark) (point)) (exchange-point-and-mark))
(let ((start (point)) (replacers
'(("\\\\" "\\\\\\\\")
("\"" "\\\\\"")
("\t" "\\\\t")
("^.*$" "\"\\&\\\\n\""))))
(while replacers
(while (re-search-forward (caar replacers) (mark) t)
(replace-match (cadar replacers) t))
(goto-char start)
(setq replacers (cdr replacers)))))))
*/
| 87,416
|
C++
|
.cpp
| 2,684
| 28.640089
| 130
| 0.637095
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,421
|
dotgraph.cpp
|
doxygen_doxygen/src/dotgraph.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include <mutex>
#include <regex>
#include "config.h"
#include "doxygen.h"
#include "indexlist.h"
#include "md5.h"
#include "message.h"
#include "util.h"
#include "dot.h"
#include "dotrunner.h"
#include "dotgraph.h"
#include "dotnode.h"
#include "dotfilepatcher.h"
#include "fileinfo.h"
#include "portable.h"
#define MAP_CMD "cmapx"
//QCString DotGraph::DOT_FONTNAME; // will be initialized in initDot
//int DotGraph::DOT_FONTSIZE; // will be initialized in initDot
/*! Checks if a file "baseName".md5 exists. If so the contents
* are compared with \a md5. If equal FALSE is returned.
* The .md5 is created or updated after successful creation of the output file.
*/
static bool sameMd5Signature(const QCString &baseName,
const QCString &md5)
{
bool same = false;
char md5stored[33];
md5stored[0]=0;
std::ifstream f = Portable::openInputStream(baseName+".md5",true);
if (f.is_open())
{
// read checksum
f.read(md5stored,32);
md5stored[32]='\0';
// compare checksum
if (!f.fail() && md5==md5stored)
{
same = true;
}
//printf("sameSignature(%s,%s==%s)=%d\n",qPrint(baseName),md5stored,qPrint(md5),same);
}
else
{
//printf("sameSignature(%s) not found\n",qPrint(baseName));
}
return same;
}
static bool deliverablesPresent(const QCString &file1,const QCString &file2)
{
bool file1Ok = true;
bool file2Ok = true;
if (!file1.isEmpty())
{
FileInfo fi(file1.str());
file1Ok = (fi.exists() && fi.size()>0);
}
if (!file2.isEmpty())
{
FileInfo fi(file2.str());
file2Ok = (fi.exists() && fi.size()>0);
}
return file1Ok && file2Ok;
}
static bool insertMapFile(TextStream &out,const QCString &mapFile,
const QCString &relPath,const QCString &mapLabel)
{
FileInfo fi(mapFile.str());
if (fi.exists() && fi.size()>0) // reuse existing map file
{
TextStream t;
DotFilePatcher::convertMapFile(t,mapFile,relPath,false);
if (!t.empty())
{
out << "<map name=\"" << mapLabel << "\" id=\"" << mapLabel << "\">\n";
out << t.str();
out << "</map>\n";
}
return true;
}
return false; // no map file yet, need to generate it
}
//--------------------------------------------------------------------
QCString DotGraph::imgName() const
{
return m_baseName + ((m_graphFormat == GraphOutputFormat::BITMAP) ?
("." + getDotImageExtension()) : (Config_getBool(USE_PDFLATEX) ? ".pdf" : ".eps"));
}
std::mutex g_dotIndexListMutex;
QCString DotGraph::writeGraph(
TextStream& t, // output stream for the code file (html, ...)
GraphOutputFormat gf, // bitmap(png/svg) or ps(eps/pdf)
EmbeddedOutputFormat ef, // html, latex, ...
const QCString &path, // output folder
const QCString &fileName, // name of the code file (for code patcher)
const QCString &relPath, // output folder relative to code file
bool generateImageMap, // in case of bitmap, shall there be code generated?
int graphId) // number of this graph in the current code, used in svg code
{
m_graphFormat = gf;
m_textFormat = ef;
m_dir = Dir(path.str());
m_fileName = fileName;
m_relPath = relPath;
m_generateImageMap = generateImageMap;
m_graphId = graphId;
m_absPath = m_dir.absPath() + "/";
m_baseName = getBaseName();
computeTheGraph();
m_regenerate = prepareDotFile();
if (!m_doNotAddImageToIndex)
{
std::lock_guard<std::mutex> lock(g_dotIndexListMutex);
Doxygen::indexList->addImageFile(imgName());
}
generateCode(t);
return m_baseName;
}
bool DotGraph::prepareDotFile()
{
if (!m_dir.exists())
{
term("Output dir %s does not exist!\n", m_dir.path().c_str());
}
char sigStr[33];
uint8_t md5_sig[16];
// calculate md5
MD5Buffer(m_theGraph.data(), static_cast<unsigned int>(m_theGraph.length()), md5_sig);
// convert result to a string
MD5SigToString(md5_sig, sigStr);
// already queued files are processed again in case the output format has changed
if (sameMd5Signature(absBaseName(), sigStr) &&
deliverablesPresent(absImgName(),
m_graphFormat == GraphOutputFormat::BITMAP && m_generateImageMap ? absMapName() : QCString()
)
)
{
// all needed files are there
return FALSE;
}
// need to rebuild the image
// write .dot file because image was new or has changed
std::ofstream f = Portable::openOutputStream(absDotName());
if (!f.is_open())
{
err("Could not open file %s for writing\n",qPrint(absDotName()));
return TRUE;
}
f << m_theGraph;
f.close();
if (m_graphFormat == GraphOutputFormat::BITMAP)
{
// run dot to create a bitmap image
DotRunner * dotRun = DotManager::instance()->createRunner(absDotName(), sigStr);
dotRun->addJob(Config_getEnumAsString(DOT_IMAGE_FORMAT), absImgName(), absDotName(), 1);
if (m_generateImageMap) dotRun->addJob(MAP_CMD, absMapName(), absDotName(), 1);
}
else if (m_graphFormat == GraphOutputFormat::EPS)
{
// run dot to create a .eps image
DotRunner *dotRun = DotManager::instance()->createRunner(absDotName(), sigStr);
if (Config_getBool(USE_PDFLATEX))
{
dotRun->addJob("pdf",absImgName(),absDotName(),1);
}
else
{
dotRun->addJob("ps",absImgName(),absDotName(),1);
}
}
return TRUE;
}
void DotGraph::generateCode(TextStream &t)
{
QCString imgExt = getDotImageExtension();
if (m_graphFormat==GraphOutputFormat::BITMAP && m_textFormat==EmbeddedOutputFormat::DocBook)
{
t << "<para>\n";
t << " <informalfigure>\n";
t << " <mediaobject>\n";
t << " <imageobject>\n";
t << " <imagedata";
t << " width=\"50%\" align=\"center\" valign=\"middle\" scalefit=\"0\" fileref=\"" << m_relPath << m_baseName << "." << imgExt << "\">";
t << "</imagedata>\n";
t << " </imageobject>\n";
t << " </mediaobject>\n";
t << " </informalfigure>\n";
t << "</para>\n";
}
else if (m_graphFormat==GraphOutputFormat::BITMAP && m_generateImageMap) // produce HTML to include the image
{
if (imgExt=="svg") // add link to SVG file without map file
{
if (!m_noDivTag) t << "<div class=\"center\">";
if (m_regenerate || !DotFilePatcher::writeSVGFigureLink(t,m_relPath,m_baseName,absImgName())) // need to patch the links in the generated SVG file
{
if (m_regenerate)
{
DotManager::instance()->
createFilePatcher(absImgName())->
addSVGConversion(m_relPath,FALSE,QCString(),m_zoomable,m_graphId);
}
int mapId = DotManager::instance()->
createFilePatcher(m_fileName)->
addSVGObject(m_baseName,absImgName(),m_relPath);
t << "<!-- " << "SVG " << mapId << " -->";
}
if (!m_noDivTag) t << "</div>\n";
}
else // add link to bitmap file with image map
{
if (!m_noDivTag) t << "<div class=\"center\">";
t << "<img src=\"" << relImgName() << "\" border=\"0\" usemap=\"#" << correctId(getMapLabel()) << "\" alt=\"" << getImgAltText() << "\"/>";
if (!m_noDivTag) t << "</div>";
t << "\n";
if (m_regenerate || !insertMapFile(t, absMapName(), m_relPath, correctId(getMapLabel())))
{
int mapId = DotManager::instance()->
createFilePatcher(m_fileName)->
addMap(absMapName(), m_relPath, m_urlOnly, QCString(), getMapLabel());
t << "<!-- MAP " << mapId << " -->\n";
}
}
}
else if (m_graphFormat==GraphOutputFormat::EPS) // produce tex to include the .eps image
{
if (m_regenerate || !DotFilePatcher::writeVecGfxFigure(t,m_baseName,absBaseName()))
{
int figId = DotManager::instance()->
createFilePatcher(m_fileName)->
addFigure(m_baseName,absBaseName(),FALSE /*TRUE*/);
t << "\n% FIG " << figId << "\n";
}
}
}
void DotGraph::writeGraphHeader(TextStream &t,const QCString &title)
{
t << "digraph ";
if (title.isEmpty())
{
t << "\"Dot Graph\"";
}
else
{
t << "\"" << convertToXML(title) << "\"";
}
t << "\n{\n";
if (Config_getBool(INTERACTIVE_SVG)) // insert a comment to force regeneration when this
// option is toggled
{
t << " // INTERACTIVE_SVG=YES\n";
}
t << " // LATEX_PDF_SIZE\n"; // write placeholder for LaTeX PDF bounding box size replacement
t << " bgcolor=\"transparent\";\n";
QCString c = Config_getString(DOT_COMMON_ATTR);
if (!c.isEmpty()) c += ",";
t << " edge [" << c << Config_getString(DOT_EDGE_ATTR) << "];\n";
t << " node [" << c << Config_getString(DOT_NODE_ATTR) << "];\n";
}
void DotGraph::writeGraphFooter(TextStream &t)
{
t << "}\n";
}
void DotGraph::computeGraph(DotNode *root,
GraphType gt,
GraphOutputFormat format,
const QCString &rank, // either "LR", "RL", or ""
bool renderParents,
bool backArrows,
const QCString &title,
QCString &graphStr)
{
//printf("computeMd5Signature\n");
TextStream md5stream;
writeGraphHeader(md5stream,title);
if (!rank.isEmpty())
{
md5stream << " rankdir=\"" << rank << "\";\n";
}
root->clearWriteFlag();
root->write(md5stream, gt, format, gt!=GraphType::CallGraph && gt!=GraphType::Dependency, TRUE, backArrows);
if (renderParents)
{
for (const auto &pn : root->parents())
{
if (pn->isVisible())
{
const auto &children = pn->children();
auto child_it = std::find(children.begin(),children.end(),root);
size_t index = child_it - children.begin();
root->writeArrow(md5stream, // stream
gt, // graph type
format, // output format
pn, // child node
&pn->edgeInfo()[index], // edge info
FALSE, // topDown?
backArrows // point back?
);
}
pn->write(md5stream, // stream
gt, // graph type
format, // output format
TRUE, // topDown?
FALSE, // toChildren?
backArrows // backward pointing arrows?
);
}
}
writeGraphFooter(md5stream);
graphStr=md5stream.str();
}
| 11,464
|
C++
|
.cpp
| 324
| 29.873457
| 152
| 0.581871
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,422
|
dotincldepgraph.cpp
|
doxygen_doxygen/src/dotincldepgraph.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include "dotincldepgraph.h"
#include "dotnode.h"
#include "util.h"
#include "config.h"
#include "textstream.h"
void DotInclDepGraph::buildGraph(DotNode *n,const FileDef *fd,int distance)
{
const IncludeInfoList &includeFiles = m_inverse ? fd->includedByFileList() : fd->includeFileList();
for (const auto &ii : includeFiles)
{
const FileDef *bfd = ii.fileDef;
QCString in = ii.includeName;
//printf(">>>> in='%s' bfd=%p\n",qPrint(ii->includeName),bfd);
bool doc=TRUE,src=FALSE;
if (bfd)
{
in = bfd->absFilePath();
doc = bfd->isLinkable() && !bfd->isHidden();
src = bfd->generateSourceFile();
}
if (doc || src || !Config_getBool(HIDE_UNDOC_RELATIONS))
{
QCString url="";
if (bfd) url=bfd->getOutputFileBase();
if (!doc && src)
{
url=bfd->getSourceFileBase();
}
auto it = m_usedNodes.find(in.str());
if (it!=m_usedNodes.end()) // file is already a node in the graph
{
DotNode *bn = it->second;
n->addChild(bn,EdgeInfo::Blue,EdgeInfo::Solid);
bn->addParent(n);
bn->setDistance(distance);
}
else
{
QCString tmp_url;
QCString tooltip;
if (bfd)
{
tmp_url=doc || src ? bfd->getReference()+"$"+url : QCString();
tooltip = bfd->briefDescriptionAsTooltip();
}
DotNode *bn = new DotNode(this,
ii.includeName, // label
tooltip, // tip
tmp_url, // url
FALSE, // rootNode
nullptr); // cd
n->addChild(bn,EdgeInfo::Blue,EdgeInfo::Solid);
bn->addParent(n);
m_usedNodes.emplace(in.str(),bn);
bn->setDistance(distance);
if (bfd) buildGraph(bn,bfd,distance+1);
}
}
}
}
void DotInclDepGraph::determineVisibleNodes(DotNodeDeque &queue, int &maxNodes)
{
while (!queue.empty() && maxNodes>0)
{
DotNode *n = queue.front();
queue.pop_front();
if (!n->isVisible() && n->distance()<=Config_getInt(MAX_DOT_GRAPH_DEPTH)) // not yet processed
{
n->markAsVisible();
maxNodes--;
// add direct children
for (const auto &dn : n->children())
{
queue.push_back(dn);
}
}
}
}
void DotInclDepGraph::determineTruncatedNodes(DotNodeDeque &queue)
{
while (!queue.empty())
{
DotNode *n = queue.front();
queue.pop_front();
if (n->isVisible() && n->isTruncated()==DotNode::Unknown)
{
bool truncated = FALSE;
for (const auto &dn : n->children())
{
if (!dn->isVisible())
{
truncated = TRUE;
}
else
{
queue.push_back(dn);
}
}
n->markAsTruncated(truncated);
}
}
}
DotInclDepGraph::DotInclDepGraph(const FileDef *fd,bool inverse)
{
m_inverse = inverse;
ASSERT(fd!=nullptr);
m_inclDepFileName = fd->includeDependencyGraphFileName();
m_inclByDepFileName = fd->includedByDependencyGraphFileName();
QCString tmp_url=fd->getReference()+"$"+fd->getOutputFileBase();
QCString tooltip = fd->briefDescriptionAsTooltip();
m_startNode = new DotNode(this,
fd->docName(),
tooltip,
tmp_url,
TRUE); // root node
m_startNode->setDistance(0);
m_usedNodes.emplace(fd->absFilePath().str(),m_startNode);
buildGraph(m_startNode,fd,1);
int maxNodes = Config_getInt(DOT_GRAPH_MAX_NODES);
DotNodeDeque openNodeQueue;
openNodeQueue.push_back(m_startNode);
determineVisibleNodes(openNodeQueue,maxNodes);
openNodeQueue.clear();
openNodeQueue.push_back(m_startNode);
determineTruncatedNodes(openNodeQueue);
}
DotInclDepGraph::~DotInclDepGraph()
{
DotNode::deleteNodes(m_startNode);
}
QCString DotInclDepGraph::getBaseName() const
{
if (m_inverse)
{
return m_inclByDepFileName;
}
else
{
return m_inclDepFileName;
}
}
void DotInclDepGraph::computeTheGraph()
{
computeGraph(m_startNode, GraphType::Dependency, m_graphFormat, "", FALSE,
m_inverse, m_startNode->label(), m_theGraph);
}
QCString DotInclDepGraph::getMapLabel() const
{
if (m_inverse)
{
return escapeCharsInString(m_startNode->label(),FALSE) + "dep";
}
else
{
return escapeCharsInString(m_startNode->label(),FALSE);
}
}
QCString DotInclDepGraph::writeGraph(TextStream &out,
GraphOutputFormat graphFormat,
EmbeddedOutputFormat textFormat,
const QCString &path,
const QCString &fileName,
const QCString &relPath,
bool generateImageMap,
int graphId)
{
return DotGraph::writeGraph(out, graphFormat, textFormat, path, fileName, relPath, generateImageMap, graphId);
}
bool DotInclDepGraph::isTrivial() const
{
return m_startNode->children().empty();
}
bool DotInclDepGraph::isTooBig() const
{
return numNodes()>=Config_getInt(DOT_GRAPH_MAX_NODES);
}
int DotInclDepGraph::numNodes() const
{
return static_cast<int>(m_startNode->children().size());
}
void DotInclDepGraph::writeXML(TextStream &t)
{
for (const auto &[name,node] : m_usedNodes)
{
node->writeXML(t,FALSE);
}
}
void DotInclDepGraph::writeDocbook(TextStream &t)
{
for (const auto &[name,node] : m_usedNodes)
{
node->writeDocbook(t,FALSE);
}
}
| 6,290
|
C++
|
.cpp
| 208
| 23.884615
| 112
| 0.609233
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,423
|
classlist.cpp
|
doxygen_doxygen/src/classlist.cpp
|
/******************************************************************************
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include "classlist.h"
#include "config.h"
#include "util.h"
#include "outputlist.h"
#include "language.h"
#include "doxygen.h"
#include "vhdldocgen.h"
#include "defargs.h"
#include "arguments.h"
#include "groupdef.h"
bool ClassLinkedRefMap::declVisible(const ClassDef::CompoundType *filter) const
{
bool hideUndocClasses = Config_getBool(HIDE_UNDOC_CLASSES);
bool extractLocalClasses = Config_getBool(EXTRACT_LOCAL_CLASSES);
for (const auto &cd : *this)
{
if (!cd->isAnonymous() &&
(filter==nullptr || *filter==cd->compoundType())
)
{
bool isLink = cd->isLinkable();
if (isLink ||
(!hideUndocClasses &&
(!cd->isLocal() || extractLocalClasses)
)
)
{
return true;
}
}
}
return false;
}
void ClassLinkedRefMap::writeDeclaration(OutputList &ol,const ClassDef::CompoundType *filter,
const QCString &header,bool localNames) const
{
bool extractPrivate = Config_getBool(EXTRACT_PRIVATE);
bool found=FALSE;
for (const auto &cd : *this)
{
//printf(" ClassLinkedRefMap::writeDeclaration for %s\n",cd->name().data());
if (!cd->isAnonymous() &&
!cd->isExtension() &&
(cd->protection()!=Protection::Private || extractPrivate) &&
(filter==nullptr || *filter==cd->compoundType())
)
{
//printf("writeDeclarationLink()\n");
cd->writeDeclarationLink(ol,found,header,localNames);
}
}
if (found) ol.endMemberList();
}
void ClassLinkedRefMap::writeDocumentation(OutputList &ol,const Definition * container) const
{
bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
bool inlineGroupedClasses = Config_getBool(INLINE_GROUPED_CLASSES);
bool inlineSimpleClasses = Config_getBool(INLINE_SIMPLE_STRUCTS);
if (!inlineGroupedClasses && !inlineSimpleClasses) return;
bool found=FALSE;
for (const auto &cd : *this)
{
//printf("%s:writeDocumentation() %p linkable=%d embedded=%d container=%p partOfGroups=%zu\n",
// cd->name().data(),cd->getOuterScope(),cd->isLinkableInProject(),cd->isEmbeddedInOuterScope(),
// container,cd->partOfGroups()->size());
if (!cd->isAnonymous() &&
cd->isLinkableInProject() &&
cd->isEmbeddedInOuterScope() &&
!cd->isAlias() &&
(container==nullptr || cd->partOfGroups().empty()) // if container==nullptr -> show as part of the group docs, otherwise only show if not part of a group
)
{
//printf(" showing class %s\n",cd->name().data());
if (!found)
{
ol.writeRuler();
ol.startGroupHeader();
ol.parseText(fortranOpt?theTranslator->trTypeDocumentation():
theTranslator->trClassDocumentation());
ol.endGroupHeader();
found=TRUE;
}
cd->writeInlineDocumentation(ol);
}
}
}
| 3,529
|
C++
|
.cpp
| 102
| 29.617647
| 161
| 0.656131
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,424
|
rtfdocvisitor.cpp
|
doxygen_doxygen/src/rtfdocvisitor.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2022 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.
*
*/
#include <algorithm>
#include "rtfdocvisitor.h"
#include "docparser.h"
#include "language.h"
#include "doxygen.h"
#include "outputgen.h"
#include "dot.h"
#include "msc.h"
#include "util.h"
#include "rtfstyle.h"
#include "rtfgen.h"
#include "message.h"
#include "parserintf.h"
#include "msc.h"
#include "dia.h"
#include "filedef.h"
#include "config.h"
#include "htmlentity.h"
#include "emoji.h"
#include "plantuml.h"
#include "fileinfo.h"
#include "portable.h"
#include "codefragment.h"
//#define DBG_RTF(x) m_t << x
#define DBG_RTF(x) do {} while(0)
static QCString align(const DocHtmlCell &cell)
{
for (const auto &attr : cell.attribs())
{
if (attr.name.lower()=="align")
{
if (attr.value.lower()=="center") return "\\qc ";
else if (attr.value.lower()=="right") return "\\qr ";
else return "";
}
}
return "";
}
static QCString makeBaseName(const QCString &name)
{
QCString baseName = name;
int i = baseName.findRev('/');
if (i!=-1)
{
baseName=baseName.mid(i+1);
}
return baseName;
}
RTFDocVisitor::RTFDocVisitor(TextStream &t,OutputCodeList &ci,
const QCString &langExt, int hierarchyLevel)
: m_t(t), m_ci(ci), m_langExt(langExt), m_hierarchyLevel(hierarchyLevel)
{
}
QCString RTFDocVisitor::getStyle(const QCString &name)
{
QCString n = name + QCString().setNum(indentLevel());
StyleData &sd = rtf_Style[n.str()];
return sd.reference();
}
QCString RTFDocVisitor::getListTable(const int id)
{
for (int i=0 ; rtf_Table_Default[i].definition ; i++ )
{
if ((id == rtf_Table_Default[i].id) && (m_indentLevel == rtf_Table_Default[i].lvl))
{
return rtf_Table_Default[i].place;
}
}
ASSERT(0);
return "";
}
int RTFDocVisitor::indentLevel() const
{
return std::min(m_indentLevel,maxIndentLevels-1);
}
void RTFDocVisitor::incIndentLevel()
{
m_indentLevel++;
if (m_indentLevel>=maxIndentLevels)
{
err("Maximum indent level (%d) exceeded while generating RTF output!\n",maxIndentLevels-1);
}
}
void RTFDocVisitor::decIndentLevel()
{
if (m_indentLevel>0) m_indentLevel--;
}
//------------------------------------
// visitor functions for leaf nodes
//--------------------------------------
void RTFDocVisitor::operator()(const DocWord &w)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocWord)}\n");
filter(w.word());
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocLinkedWord &w)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocLinkedWord)}\n");
startLink(w.ref(),w.file(),w.anchor());
filter(w.word());
endLink(w.ref());
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocWhiteSpace &w)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocWhiteSpace)}\n");
if (m_insidePre)
{
m_t << w.chars();
}
else
{
m_t << " ";
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocSymbol &s)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocSymbol)}\n");
const char *res = HtmlEntityMapper::instance().rtf(s.symbol());
if (res)
{
m_t << res;
}
else
{
err("RTF: non supported HTML-entity found: %s\n",HtmlEntityMapper::instance().html(s.symbol(),TRUE));
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocEmoji &s)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocEmoji)}\n");
const char *res = EmojiEntityMapper::instance().unicode(s.index());
if (res)
{
const char *p = res;
int val = 0;
int val1 = 0;
while (*p)
{
switch(*p)
{
case '&': case '#': case 'x':
break;
case ';':
val1 = val;
val = 0xd800 + ( ( val1 - 0x10000 ) & 0xffc00 ) / 0x400 - 0x10000;
m_t << "\\u" << val << "?";
val = 0xdC00 + ( ( val1 - 0x10000 ) & 0x3ff ) - 0x10000 ;
m_t << "\\u" << val << "?";
val = 0;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
val = val * 16 + *p - '0';
break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
val = val * 16 + *p - 'a' + 10;
break;
}
p++;
}
}
else
{
m_t << s.name();
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocURL &u)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocURL)}\n");
if (Config_getBool(RTF_HYPERLINKS))
{
m_t << "{\\field "
"{\\*\\fldinst "
"{ HYPERLINK \"";
if (u.isEmail()) m_t << "mailto:";
m_t << u.url();
m_t << "\" }"
"{}";
m_t << "}"
"{\\fldrslt "
"{\\cs37\\ul\\cf2 ";
filter(u.url());
m_t << "}"
"}"
"}\n";
}
else
{
m_t << "{\\f2 ";
filter(u.url());
m_t << "}";
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocLineBreak &)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocLineBreak)}\n");
m_t << "\\par\n";
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHorRuler &)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocHorRuler)}\n");
m_t << "{\\pard\\widctlpar\\brdrb\\brdrs\\brdrw5\\brsp20 \\adjustright \\par}\n";
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocStyleChange &s)
{
if (m_hide) return;
m_lastIsPara=FALSE;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocStyleChange)}\n");
switch (s.style())
{
case DocStyleChange::Bold:
if (s.enable()) m_t << "{\\b "; else m_t << "} ";
break;
case DocStyleChange::S:
case DocStyleChange::Strike:
case DocStyleChange::Del:
if (s.enable()) m_t << "{\\strike "; else m_t << "} ";
break;
case DocStyleChange::Underline:
case DocStyleChange::Ins:
if (s.enable()) m_t << "{\\ul "; else m_t << "} ";
break;
case DocStyleChange::Italic:
if (s.enable()) m_t << "{\\i "; else m_t << "} ";
break;
case DocStyleChange::Kbd:
case DocStyleChange::Code:
if (s.enable()) m_t << "{\\f2 "; else m_t << "} ";
break;
case DocStyleChange::Subscript:
if (s.enable()) m_t << "{\\sub "; else m_t << "} ";
break;
case DocStyleChange::Superscript:
if (s.enable()) m_t << "{\\super "; else m_t << "} ";
break;
case DocStyleChange::Center:
if (s.enable()) m_t << "{\\qc "; else m_t << "} ";
break;
case DocStyleChange::Small:
if (s.enable()) m_t << "{\\sub "; else m_t << "} ";
break;
case DocStyleChange::Cite:
if (s.enable()) m_t << "{\\i "; else m_t << "} ";
break;
case DocStyleChange::Preformatted:
if (s.enable())
{
m_t << "{\n";
m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
m_insidePre=TRUE;
}
else
{
m_insidePre=FALSE;
m_t << "\\par";
m_t << "}\n";
}
m_lastIsPara=TRUE;
break;
case DocStyleChange::Div: /* HTML only */ break;
case DocStyleChange::Span: /* HTML only */ break;
}
}
void RTFDocVisitor::operator()(const DocVerbatim &s)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocVerbatim)}\n");
QCString lang = m_langExt;
if (!s.language().isEmpty()) // explicit language setting
{
lang = s.language();
}
SrcLangExt langExt = getLanguageFromCodeLang(lang);
switch(s.type())
{
case DocVerbatim::Code:
m_t << "{\n";
m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
getCodeParser(lang).parseCode(m_ci,s.context(),s.text(),langExt,
Config_getBool(STRIP_CODE_COMMENTS),
s.isExample(),s.exampleFile());
//m_t << "\\par\n";
m_t << "}\n";
break;
case DocVerbatim::JavaDocLiteral:
filter(s.text(),TRUE);
break;
case DocVerbatim::JavaDocCode:
m_t << "{\n";
m_t << "{\\f2 ";
filter(s.text(),TRUE);
m_t << "}";
m_t << "}\n";
break;
case DocVerbatim::Verbatim:
m_t << "{\n";
m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
filter(s.text(),TRUE);
//m_t << "\\par\n";
m_t << "}\n";
break;
case DocVerbatim::RtfOnly:
m_t << s.text();
break;
case DocVerbatim::HtmlOnly:
case DocVerbatim::LatexOnly:
case DocVerbatim::XmlOnly:
case DocVerbatim::ManOnly:
case DocVerbatim::DocbookOnly:
/* nothing */
break;
case DocVerbatim::Dot:
{
static int dotindex = 1;
QCString fileName(4096, QCString::ExplicitSize);
fileName.sprintf("%s%d%s",
qPrint(Config_getString(RTF_OUTPUT)+"/inline_dotgraph_"),
dotindex++,
".dot"
);
std::ofstream file = Portable::openOutputStream(fileName);
if (!file.is_open())
{
err("Could not open file %s for writing\n",qPrint(fileName));
}
else
{
QCString stext = s.text();
file.write( stext.data(), stext.length() );
file.close();
}
writeDotFile(fileName, s.hasCaption(), s.srcFile(), s.srcLine());
visitChildren(s);
includePicturePostRTF(true, s.hasCaption());
if (Config_getBool(DOT_CLEANUP)) Dir().remove(fileName.str());
}
break;
case DocVerbatim::Msc:
{
static int mscindex = 1;
QCString baseName(4096, QCString::ExplicitSize);
baseName.sprintf("%s%d%s",
qPrint(Config_getString(RTF_OUTPUT)+"/inline_mscgraph_"),
mscindex++,
".msc"
);
std::ofstream file = Portable::openOutputStream(baseName);
if (!file.is_open())
{
err("Could not open file %s for writing\n",qPrint(baseName));
}
QCString text = "msc {";
text+=s.text();
text+="}";
file.write( text.data(), text.length() );
file.close();
writeMscFile(baseName, s.hasCaption(), s.srcFile(), s.srcLine());
visitChildren(s);
includePicturePostRTF(true, s.hasCaption());
if (Config_getBool(DOT_CLEANUP)) Dir().remove(baseName.str());
}
break;
case DocVerbatim::PlantUML:
{
QCString rtfOutput = Config_getString(RTF_OUTPUT);
QCString baseName = PlantumlManager::instance().writePlantUMLSource(
rtfOutput,s.exampleFile(),s.text(),PlantumlManager::PUML_BITMAP,
s.engine(),s.srcFile(),s.srcLine(),true);
writePlantUMLFile(baseName, s.hasCaption());
visitChildren(s);
includePicturePostRTF(true, s.hasCaption());
}
break;
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocAnchor &anc)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocAnchor)}\n");
QCString anchor;
if (!anc.file().isEmpty())
{
anchor+=stripPath(anc.file());
}
if (!anc.file().isEmpty() && !anc.anchor().isEmpty())
{
anchor+="_";
}
if (!anc.anchor().isEmpty())
{
anchor+=anc.anchor();
}
m_t << "{\\bkmkstart " << rtfFormatBmkStr(anchor) << "}\n";
m_t << "{\\bkmkend " << rtfFormatBmkStr(anchor) << "}\n";
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocInclude &inc)
{
if (m_hide) return;
SrcLangExt langExt = getLanguageFromFileName(inc.extension());
DBG_RTF("{\\comment RTFDocVisitor::visit(DocInclude)}\n");
switch(inc.type())
{
case DocInclude::IncWithLines:
{
m_t << "{\n";
m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
FileInfo cfi( inc.file().str() );
auto fd = createFileDef( cfi.dirPath(), cfi.fileName() );
getCodeParser(inc.extension()).parseCode(m_ci,inc.context(),
inc.text(),
langExt,
inc.stripCodeComments(),
inc.isExample(),
inc.exampleFile(),
fd.get(), // fileDef,
-1, // start line
-1, // end line
FALSE, // inline fragment
nullptr, // memberDef
TRUE // show line numbers
);
m_t << "\\par";
m_t << "}\n";
}
break;
case DocInclude::Include:
m_t << "{\n";
m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
getCodeParser(inc.extension()).parseCode(m_ci,inc.context(),
inc.text(),langExt,
inc.stripCodeComments(),
inc.isExample(),
inc.exampleFile(),
nullptr, // fileDef
-1, // startLine
-1, // endLine
TRUE, // inlineFragment
nullptr, // memberDef
FALSE // show line numbers
);
m_t << "\\par";
m_t << "}\n";
break;
case DocInclude::DontInclude:
case DocInclude::DontIncWithLines:
case DocInclude::HtmlInclude:
case DocInclude::LatexInclude:
case DocInclude::ManInclude:
case DocInclude::XmlInclude:
case DocInclude::DocbookInclude:
break;
case DocInclude::RtfInclude:
m_t << inc.text();
break;
case DocInclude::VerbInclude:
m_t << "{\n";
m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
filter(inc.text());
m_t << "\\par";
m_t << "}\n";
break;
case DocInclude::Snippet:
case DocInclude::SnippetWithLines:
m_t << "{\n";
if (!m_lastIsPara) m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
CodeFragmentManager::instance().parseCodeFragment(m_ci,
inc.file(),
inc.blockId(),
inc.context(),
inc.type()==DocInclude::SnippetWithLines,
inc.trimLeft(),
inc.stripCodeComments()
);
m_t << "}";
break;
}
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocIncOperator &op)
{
//printf("DocIncOperator: type=%d first=%d, last=%d text='%s'\n",
// op.type(),op.isFirst(),op.isLast(),qPrint(op.text()));
DBG_RTF("{\\comment RTFDocVisitor::visit(DocIncOperator)}\n");
QCString locLangExt = getFileNameExtension(op.includeFileName());
if (locLangExt.isEmpty()) locLangExt = m_langExt;
SrcLangExt langExt = getLanguageFromFileName(locLangExt);
if (op.isFirst())
{
if (!m_hide)
{
m_t << "{\n";
m_t << "\\par\n";
m_t << rtf_Style_Reset << getStyle("CodeExample");
}
pushHidden(m_hide);
m_hide = TRUE;
}
if (op.type()!=DocIncOperator::Skip)
{
m_hide = popHidden();
if (!m_hide)
{
std::unique_ptr<FileDef> fd = nullptr;
if (!op.includeFileName().isEmpty())
{
FileInfo cfi( op.includeFileName().str() );
fd = createFileDef( cfi.dirPath(), cfi.fileName() );
}
getCodeParser(locLangExt).parseCode(m_ci,op.context(),op.text(),langExt,
op.stripCodeComments(),
op.isExample(),op.exampleFile(),
fd.get(), // fileDef
op.line(), // startLine
-1, // endLine
FALSE, // inline fragment
nullptr, // memberDef
op.showLineNo() // show line numbers
);
}
pushHidden(m_hide);
m_hide=TRUE;
}
if (op.isLast())
{
m_hide = popHidden();
if (!m_hide)
{
m_t << "\\par";
m_t << "}\n";
}
m_lastIsPara=TRUE;
}
else
{
if (!m_hide) m_t << "\n";
m_lastIsPara=FALSE;
}
}
void RTFDocVisitor::operator()(const DocFormula &f)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocFormula)}\n");
bool bDisplay = !f.isInline();
if (bDisplay)
{
m_t << "\\par";
m_t << "{";
m_t << "\\pard\\plain";
m_t << "\\pard";
m_t << "\\qc";
}
m_t << "{ \\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"" << f.relPath() << f.name() << ".png\" \\\\d \\\\*MERGEFORMAT}{\\fldrslt Image}}";
if (bDisplay)
{
m_t << "\\par}";
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocIndexEntry &i)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::visit(DocIndexEntry)}\n");
m_t << "{\\xe \\v " << i.entry() << "}\n";
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocSimpleSectSep &)
{
}
void RTFDocVisitor::operator()(const DocCite &cite)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocCite &)}\n");
if (!cite.file().isEmpty())
{
startLink(cite.ref(),cite.file(),cite.anchor());
}
else
{
m_t << "{\\b ";
}
filter(cite.text());
if (!cite.file().isEmpty())
{
endLink(cite.ref());
}
else
{
m_t << "}";
}
}
//--------------------------------------
// visitor functions for compound nodes
//--------------------------------------
void RTFDocVisitor::operator()(const DocAutoList &l)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocAutoList &)}\n");
m_t << "{\n";
int level = indentLevel();
m_listItemInfo[level].isEnum = l.isEnumList();
m_listItemInfo[level].isCheck = l.isCheckedList();
m_listItemInfo[level].type = '1';
m_listItemInfo[level].number = 1;
m_lastIsPara=FALSE;
visitChildren(l);
if (!m_lastIsPara) m_t << "\\par";
m_t << "}\n";
m_lastIsPara=TRUE;
if (!l.isCheckedList() && indentLevel()==0) m_t << "\\par\n";
}
void RTFDocVisitor::operator()(const DocAutoListItem &li)
{
static int prevLevel = -1;
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocAutoListItem &)}\n");
int level = indentLevel();
if ((level != prevLevel-1) &&
(!(level==prevLevel && level != 0 && m_listItemInfo[level].isCheck)) &&
(!m_lastIsPara))
m_t << "\\par\n";
prevLevel= level;
m_t << rtf_Style_Reset;
if (m_listItemInfo[level].isEnum)
{
m_t << getStyle("ListEnum") << "\n";
m_t << m_listItemInfo[level].number << ".\\tab ";
m_listItemInfo[level].number++;
}
else
{
switch (li.itemNumber())
{
case DocAutoList::Unchecked: // unchecked
m_t << getListTable(2) << "\n";
break;
case DocAutoList::Checked_x: // checked with x
case DocAutoList::Checked_X: // checked with X
m_t << getListTable(3) << "\n";
break;
default:
m_t << getListTable(1) << "\n";
break;
}
}
incIndentLevel();
m_lastIsPara=false;
visitChildren(li);
decIndentLevel();
}
void RTFDocVisitor::operator()(const DocPara &p)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocPara &)}\n");
visitChildren(p);
if (!m_lastIsPara &&
!p.isLast() && // omit <p> for last paragraph
!(p.parent() && // and for parameters & sections
std::get_if<DocParamSect>(p.parent())
)
)
{
m_t << "\\par\n";
m_lastIsPara=TRUE;
}
}
void RTFDocVisitor::operator()(const DocRoot &r)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocRoot &)}\n");
if (r.indent()) incIndentLevel();
m_t << "{" << rtf_Style["BodyText"].reference() << "\n";
visitChildren(r);
if (!m_lastIsPara && !r.singleLine()) m_t << "\\par\n";
m_t << "}";
m_lastIsPara=TRUE;
if (r.indent()) decIndentLevel();
}
void RTFDocVisitor::operator()(const DocSimpleSect &s)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocSimpleSect &)}\n");
if (!m_lastIsPara) m_t << "\\par\n";
m_t << "{"; // start desc
//m_t << "{\\b "; // start bold
m_t << "{" << rtf_Style["Heading5"].reference() << "\n";
switch(s.type())
{
case DocSimpleSect::See:
m_t << theTranslator->trSeeAlso(); break;
case DocSimpleSect::Return:
m_t << theTranslator->trReturns(); break;
case DocSimpleSect::Author:
m_t << theTranslator->trAuthor(TRUE,TRUE); break;
case DocSimpleSect::Authors:
m_t << theTranslator->trAuthor(TRUE,FALSE); break;
case DocSimpleSect::Version:
m_t << theTranslator->trVersion(); break;
case DocSimpleSect::Since:
m_t << theTranslator->trSince(); break;
case DocSimpleSect::Date:
m_t << theTranslator->trDate(); break;
case DocSimpleSect::Note:
m_t << theTranslator->trNote(); break;
case DocSimpleSect::Warning:
m_t << theTranslator->trWarning(); break;
case DocSimpleSect::Pre:
m_t << theTranslator->trPrecondition(); break;
case DocSimpleSect::Post:
m_t << theTranslator->trPostcondition(); break;
case DocSimpleSect::Copyright:
m_t << theTranslator->trCopyright(); break;
case DocSimpleSect::Invar:
m_t << theTranslator->trInvariant(); break;
case DocSimpleSect::Remark:
m_t << theTranslator->trRemarks(); break;
case DocSimpleSect::Attention:
m_t << theTranslator->trAttention(); break;
case DocSimpleSect::Important:
m_t << theTranslator->trImportant(); break;
case DocSimpleSect::User: break;
case DocSimpleSect::Rcs: break;
case DocSimpleSect::Unknown: break;
}
incIndentLevel();
if (s.type()!=DocSimpleSect::User && s.type()!=DocSimpleSect::Rcs)
{
m_t << "\\par";
m_t << "}"; // end bold
m_t << rtf_Style_Reset << getStyle("DescContinue");
m_t << "{\\s17 \\sa60 \\sb30\n";
}
else
{
if (s.title())
{
std::visit(*this,*s.title());
}
m_t << "\\par\n";
m_t << "}"; // end bold
m_t << rtf_Style_Reset << getStyle("DescContinue");
}
m_lastIsPara=FALSE;
visitChildren(s);
if (!m_lastIsPara) m_t << "\\par\n";
decIndentLevel();
if (s.type()!=DocSimpleSect::User && s.type()!=DocSimpleSect::Rcs)
{
m_t << "}"; // end DescContinue
}
m_t << "}"; // end desc
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocTitle &t)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocTitle &)}\n");
if (m_hide) return;
visitChildren(t);
}
void RTFDocVisitor::operator()(const DocSimpleList &l)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocSimpleSect &)}\n");
m_t << "{\n";
m_listItemInfo[indentLevel()].isEnum = false;
m_listItemInfo[indentLevel()].isCheck = false;
m_lastIsPara=FALSE;
visitChildren(l);
if (!m_lastIsPara) m_t << "\\par\n";
m_t << "}\n";
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocSimpleListItem &li)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocSimpleListItem &)}\n");
m_t << "\\par" << rtf_Style_Reset << getStyle("ListBullet") << "\n";
m_lastIsPara=FALSE;
incIndentLevel();
if (li.paragraph())
{
std::visit(*this,*li.paragraph());
}
decIndentLevel();
DBG_RTF("{\\comment RTFDocVisitor::visitPost(DocSimpleListItem)}\n");
}
void RTFDocVisitor::operator()(const DocSection &s)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocSection &)}\n");
if (!m_lastIsPara) m_t << "\\par\n";
m_t << "{\\bkmkstart " << rtfFormatBmkStr(stripPath(s.file())+"_"+s.anchor()) << "}\n";
m_t << "{\\bkmkend " << rtfFormatBmkStr(stripPath(s.file())+"_"+s.anchor()) << "}\n";
m_t << "{{" // start section
<< rtf_Style_Reset;
QCString heading;
int level = std::min(s.level()+2+m_hierarchyLevel,4);
if (level <= 0)
level = 1;
heading.sprintf("Heading%d",level);
// set style
m_t << rtf_Style[heading.str()].reference() << "\n";
// make table of contents entry
if (s.title())
{
std::visit(*this,*s.title());
}
m_t << "\n\\par" << "}\n";
m_t << "{\\tc\\tcl" << level << " \\v ";
if (s.title())
{
std::visit(*this,*s.title());
}
m_t << "}\n";
m_lastIsPara=TRUE;
visitChildren(s);
m_t << "\\par}\n"; // end section
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHtmlList &l)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlList &)}\n");
m_t << "{\n";
int level = indentLevel();
m_listItemInfo[level].isEnum = l.type()==DocHtmlList::Ordered;
m_listItemInfo[level].isCheck = false;
m_listItemInfo[level].number = 1;
m_listItemInfo[level].type = '1';
for (const auto &opt : l.attribs())
{
if (opt.name=="type")
{
m_listItemInfo[level].type = opt.value[0];
}
if (opt.name=="start")
{
bool ok = false;
int val = opt.value.toInt(&ok);
if (ok) m_listItemInfo[level].number = val;
}
}
m_lastIsPara=FALSE;
visitChildren(l);
m_t << "\\par" << "}\n";
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHtmlListItem &l)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlListItem &)}\n");
m_t << "\\par\n";
m_t << rtf_Style_Reset;
int level = indentLevel();
if (m_listItemInfo[level].isEnum)
{
for (const auto &opt : l.attribs())
{
if (opt.name=="value")
{
bool ok = false;
int val = opt.value.toInt(&ok);
if (ok) m_listItemInfo[level].number = val;
}
}
m_t << getStyle("ListEnum") << "\n";
switch (m_listItemInfo[level].type)
{
case '1':
m_t << m_listItemInfo[level].number;
break;
case 'a':
m_t << integerToAlpha(m_listItemInfo[level].number,false);
break;
case 'A':
m_t << integerToAlpha(m_listItemInfo[level].number);
break;
case 'i':
m_t << integerToRoman(m_listItemInfo[level].number,false);
break;
case 'I':
m_t << integerToRoman(m_listItemInfo[level].number);
break;
default:
m_t << m_listItemInfo[level].number;
break;
}
m_t << ".\\tab ";
m_listItemInfo[level].number++;
}
else
{
m_t << getStyle("ListBullet") << "\n";
}
incIndentLevel();
m_lastIsPara=FALSE;
visitChildren(l);
decIndentLevel();
DBG_RTF("{\\comment RTFDocVisitor::visitPost(DocHtmlListItem)}\n");
}
void RTFDocVisitor::operator()(const DocHtmlDescList &dl)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlDescList &)}\n");
//m_t << "{\n";
//m_t << rtf_Style_Reset << getStyle("ListContinue");
//m_lastIsPara=FALSE;
visitChildren(dl);
//m_t << "}\n";
//m_t << "\\par\n";
//m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHtmlDescTitle &dt)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlDescTitle &)}\n");
//m_t << "\\par\n";
//m_t << "{\\b ";
m_t << "{" << rtf_Style["Heading5"].reference() << "\n";
m_lastIsPara=FALSE;
visitChildren(dt);
m_t << "\\par\n";
m_t << "}\n";
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHtmlDescData &dd)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlDescData &)}\n");
incIndentLevel();
m_t << "{" << rtf_Style_Reset << getStyle("DescContinue");
visitChildren(dd);
m_t << "\\par";
m_t << "}\n";
decIndentLevel();
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHtmlTable &t)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlTable &)}\n");
if (!m_lastIsPara) m_t << "\\par\n";
m_lastIsPara=TRUE;
if (t.caption())
{
const DocHtmlCaption &c = std::get<DocHtmlCaption>(*t.caption());
m_t << "\\pard \\qc \\b";
if (!c.file().isEmpty())
{
m_t << "{\\bkmkstart " << rtfFormatBmkStr(stripPath(c.file())+"_"+c.anchor()) << "}\n";
m_t << "{\\bkmkend " << rtfFormatBmkStr(stripPath(c.file())+"_"+c.anchor()) << "}\n";
}
m_t << "{Table \\field\\flddirty{\\*\\fldinst { SEQ Table \\\\*Arabic }}{\\fldrslt {\\noproof 1}} ";
std::visit(*this,*t.caption());
}
visitChildren(t);
m_t << "\\pard\\plain\n";
m_t << "\\par\n";
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHtmlCaption &c)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlCaption &)}\n");
visitChildren(c);
m_t << "}\n\\par\n";
}
void RTFDocVisitor::operator()(const DocHtmlRow &r)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlRow &)}\n");
size_t columnWidth=r.numCells()>0 ? rtf_pageWidth/r.numCells() : 10;
m_t << "\\trowd \\trgaph108\\trleft-108"
"\\trbrdrt\\brdrs\\brdrw10 "
"\\trbrdrl\\brdrs\\brdrw10 "
"\\trbrdrb\\brdrs\\brdrw10 "
"\\trbrdrr\\brdrs\\brdrw10 "
"\\trbrdrh\\brdrs\\brdrw10 "
"\\trbrdrv\\brdrs\\brdrw10 \n";
for (size_t i=0;i<r.numCells();i++)
{
if (r.isHeading())
{
m_t << "\\clcbpat16"; // set cell shading to light grey (color 16 in the clut)
}
m_t << "\\clvertalt\\clbrdrt\\brdrs\\brdrw10 "
"\\clbrdrl\\brdrs\\brdrw10 "
"\\clbrdrb\\brdrs\\brdrw10 "
"\\clbrdrr \\brdrs\\brdrw10 "
"\\cltxlrtb "
"\\cellx" << ((i+1)*columnWidth) << "\n";
}
m_t << "\\pard \\widctlpar\\intbl\\adjustright\n";
m_lastIsPara=FALSE;
visitChildren(r);
m_t << "\n";
m_t << "\\pard \\widctlpar\\intbl\\adjustright\n";
m_t << "{\\row }\n";
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocHtmlCell &c)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlCell &)}\n");
m_t << "{" << align(c);
m_lastIsPara=FALSE;
visitChildren(c);
m_t << "\\cell }";
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocInternal &i)
{
if (m_hide) return;
visitChildren(i);
}
void RTFDocVisitor::operator()(const DocHRef &href)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHRef &)}\n");
if (Config_getBool(RTF_HYPERLINKS))
{
if (href.url().startsWith("#"))
{
// when starting with # so a local link
QCString cite;
cite = href.file() + "_" + href.url().right(href.url().length()-1);
m_t << "{\\field "
"{\\*\\fldinst "
"{ HYPERLINK \\\\l \"" << rtfFormatBmkStr(cite) << "\" "
"}{}"
"}"
"{\\fldrslt "
"{\\cs37\\ul\\cf2 ";
}
else
{
m_t << "{\\field "
"{\\*\\fldinst "
"{ HYPERLINK \"" << href.url() << "\" "
"}{}"
"}"
"{\\fldrslt "
"{\\cs37\\ul\\cf2 ";
}
}
else
{
m_t << "{\\f2 ";
}
m_lastIsPara=FALSE;
visitChildren(href);
if (Config_getBool(RTF_HYPERLINKS))
{
m_t << "}"
"}"
"}";
}
else
{
m_t << "}";
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::operator()(const DocHtmlSummary &s)
{
if (m_hide) return;
m_t << "{\\b ";
visitChildren(s);
m_t << "}\\par ";
}
void RTFDocVisitor::operator()(const DocHtmlDetails &d)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlDetails &)}\n");
if (!m_lastIsPara) m_t << "\\par\n";
auto summary = d.summary();
if (summary)
{
std::visit(*this,*summary);
m_t << "{"; // start desc
incIndentLevel();
m_t << rtf_Style_Reset << getStyle("DescContinue");
}
visitChildren(d);
if (!m_lastIsPara) m_t << "\\par\n";
if (summary)
{
decIndentLevel();
m_t << "}"; // end desc
}
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocHtmlHeader &header)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlHeader &)}\n");
m_t << "{" // start section
<< rtf_Style_Reset;
QCString heading;
int level = std::clamp(header.level()+m_hierarchyLevel,SectionType::MinLevel,SectionType::MaxLevel);
heading.sprintf("Heading%d",level);
// set style
m_t << rtf_Style[heading.str()].reference();
// make open table of contents entry that will be closed in visitPost method
m_t << "{\\tc\\tcl" << level << " ";
m_lastIsPara=FALSE;
visitChildren(header);
// close open table of contents entry
m_t << "} \\par";
m_t << "}\n"; // end section
m_lastIsPara=TRUE;
}
void RTFDocVisitor::includePicturePreRTF(const QCString &name, bool isTypeRTF, bool hasCaption, bool inlineImage)
{
if (isTypeRTF)
{
if (!inlineImage)
{
m_t << "\\par\n";
m_t << "{\n";
m_t << rtf_Style_Reset << "\n";
if (hasCaption || m_lastIsPara) m_t << "\\par\n";
m_t << "\\pard \\qc ";
}
m_t << "{ \\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"";
m_t << name;
m_t << "\" \\\\d \\\\*MERGEFORMAT}{\\fldrslt Image}}\n";
if (!inlineImage)
{
m_t << "\\par\n";
if (hasCaption)
{
m_t << "\\pard \\qc \\b";
m_t << "{Image \\field\\flddirty{\\*\\fldinst { SEQ Image \\\\*Arabic }}{\\fldrslt {\\noproof 1}} ";
}
m_lastIsPara=TRUE;
}
else
{
if (hasCaption) m_t << "{\\comment "; // to prevent caption to be shown
}
}
else // other format -> skip
{
pushHidden(m_hide);
m_hide=TRUE;
}
}
void RTFDocVisitor::includePicturePostRTF(bool isTypeRTF, bool hasCaption, bool inlineImage)
{
if (isTypeRTF)
{
if (m_hide) return;
if (inlineImage)
{
if (hasCaption) m_t << " }";
}
else
{
if (hasCaption)
{
m_t << "}\n";
m_t << "\\par}\n";
}
else
{
m_t << "}\n";
}
}
}
else
{
m_hide = popHidden();
}
}
void RTFDocVisitor::operator()(const DocImage &img)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocImage &)}\n");
includePicturePreRTF(img.name(), img.type()==DocImage::Rtf, img.hasCaption(), img.isInlineImage());
visitChildren(img);
includePicturePostRTF(img.type()==DocImage::Rtf, img.hasCaption(), img.isInlineImage());
}
void RTFDocVisitor::operator()(const DocDotFile &df)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocDotFile &)}\n");
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(RTF_OUTPUT)+"/"+stripPath(df.file()));
writeDotFile(df);
visitChildren(df);
includePicturePostRTF(true, df.hasCaption());
}
void RTFDocVisitor::operator()(const DocMscFile &df)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocMscFile &)}\n");
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(RTF_OUTPUT)+"/"+stripPath(df.file()));
writeMscFile(df);
visitChildren(df);
includePicturePostRTF(true, df.hasCaption());
}
void RTFDocVisitor::operator()(const DocDiaFile &df)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocDiaFile &)}\n");
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(RTF_OUTPUT)+"/"+stripPath(df.file()));
writeDiaFile(df);
visitChildren(df);
includePicturePostRTF(true, df.hasCaption());
}
void RTFDocVisitor::operator()(const DocPlantUmlFile &df)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocPlantUmlFile &)}\n");
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(RTF_OUTPUT)+"/"+stripPath(df.file()));
QCString rtfOutput = Config_getString(RTF_OUTPUT);
std::string inBuf;
readInputFile(df.file(),inBuf);
QCString baseName = PlantumlManager::instance().writePlantUMLSource(
rtfOutput,QCString(),inBuf.c_str(),PlantumlManager::PUML_BITMAP,
QCString(),df.srcFile(),df.srcLine(),false);
writePlantUMLFile(baseName, df.hasCaption());
visitChildren(df);
includePicturePostRTF(true, df.hasCaption());
}
void RTFDocVisitor::operator()(const DocLink &lnk)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocLink &)}\n");
startLink(lnk.ref(),lnk.file(),lnk.anchor());
visitChildren(lnk);
endLink(lnk.ref());
}
void RTFDocVisitor::operator()(const DocRef &ref)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocRef &)}\n");
// when ref.isSubPage()==TRUE we use ref.file() for HTML and
// ref.anchor() for LaTeX/RTF
if (ref.isSubPage())
{
startLink(ref.ref(),QCString(),ref.anchor());
}
else
{
if (!ref.file().isEmpty()) startLink(ref.ref(),ref.file(),ref.anchor());
}
if (!ref.hasLinkText()) filter(ref.targetTitle());
visitChildren(ref);
if (!ref.file().isEmpty()) endLink(ref.ref());
//m_t << " ";
}
void RTFDocVisitor::operator()(const DocSecRefItem &ref)
{
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocSecRefItem &)}\n");
visitChildren(ref);
}
void RTFDocVisitor::operator()(const DocSecRefList &l)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocSecRefList &)}\n");
m_t << "{\n";
incIndentLevel();
m_t << rtf_Style_Reset << getStyle("LatexTOC") << "\n";
m_t << "\\par\n";
m_lastIsPara=TRUE;
visitChildren(l);
decIndentLevel();
m_t << "\\par";
m_t << "}\n";
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocParamSect &s)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocParamSect &)}\n");
m_t << "{"; // start param list
if (!m_lastIsPara) m_t << "\\par\n";
//m_t << "{\\b "; // start bold
m_t << "{" << rtf_Style["Heading5"].reference() << "\n";
switch(s.type())
{
case DocParamSect::Param:
m_t << theTranslator->trParameters(); break;
case DocParamSect::RetVal:
m_t << theTranslator->trReturnValues(); break;
case DocParamSect::Exception:
m_t << theTranslator->trExceptions(); break;
case DocParamSect::TemplateParam:
m_t << theTranslator->trTemplateParameters(); break;
default:
ASSERT(0);
}
m_t << "\\par";
m_t << "}\n";
bool useTable = s.type()==DocParamSect::Param ||
s.type()==DocParamSect::RetVal ||
s.type()==DocParamSect::Exception ||
s.type()==DocParamSect::TemplateParam;
if (!useTable)
{
incIndentLevel();
}
m_t << rtf_Style_Reset << getStyle("DescContinue");
m_lastIsPara=TRUE;
visitChildren(s);
//m_t << "\\par\n";
if (!useTable)
{
decIndentLevel();
}
m_t << "}\n";
}
void RTFDocVisitor::operator()(const DocSeparator &sep)
{
m_t << " " << sep.chars() << " ";
}
void RTFDocVisitor::operator()(const DocParamList &pl)
{
static int columnPos[4][5] =
{ { 2, 25, 100, 100, 100 }, // no inout, no type
{ 3, 14, 35, 100, 100 }, // inout, no type
{ 3, 25, 50, 100, 100 }, // no inout, type
{ 4, 14, 35, 55, 100 }, // inout, type
};
int config=0;
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocParamList &)}\n");
DocParamSect::Type parentType = DocParamSect::Unknown;
const DocParamSect *sect = std::get_if<DocParamSect>(pl.parent());
if (sect)
{
parentType = sect->type();
}
bool useTable = parentType==DocParamSect::Param ||
parentType==DocParamSect::RetVal ||
parentType==DocParamSect::Exception ||
parentType==DocParamSect::TemplateParam;
if (sect && sect->hasInOutSpecifier()) config+=1;
if (sect && sect->hasTypeSpecifier()) config+=2;
if (useTable)
{
m_t << "\\trowd \\trgaph108\\trleft426\\tblind426"
"\\trbrdrt\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrl\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrb\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrr\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrh\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrv\\brdrs\\brdrw10\\brdrcf15 "<< "\n";
for (int i=0;i<columnPos[config][0];i++)
{
m_t << "\\clvertalt\\clbrdrt\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrl\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrb\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrr \\brdrs\\brdrw10\\brdrcf15 "
"\\cltxlrtb "
"\\cellx" << (rtf_pageWidth*columnPos[config][i+1]/100) << "\n";
}
m_t << "\\pard \\widctlpar\\intbl\\adjustright\n";
}
if (sect && sect->hasInOutSpecifier())
{
if (useTable)
{
m_t << "{";
}
// Put in the direction: in/out/in,out if specified.
if (pl.direction()!=DocParamSect::Unspecified)
{
if (pl.direction()==DocParamSect::In)
{
m_t << "in";
}
else if (pl.direction()==DocParamSect::Out)
{
m_t << "out";
}
else if (pl.direction()==DocParamSect::InOut)
{
m_t << "in,out";
}
}
if (useTable)
{
m_t << "\\cell }";
}
}
if (sect && sect->hasTypeSpecifier())
{
if (useTable)
{
m_t << "{";
}
for (const auto &type : pl.paramTypes())
{
std::visit(*this,type);
}
if (useTable)
{
m_t << "\\cell }";
}
}
if (useTable)
{
m_t << "{";
}
m_t << "{\\i ";
bool first=TRUE;
for (const auto ¶m : pl.parameters())
{
if (!first) m_t << ","; else first=FALSE;
std::visit(*this,param);
}
m_t << "} ";
if (useTable)
{
m_t << "\\cell }{";
}
m_lastIsPara=TRUE;
for (const auto &par : pl.paragraphs())
{
std::visit(*this,par);
}
if (useTable)
{
m_t << "\\cell }\n";
//m_t << "\\pard \\widctlpar\\intbl\\adjustright\n";
m_t << "{\\row }\n";
}
else
{
m_t << "\\par\n";
}
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocXRefItem &x)
{
if (m_hide) return;
if (x.title().isEmpty()) return;
bool anonymousEnum = x.file()=="@";
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocXRefItem &)}\n");
if (!m_lastIsPara)
{
m_t << "\\par\n";
m_lastIsPara=TRUE;
}
m_t << "{"; // start param list
//m_t << "{\\b "; // start bold
m_t << "{" << rtf_Style["Heading5"].reference() << "\n";
if (Config_getBool(RTF_HYPERLINKS) && !anonymousEnum)
{
QCString refName;
if (!x.file().isEmpty())
{
refName+=stripPath(x.file());
}
if (!x.file().isEmpty() && !x.anchor().isEmpty())
{
refName+="_";
}
if (!x.anchor().isEmpty())
{
refName+=x.anchor();
}
m_t << "{\\field "
"{\\*\\fldinst "
"{ HYPERLINK \\\\l \"" << rtfFormatBmkStr(refName) << "\" "
"}{}"
"}"
"{\\fldrslt "
"{\\cs37\\ul\\cf2 ";
filter(x.title());
m_t << "}"
"}"
"}";
}
else
{
filter(x.title());
}
m_t << ":";
m_t << "\\par";
m_t << "}"; // end bold
incIndentLevel();
m_t << rtf_Style_Reset << getStyle("DescContinue");
m_lastIsPara=FALSE;
visitChildren(x);
if (x.title().isEmpty()) return;
DBG_RTF("{\\comment RTFDocVisitor::visitPost(DocXRefItem)}\n");
m_t << "\\par\n";
decIndentLevel();
m_t << "}\n"; // end xref item
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocInternalRef &ref)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocInternalRef &)}\n");
startLink("",ref.file(),ref.anchor());
visitChildren(ref);
endLink("");
m_t << " ";
}
void RTFDocVisitor::operator()(const DocText &t)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocText &)}\n");
visitChildren(t);
}
void RTFDocVisitor::operator()(const DocHtmlBlockQuote &q)
{
if (m_hide) return;
DBG_RTF("{\\comment RTFDocVisitor::operator()(const DocHtmlBlockQuote &)}\n");
if (!m_lastIsPara) m_t << "\\par\n";
m_t << "{"; // start desc
incIndentLevel();
m_t << rtf_Style_Reset << getStyle("DescContinue");
visitChildren(q);
if (!m_lastIsPara) m_t << "\\par\n";
decIndentLevel();
m_t << "}"; // end desc
m_lastIsPara=TRUE;
}
void RTFDocVisitor::operator()(const DocVhdlFlow &)
{
}
void RTFDocVisitor::operator()(const DocParBlock &pb)
{
if (m_hide) return;
visitChildren(pb);
}
//static char* getMultiByte(int c)
//{
// static char s[10];
// sprintf(s,"\\'%X",c);
// return s;
//}
void RTFDocVisitor::filter(const QCString &str,bool verbatim)
{
if (!str.isEmpty())
{
const char *p=str.data();
while (*p)
{
char c=*p++;
switch (c)
{
case '{': m_t << "\\{"; break;
case '}': m_t << "\\}"; break;
case '\\': m_t << "\\\\"; break;
case '\n': if (verbatim)
{
m_t << "\\par\n";
}
else
{
m_t << '\n';
}
break;
default: m_t << c;
}
}
}
}
void RTFDocVisitor::startLink(const QCString &ref,const QCString &file,const QCString &anchor)
{
if (ref.isEmpty() && Config_getBool(RTF_HYPERLINKS))
{
QCString refName;
if (!file.isEmpty())
{
refName+=stripPath(file);
}
if (!file.isEmpty() && !anchor.isEmpty())
{
refName+='_';
}
if (!anchor.isEmpty())
{
refName+=anchor;
}
m_t << "{\\field {\\*\\fldinst { HYPERLINK \\\\l \"";
m_t << rtfFormatBmkStr(refName);
m_t << "\" }{}";
m_t << "}{\\fldrslt {\\cs37\\ul\\cf2 ";
}
else
{
m_t << "{\\b ";
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::endLink(const QCString &ref)
{
if (ref.isEmpty() && Config_getBool(RTF_HYPERLINKS))
{
m_t << "}}}";
}
else
{
m_t << "}";
}
m_lastIsPara=FALSE;
}
void RTFDocVisitor::writeDotFile(const DocDotFile &df)
{
writeDotFile(df.file(), df.hasCaption(), df.srcFile(), df.srcLine());
}
void RTFDocVisitor::writeDotFile(const QCString &filename, bool hasCaption,
const QCString &srcFile, int srcLine)
{
QCString baseName=makeBaseName(filename);
QCString outDir = Config_getString(RTF_OUTPUT);
writeDotGraphFromFile(filename,outDir,baseName,GraphOutputFormat::BITMAP,srcFile,srcLine);
QCString imgExt = getDotImageExtension();
includePicturePreRTF(baseName + "." + imgExt, true, hasCaption);
}
void RTFDocVisitor::writeMscFile(const DocMscFile &df)
{
writeMscFile(df.file(), df.hasCaption(), df.srcFile(), df.srcLine());
}
void RTFDocVisitor::writeMscFile(const QCString &fileName, bool hasCaption,
const QCString &srcFile, int srcLine)
{
QCString baseName=makeBaseName(fileName);
QCString outDir = Config_getString(RTF_OUTPUT);
writeMscGraphFromFile(fileName,outDir,baseName,MscOutputFormat::BITMAP,srcFile,srcLine);
includePicturePreRTF(baseName + ".png", true, hasCaption);
}
void RTFDocVisitor::writeDiaFile(const DocDiaFile &df)
{
QCString baseName=makeBaseName(df.file());
QCString outDir = Config_getString(RTF_OUTPUT);
writeDiaGraphFromFile(df.file(),outDir,baseName,DiaOutputFormat::BITMAP,df.srcFile(),df.srcLine());
includePicturePreRTF(baseName + ".png", true, df.hasCaption());
}
void RTFDocVisitor::writePlantUMLFile(const QCString &fileName, bool hasCaption)
{
QCString baseName=makeBaseName(fileName);
QCString outDir = Config_getString(RTF_OUTPUT);
PlantumlManager::instance().generatePlantUMLOutput(fileName,outDir,PlantumlManager::PUML_BITMAP);
includePicturePreRTF(baseName + ".png", true, hasCaption);
}
| 48,740
|
C++
|
.cpp
| 1,675
| 23.587463
| 145
| 0.570893
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,425
|
plantuml.cpp
|
doxygen_doxygen/src/plantuml.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2015 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.
*
*/
#include "plantuml.h"
#include "util.h"
#include "portable.h"
#include "config.h"
#include "doxygen.h"
#include "message.h"
#include "debug.h"
#include "fileinfo.h"
#include "dir.h"
#include "indexlist.h"
QCString PlantumlManager::writePlantUMLSource(const QCString &outDirArg,const QCString &fileName,
const QCString &content,OutputFormat format, const QCString &engine,
const QCString &srcFile,int srcLine,bool inlineCode)
{
QCString baseName;
QCString puName;
QCString imgName;
QCString outDir(outDirArg);
static int umlindex=1;
Debug::print(Debug::Plantuml,0,"*** %s fileName: %s\n","writePlantUMLSource",qPrint(fileName));
Debug::print(Debug::Plantuml,0,"*** %s outDir: %s\n","writePlantUMLSource",qPrint(outDir));
// strip any trailing slashes and backslashes
size_t l = 0;
while ((l=outDir.length())>0 && (outDir.at(l-1)=='/' || outDir.at(l-1)=='\\'))
{
outDir = outDir.left(l-1);
}
if (fileName.isEmpty()) // generate name
{
puName = "inline_umlgraph_"+QCString().setNum(umlindex);
baseName = outDir+"/inline_umlgraph_"+QCString().setNum(umlindex++);
}
else // user specified name
{
baseName = fileName;
int i=baseName.findRev('.');
if (i!=-1) baseName = baseName.left(i);
puName = baseName;
baseName.prepend(outDir+"/");
}
switch (format)
{
case PUML_BITMAP:
imgName =puName+".png";
break;
case PUML_EPS:
imgName =puName+".eps";
break;
case PUML_SVG:
imgName =puName+".svg";
break;
}
Debug::print(Debug::Plantuml,0,"*** %s baseName: %s\n","writePlantUMLSource",qPrint(baseName));
Debug::print(Debug::Plantuml,0,"*** %s puName: %s\n","writePlantUMLSource",qPrint(puName));
Debug::print(Debug::Plantuml,0,"*** %s imgName: %s\n","writePlantUMLSource",qPrint(imgName));
QCString text;
if (inlineCode) text = "@start"+engine+" "+imgName+"\n";
text.reserve(text.length()+content.length()+100); // add room for image name and end marker
const char *p = content.data();
if (p)
{
char c = 0;
bool insideComment = false;
bool initial = true;
while ((c=*p++))
{
text+=c;
switch (c)
{
case '\'': insideComment=true; break;
case '\n': insideComment=false; break;
case '\t': break;
case ' ': break;
case '@':
if (initial && qstrncmp(p,"start",5)==0) // @start...
{
while ((c=*p++) && isId(c)) text+=c;
// insert the image name
text+=' ';
text+=imgName;
if (c) text+=c;
}
break;
default:
if (!insideComment) initial=false;
break;
}
}
text+='\n';
}
if (inlineCode) text +="@end"+engine+"\n";
//printf("content\n====\n%s\n=====\n->\n-----\n%s\n------\n",qPrint(content),qPrint(text));
QCString qcOutDir(substitute(outDir,"\\","/"));
uint32_t pos = qcOutDir.findRev("/");
QCString generateType(qcOutDir.right(qcOutDir.length() - (pos + 1)) );
Debug::print(Debug::Plantuml,0,"*** %s generateType: %s\n","writePlantUMLSource",qPrint(generateType));
PlantumlManager::instance().insert(generateType.str(),puName.str(),outDir,format,text,srcFile,srcLine);
Debug::print(Debug::Plantuml,0,"*** %s generateType: %s\n","writePlantUMLSource",qPrint(generateType));
return baseName;
}
void PlantumlManager::generatePlantUMLOutput(const QCString &baseName,const QCString &/* outDir */,OutputFormat format)
{
QCString imgName = baseName;
// The basename contains path, we need to strip the path from the filename in order
// to create the image file name which should be included in the index.qhp (Qt help index file).
int i = imgName.findRev('/');
if (i!=-1) // strip path
{
imgName=imgName.mid(i+1);
}
switch (format)
{
case PUML_BITMAP:
imgName+=".png";
break;
case PUML_EPS:
imgName+=".eps";
break;
case PUML_SVG:
imgName+=".svg";
break;
}
Doxygen::indexList->addImageFile(imgName);
}
//--------------------------------------------------------------------
PlantumlManager &PlantumlManager::instance()
{
static PlantumlManager theInstance;
return theInstance;
}
PlantumlManager::PlantumlManager()
{
}
static void runPlantumlContent(const PlantumlManager::FilesMap &plantumlFiles,
const PlantumlManager::ContentMap &plantumlContent,
PlantumlManager::OutputFormat format)
{
/* example : running: java -Djava.awt.headless=true
-jar "/usr/local/bin/plantuml.jar"
-o "test_doxygen/DOXYGEN_OUTPUT/html"
-tpng
"test_doxygen/DOXYGEN_OUTPUT/html/A.pu"
-charset UTF-8
outDir:test_doxygen/DOXYGEN_OUTPUT/html
test_doxygen/DOXYGEN_OUTPUT/html/A
*/
int exitCode = 0;
QCString plantumlJarPath = Config_getString(PLANTUML_JAR_PATH);
QCString plantumlConfigFile = Config_getString(PLANTUML_CFG_FILE);
QCString pumlExe = "java";
QCString pumlArgs = "";
QCString pumlType = "";
QCString pumlOutDir = "";
const StringVector &pumlIncludePathList = Config_getList(PLANTUML_INCLUDE_PATH);
{
auto it = pumlIncludePathList.begin();
if (it!=pumlIncludePathList.end())
{
pumlArgs += "-Dplantuml.include.path=\"";
pumlArgs += it->c_str();
++it;
}
while (it!=pumlIncludePathList.end())
{
pumlArgs += Portable::pathListSeparator();
pumlArgs += it->c_str();
++it;
}
}
if (!pumlIncludePathList.empty()) pumlArgs += "\" ";
pumlArgs += "-Djava.awt.headless=true -jar \""+plantumlJarPath+"\" ";
if (!plantumlConfigFile.isEmpty())
{
pumlArgs += "-config \"";
pumlArgs += plantumlConfigFile;
pumlArgs += "\" ";
}
// the -graphvizdot option expects a relative or absolute path to the dot executable, so
// we need to use the unverified DOT_PATH option and check if it points to an existing file.
QCString dotPath = Config_getString(DOT_PATH);
FileInfo dp(dotPath.str());
if (Config_getBool(HAVE_DOT) && dp.exists() && dp.isFile())
{
pumlArgs += "-graphvizdot \"";
pumlArgs += dotPath;
pumlArgs += "\" ";
}
switch (format)
{
case PlantumlManager::PUML_BITMAP:
pumlType="png";
break;
case PlantumlManager::PUML_EPS:
pumlType="eps";
break;
case PlantumlManager::PUML_SVG:
pumlType="svg";
break;
}
{
for (const auto &[name,nb] : plantumlContent)
{
if (nb.content.isEmpty()) continue;
QCString pumlArguments = pumlArgs;
msg("Generating PlantUML %s Files in %s\n",qPrint(pumlType),name.c_str());
pumlArguments+="-o \"";
pumlArguments+=nb.outDir;
pumlArguments+="\" ";
pumlArguments+="-charset UTF-8 -t";
pumlArguments+=pumlType;
pumlArguments+=" ";
QCString puFileName("");
puFileName+=nb.outDir;
puFileName+="/";
pumlOutDir=puFileName;
puFileName+="inline_umlgraph_";
puFileName+=pumlType;
puFileName+=name.c_str();
puFileName+=".pu";
pumlArguments+="\"";
pumlArguments+=puFileName;
pumlArguments+="\" ";
QCString cachedContent;
FileInfo fi(puFileName.str());
if (fi.exists())
{
cachedContent = fileToString(puFileName);
}
std::ofstream file = Portable::openOutputStream(puFileName);
if (!file.is_open())
{
err_full(nb.srcFile,nb.srcLine,"Could not open file %s for writing",puFileName.data());
}
file.write( nb.content.data(), nb.content.length() );
file.close();
Debug::print(Debug::Plantuml,0,"*** PlantumlManager::runPlantumlContent Running Plantuml arguments:%s\n",qPrint(pumlArguments));
if (cachedContent == nb.content) continue;
if ((exitCode=Portable::system(pumlExe.data(),pumlArguments.data(),TRUE))!=0)
{
err_full(nb.srcFile,nb.srcLine,"Problems running PlantUML. Verify that the command 'java -jar \"%s\" -h' works from the command line. Exit code: %d.",
plantumlJarPath.data(),exitCode);
}
if ( (format==PlantumlManager::PUML_EPS) && (Config_getBool(USE_PDFLATEX)) )
{
Debug::print(Debug::Plantuml,0,"*** %s Running epstopdf\n","PlantumlManager::runPlantumlContent");
auto files_kv = plantumlFiles.find(name);
if (files_kv!=plantumlFiles.end())
{
for (const auto &str : files_kv->second)
{
const int maxCmdLine = 40960;
QCString epstopdfArgs(maxCmdLine, QCString::ExplicitSize);
epstopdfArgs.sprintf("\"%s%s.eps\" --outfile=\"%s%s.pdf\"",
pumlOutDir.data(),str.c_str(), pumlOutDir.data(),str.c_str());
if ((exitCode=Portable::system("epstopdf",epstopdfArgs.data()))!=0)
{
err_full(nb.srcFile,nb.srcLine,"Problems running epstopdf. Check your TeX installation! Exit code: %d.",exitCode);
}
else
{
Dir().remove(pumlOutDir.str()+str+".eps");
}
}
}
}
}
}
}
void PlantumlManager::run()
{
Debug::print(Debug::Plantuml,0,"*** %s\n","PlantumlManager::run");
runPlantumlContent(m_pngPlantumlFiles, m_pngPlantumlContent, PUML_BITMAP);
runPlantumlContent(m_svgPlantumlFiles, m_svgPlantumlContent, PUML_SVG);
runPlantumlContent(m_epsPlantumlFiles, m_epsPlantumlContent, PUML_EPS);
}
static void print(const PlantumlManager::FilesMap &plantumlFiles)
{
if (Debug::isFlagSet(Debug::Plantuml))
{
for (const auto &[key,list] : plantumlFiles)
{
Debug::print(Debug::Plantuml,0,"*** PlantumlManager::print Files PlantumlFiles key:%s size:%zu\n",key.c_str(),list.size());
for (const auto &s : list)
{
Debug::print(Debug::Plantuml,0,"*** PlantumlManager::print list:%s\n",s.c_str());
}
}
}
}
static void print(const PlantumlManager::ContentMap &plantumlContent)
{
if (Debug::isFlagSet(Debug::Plantuml))
{
for (const auto &[key,content] : plantumlContent)
{
Debug::print(Debug::Plantuml,0,"*** PlantumlManager::print Content PlantumlContent key: %s\n",key.c_str());
Debug::print(Debug::Plantuml,0,"*** PlantumlManager::print Content:\n%s\n",content.content.data());
}
}
}
static void addPlantumlFiles(PlantumlManager::FilesMap &plantumlFiles,
const std::string &key, const std::string &value)
{
auto kv = plantumlFiles.find(key);
if (kv==plantumlFiles.end())
{
kv = plantumlFiles.emplace(key,StringVector()).first;
}
kv->second.push_back(value);
}
static void addPlantumlContent(PlantumlManager::ContentMap &plantumlContent,
const std::string &key, const QCString &outDir, const QCString &puContent,
const QCString &srcFile,int srcLine)
{
auto kv = plantumlContent.find(key);
if (kv==plantumlContent.end())
{
kv = plantumlContent.emplace(key,PlantumlContent("",outDir,srcFile,srcLine)).first;
}
kv->second.content+=puContent;
}
void PlantumlManager::insert(const std::string &key, const std::string &value,
const QCString &outDir,OutputFormat format,const QCString &puContent,
const QCString &srcFile,int srcLine)
{
Debug::print(Debug::Plantuml,0,"*** PlantumlManager::insert key:%s ,value:%s\n",qPrint(key),qPrint(value));
switch (format)
{
case PUML_BITMAP:
addPlantumlFiles(m_pngPlantumlFiles,key,value);
print(m_pngPlantumlFiles);
addPlantumlContent(m_pngPlantumlContent,key,outDir,puContent,srcFile,srcLine);
print(m_pngPlantumlContent);
break;
case PUML_EPS:
addPlantumlFiles(m_epsPlantumlFiles,key,value);
print(m_epsPlantumlFiles);
addPlantumlContent(m_epsPlantumlContent,key,outDir,puContent,srcFile,srcLine);
print(m_epsPlantumlContent);
break;
case PUML_SVG:
addPlantumlFiles(m_svgPlantumlFiles,key,value);
print(m_svgPlantumlFiles);
addPlantumlContent(m_svgPlantumlContent,key,outDir,puContent,srcFile,srcLine);
print(m_svgPlantumlContent);
break;
}
}
//--------------------------------------------------------------------
| 13,077
|
C++
|
.cpp
| 363
| 29.950413
| 158
| 0.632139
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,426
|
rtfgen.cpp
|
doxygen_doxygen/src/rtfgen.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 by Parker Waechter & Dimitri van Heesch.
*
* Style sheet additions by Alexander Bartolich
*
* 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.
*
*/
#include <mutex>
#include <stdlib.h>
#include <algorithm>
#include <unordered_map>
#include "rtfgen.h"
#include "config.h"
#include "message.h"
#include "doxygen.h"
#include "util.h"
#include "diagram.h"
#include "language.h"
#include "dot.h"
#include "dotcallgraph.h"
#include "dotclassgraph.h"
#include "dotdirdeps.h"
#include "dotincldepgraph.h"
#include "version.h"
#include "pagedef.h"
#include "rtfstyle.h"
#include "rtfdocvisitor.h"
#include "docparser.h"
#include "dirdef.h"
#include "vhdldocgen.h"
#include "portable.h"
#include "groupdef.h"
#include "classlist.h"
#include "filename.h"
#include "namespacedef.h"
#include "dir.h"
#include "utf8.h"
#include "debug.h"
#include "datetime.h"
#include "outputlist.h"
#include "moduledef.h"
//#define DBG_RTF(x) x;
#define DBG_RTF(x)
static StringSet removeSet;
static QCString dateToRTFDateString()
{
auto tm = getCurrentDateTime();
QCString result;
switch (Config_getEnum(TIMESTAMP))
{
case TIMESTAMP_t::YES:
case TIMESTAMP_t::DATETIME:
result.sprintf("\\yr%d\\mo%d\\dy%d\\hr%d\\min%d\\sec%d",
tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
break;
case TIMESTAMP_t::DATE:
result.sprintf("\\yr%d\\mo%d\\dy%d",
tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday);
break;
case TIMESTAMP_t::NO:
return "";
}
return "{\\creatim " + result + "}\n";
}
static QCString docifyToString(const QCString &str)
{
QCString result;
result.reserve(str.length());
if (!str.isEmpty())
{
const char *p=str.data();
while (*p)
{
char c=*p++;
switch (c)
{
case '{': result += "\\{"; break;
case '}': result += "\\}"; break;
case '\\': result += "\\\\"; break;
default: result += c; break;
}
}
}
return result;
}
static QCString makeIndexName(const QCString &s,int i)
{
QCString result=s;
result+=static_cast<char>(i+'0');
return result;
}
//------------------------------------------------------------------------------------------------
RTFCodeGenerator::RTFCodeGenerator(TextStream *t) : m_t(t)
{
}
void RTFCodeGenerator::writeCodeLink(CodeSymbolType,
const QCString &ref,const QCString &f,
const QCString &anchor,const QCString &name,
const QCString &)
{
m_col+=name.length();
if (m_hide) return;
if (ref.isEmpty() && Config_getBool(RTF_HYPERLINKS))
{
QCString refName;
if (!f.isEmpty())
{
refName+=stripPath(f);
}
if (!anchor.isEmpty())
{
refName+='_';
refName+=anchor;
}
*m_t << "{\\field {\\*\\fldinst { HYPERLINK \\\\l \"";
*m_t << rtfFormatBmkStr(refName);
*m_t << "\" }{}";
*m_t << "}{\\fldrslt {\\cs37\\ul\\cf2 ";
codify(name);
*m_t << "}}}\n";
}
else
{
codify(name);
}
}
void RTFCodeGenerator::codify(const QCString &str)
{
// note that RTF does not have a "verbatim", so "\n" means
// nothing... add a "newParagraph()";
const int tabSize = Config_getInt(TAB_SIZE);
if (!str.isEmpty())
{
char c;
const char *p=str.data();
if (m_hide)
{
m_col = updateColumnCount(p,m_col);
}
else
{
while ((c=*p++))
{
switch(c)
{
case '\t': {
int spacesToNextTabStop = tabSize - (m_col%tabSize);
while (spacesToNextTabStop--)
{
if (m_col>=m_stripIndentAmount) *m_t << " ";
m_col++;
}
}
break;
case ' ': if (m_col>=m_stripIndentAmount) *m_t << " ";
m_col++;
break;
case '\n': *m_t << "\\par\n";
m_col=0;
break;
case '{': *m_t << "\\{"; m_col++; break;
case '}': *m_t << "\\}"; m_col++; break;
case '\\': *m_t << "\\\\"; m_col++; break;
default: p=writeUTF8Char(*m_t,p-1); m_col++; break;
}
}
}
}
}
void RTFCodeGenerator::stripCodeComments(bool b)
{
m_stripCodeComments = b;
}
void RTFCodeGenerator::startSpecialComment()
{
m_hide = m_stripCodeComments;
}
void RTFCodeGenerator::endSpecialComment()
{
m_hide = false;
}
void RTFCodeGenerator::setStripIndentAmount(size_t amount)
{
m_stripIndentAmount = amount;
}
void RTFCodeGenerator::startCodeFragment(const QCString &)
{
DBG_RTF(*m_t << "{\\comment (startCodeFragment) }\n")
*m_t << "{\n";
*m_t << "\\par\n";
*m_t << rtf_Style_Reset << rtf_Code_DepthStyle();
}
void RTFCodeGenerator::endCodeFragment(const QCString &)
{
endCodeLine();
DBG_RTF(*m_t << "{\\comment (endCodeFragment) }\n")
*m_t << "}\n";
//m_omitParagraph = TRUE;
}
void RTFCodeGenerator::writeLineNumber(const QCString &ref,const QCString &fileName,const QCString &anchor,int l,bool writeLineAnchor)
{
if (m_hide) return;
bool rtfHyperlinks = Config_getBool(RTF_HYPERLINKS);
m_doxyCodeLineOpen = true;
if (Config_getBool(SOURCE_BROWSER))
{
QCString lineNumber;
lineNumber.sprintf("%05d",l);
QCString lineAnchor;
if (!m_sourceFileName.isEmpty())
{
lineAnchor.sprintf("_l%05d",l);
lineAnchor.prepend(stripExtensionGeneral(stripPath(m_sourceFileName), ".rtf"));
}
bool showTarget = rtfHyperlinks && !lineAnchor.isEmpty() && writeLineAnchor;
if (showTarget)
{
*m_t << "{\\bkmkstart ";
*m_t << rtfFormatBmkStr(lineAnchor);
*m_t << "}";
*m_t << "{\\bkmkend ";
*m_t << rtfFormatBmkStr(lineAnchor);
*m_t << "}\n";
}
if (!fileName.isEmpty())
{
writeCodeLink(CodeSymbolType::Default,ref,fileName,anchor,lineNumber,QCString());
}
else
{
*m_t << lineNumber;
}
*m_t << " ";
}
else
{
*m_t << l << " ";
}
m_col=0;
}
void RTFCodeGenerator::startCodeLine(int)
{
if (m_hide) return;
m_doxyCodeLineOpen = true;
m_col=0;
}
void RTFCodeGenerator::endCodeLine()
{
if (m_hide) return;
if (m_doxyCodeLineOpen) *m_t << "\\par\n";
m_doxyCodeLineOpen = false;
}
void RTFCodeGenerator::startFontClass(const QCString &name)
{
if (m_hide) return;
int cod = 2;
static const std::unordered_map<std::string,int> map {
{ "keyword", 17 },
{ "keywordtype", 18 },
{ "keywordflow", 19 },
{ "comment", 20 },
{ "preprocessor", 21 },
{ "stringliteral", 22 },
{ "charliteral", 23 },
{ "vhdldigit", 24 },
{ "vhdlchar", 25 },
{ "vhdlkeyword", 26 },
{ "vhdllogic", 27 }
};
auto it = map.find(name.str());
if (it != map.end())
{
cod = it->second;
}
*m_t << "{\\cf" << cod << " ";
}
void RTFCodeGenerator::endFontClass()
{
if (m_hide) return;
*m_t << "}";
}
QCString RTFCodeGenerator::rtf_Code_DepthStyle()
{
QCString n=makeIndexName("CodeExample",m_indentLevel);
return rtf_Style[n.str()].reference();
}
void RTFCodeGenerator::setSourceFileName(const QCString &name)
{
m_sourceFileName = name;
}
//------------------------------------------------------------------------------------------------
RTFGenerator::RTFGenerator()
: OutputGenerator(Config_getString(RTF_OUTPUT))
, m_codeList(std::make_unique<OutputCodeList>())
{
m_codeGen = m_codeList->add<RTFCodeGenerator>(&m_t);
}
RTFGenerator::RTFGenerator(const RTFGenerator &og) : OutputGenerator(og.m_dir), OutputGenIntf()
{
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<RTFCodeGenerator>(OutputType::RTF);
m_codeGen->setTextStream(&m_t);
m_bstartedBody = og.m_bstartedBody;
m_omitParagraph = og.m_omitParagraph;
m_numCols = og.m_numCols;
m_relPath = og.m_relPath;
m_indentLevel = og.m_indentLevel;
m_listItemInfo = og.m_listItemInfo;
}
RTFGenerator &RTFGenerator::operator=(const RTFGenerator &og)
{
if (this!=&og)
{
m_dir = og.m_dir;
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<RTFCodeGenerator>(OutputType::RTF);
m_codeGen->setTextStream(&m_t);
m_bstartedBody = og.m_bstartedBody;
m_omitParagraph = og.m_omitParagraph;
m_numCols = og.m_numCols;
m_relPath = og.m_relPath;
m_indentLevel = og.m_indentLevel;
m_listItemInfo = og.m_listItemInfo;
}
return *this;
}
RTFGenerator::~RTFGenerator() = default;
void RTFGenerator::addCodeGen(OutputCodeList &list)
{
list.add<RTFCodeGeneratorDefer>(m_codeGen);
}
void RTFGenerator::setRelativePath(const QCString &path)
{
m_relPath = path;
}
void RTFGenerator::setSourceFileName(const QCString &name)
{
m_codeGen->setSourceFileName(name);
}
void RTFGenerator::writeStyleSheetFile(TextStream &t)
{
t << "# Generated by doxygen " << getDoxygenVersion() << "\n\n";
t << "# This file describes styles used for generating RTF output.\n";
t << "# All text after a hash (#) is considered a comment and will be ignored.\n";
t << "# Remove a hash to activate a line.\n\n";
for (int i=0 ; rtf_Style_Default[i].reference!=nullptr ; i++ )
{
t << "# " << rtf_Style_Default[i].name << " = "
<< rtf_Style_Default[i].reference
<< rtf_Style_Default[i].definition << "\n";
}
}
void RTFGenerator::writeExtensionsFile(TextStream &t)
{
t << "# Generated by doxygen " << getDoxygenVersion() << "\n\n";
t << "# This file describes extensions used for generating RTF output.\n";
t << "# All text after a hash (#) is considered a comment and will be ignored.\n";
t << "# Remove a hash to activate a line.\n\n";
t << "# Overrides the project title.\n";
t << "#Title = \n\n";
t << "# Name of the company that produced this document.\n";
t << "#Company = \n\n";
t << "# Filename of a company or project logo.\n";
t << "#LogoFilename = \n\n";
t << "# Author of the document.\n";
t << "#Author = \n\n";
t << "# Type of document (e.g. Design Specification, User Manual, etc.).\n";
t << "#DocumentType = \n\n";
t << "# Document tracking number.\n";
t << "#DocumentId = \n\n";
t << "# Name of the author's manager.\n";
t << "# This field is not displayed in the document itself, but it is \n";
t << "# available in the information block of the rtf file. In Microsoft \n";
t << "# Word, it is available under File:Properties.\n";
t << "#Manager = \n\n";
t << "# Subject of the document.\n";
t << "# This field is not displayed in the document itself, but it is \n";
t << "# available in the information block of the rtf file. In Microsoft \n";
t << "# Word, it is available under File:Properties.\n";
t << "#Subject = \n\n";
t << "# Comments regarding the document.\n";
t << "# This field is not displayed in the document itself, but it is \n";
t << "# available in the information block of the rtf file. In Microsoft \n";
t << "# Word, it is available under File:Properties.\n";
t << "#Comments = \n\n";
t << "# Keywords associated with the document.\n";
t << "# This field is not displayed in the document itself, but it is \n";
t << "# available in the information block of the rtf file. In Microsoft \n";
t << "# Word, it is available under File:Properties.\n";
t << "#Keywords = \n\n";
}
void RTFGenerator::init()
{
QCString dir=Config_getString(RTF_OUTPUT);
Dir d(dir.str());
if (!d.exists() && !d.mkdir(dir.str()))
{
term("Could not create output directory %s\n",qPrint(dir));
}
// first duplicate strings of rtf_Style_Default
const struct Rtf_Style_Default* def = rtf_Style_Default;
while (def->reference)
{
if (def->definition == nullptr)
{
err("Internal: rtf_Style_Default[%s] has no definition.\n", def->name);
}
else
{
rtf_Style.emplace(def->name, StyleData(def->reference, def->definition));
}
def++;
}
// overwrite some (or all) definitions from file
QCString rtfStyleSheetFile = Config_getString(RTF_STYLESHEET_FILE);
if (!rtfStyleSheetFile.isEmpty())
{
loadStylesheet(rtfStyleSheetFile, rtf_Style);
}
// If user has defined an extension file, load its contents.
QCString rtfExtensionsFile = Config_getString(RTF_EXTENSIONS_FILE);
if (!rtfExtensionsFile.isEmpty())
{
loadExtensions(rtfExtensionsFile);
if (!rtf_logoFilename.isEmpty())
{
FileInfo fi(rtf_logoFilename.str());
if (!fi.exists())
{
err("Logo '%s' specified by 'LogoFilename' in the rtf extension file '%s' does not exist!\n",
qPrint(rtf_logoFilename), qPrint(rtfExtensionsFile));
rtf_logoFilename = "";
}
else
{
QCString destFileName = Config_getString(RTF_OUTPUT)+"/"+fi.fileName();
copyFile(rtf_logoFilename,destFileName);
rtf_logoFilename = fi.fileName();
}
}
}
createSubDirs(d);
}
void RTFGenerator::cleanup()
{
QCString dname = Config_getString(RTF_OUTPUT);
Dir d(dname.str());
clearSubDirs(d);
}
void RTFGenerator::beginRTFDocument()
{
/* all the included RTF files should begin with the
* same header
*/
m_t << "{\\rtf1\\ansi\\ansicpg" << theTranslator->trRTFansicp();
m_t << "\\uc1 \\deff0\\deflang1033\\deflangfe1033\n";
DBG_RTF(m_t << "{\\comment Beginning font list}\n")
m_t << "{\\fonttbl ";
m_t << "{\\f0\\froman\\fcharset" << theTranslator->trRTFCharSet();
m_t << "\\fprq2{\\*\\panose 02020603050405020304}Times New Roman;}\n";
m_t << "{\\f1\\fswiss\\fcharset" << theTranslator->trRTFCharSet();
m_t << "\\fprq2{\\*\\panose 020b0604020202020204}Arial;}\n";
m_t << "{\\f2\\fmodern\\fcharset" << theTranslator->trRTFCharSet();
m_t << "\\fprq1{\\*\\panose 02070309020205020404}Courier New;}\n";
m_t << "{\\f3\\froman\\fcharset2\\fprq2{\\*\\panose 05050102010706020507}Symbol;}\n";
m_t << "}\n";
DBG_RTF(m_t << "{\\comment begin colors}\n")
m_t << "{\\colortbl;";
m_t << "\\red0\\green0\\blue0;";
m_t << "\\red0\\green0\\blue255;";
m_t << "\\red0\\green255\\blue255;";
m_t << "\\red0\\green255\\blue0;";
m_t << "\\red255\\green0\\blue255;";
m_t << "\\red255\\green0\\blue0;";
m_t << "\\red255\\green255\\blue0;";
m_t << "\\red255\\green255\\blue255;";
m_t << "\\red0\\green0\\blue128;";
m_t << "\\red0\\green128\\blue128;";
m_t << "\\red0\\green128\\blue0;";
m_t << "\\red128\\green0\\blue128;";
m_t << "\\red128\\green0\\blue0;";
m_t << "\\red128\\green128\\blue0;";
m_t << "\\red128\\green128\\blue128;";
m_t << "\\red192\\green192\\blue192;";
// code highlighting colors. Note order is important see also RTFGenerator::startFontClass
m_t << "\\red0\\green128\\blue0;"; // keyword = index 17
m_t << "\\red96\\green64\\blue32;"; // keywordtype
m_t << "\\rede0\\green128\\blue0;"; // keywordflow
m_t << "\\red128\\green0\\blue0;"; // comment
m_t << "\\red128\\green96\\blue32;"; // preprocessor
m_t << "\\red0\\green32\\blue128;"; // stringliteral
m_t << "\\red0\\green128\\blue128;"; // charliteral
m_t << "\\red255\\green0\\blue255;"; // vhdldigit
m_t << "\\red0\\green0\\blue0;"; // vhdlchar
m_t << "\\red112\\green0\\blue112;"; // vhdlkeyword
m_t << "\\red255\\green0\\blue0;"; // vhdllogic
m_t << "}\n";
DBG_RTF(m_t << "{\\comment Beginning style list}\n")
m_t << "{\\stylesheet\n";
m_t << "{\\widctlpar\\adjustright \\fs20\\cgrid \\snext0 Normal;}\n";
// set the paper dimensions according to PAPER_TYPE
auto paperType = Config_getEnum(PAPER_TYPE);
m_t << "{";
switch (paperType)
{
// width & height values are inches * 1440
case PAPER_TYPE_t::a4: m_t << "\\paperw11900\\paperh16840"; break;
case PAPER_TYPE_t::letter: m_t << "\\paperw12240\\paperh15840"; break;
case PAPER_TYPE_t::legal: m_t << "\\paperw12240\\paperh20160"; break;
case PAPER_TYPE_t::executive: m_t << "\\paperw10440\\paperh15120"; break;
}
m_t << "\\margl1800\\margr1800\\margt1440\\margb1440\\gutter0\\ltrsect}\n";
// sort styles ascending by \s-number via an intermediate QArray
unsigned maxIndex = 0;
for (const auto &[name,data] : rtf_Style)
{
uint32_t index = data.index();
if (index > maxIndex) maxIndex = index;
}
std::vector<const StyleData*> array(maxIndex + 1, nullptr);
ASSERT(maxIndex < array.size());
for (const auto &[name,data] : rtf_Style)
{
uint32_t index = data.index();
if (array[index] != nullptr)
{
err("Style '%s' redefines \\s%d.\n", name.c_str(), index);
}
array[index] = &data;
}
// write array elements
size_t size = array.size();
for(size_t i = 0; i < size; i++)
{
const StyleData *pStyle = array[i];
if (pStyle)
{
m_t << "{" << pStyle->reference() << pStyle->definition() << ";}\n";
}
}
m_t << "}\n";
// place to write rtf_Table_Default
int id = -1;
m_t << "{\\*\\listtable" << "\n";
for (int i=0 ; rtf_Table_Default[i].definition ; i++ )
{
if (id != rtf_Table_Default[i].id)
{
if (id != -1)
{
m_t << "\\listid" << id << "}" << "\n";
}
id = rtf_Table_Default[i].id;
m_t << "{\\list\\listtemplateid" << rtf_Table_Default[i].id << "\n";
}
m_t << "{ " << rtf_Table_Default[i].definition << " }" << "\n";
}
m_t << "\\listid" << id << "}" << "\n";
m_t << "}" <<"\n";
m_t << "{\\listoverridetable" <<"\n";
id = -1;
for (int i=0 ; rtf_Table_Default[i].definition ; i++ )
{
if (id != rtf_Table_Default[i].id)
{
id = rtf_Table_Default[i].id;
m_t << "{\\listoverride\\listid" << id << "\\listoverridecount0\\ls" << id << "}" << "\n";
}
}
m_t << "}" << "\n";
// this comment is needed for postprocessing!
m_t << "{\\comment begin body}\n";
}
void RTFGenerator::beginRTFChapter()
{
m_t << "\n";
DBG_RTF(m_t << "{\\comment BeginRTFChapter}\n")
m_t << rtf_Style_Reset;
// if we are compact, no extra page breaks...
if (Config_getBool(COMPACT_RTF))
{
// m_t << "\\sect\\sectd\\sbknone\n";
m_t << "\\sect\\sbknone\n";
rtfwriteRuler_thick();
}
else
m_t << "\\sect\\sbkpage\n";
//m_t << "\\sect\\sectd\\sbkpage\n";
m_t << rtf_Style["Heading1"].reference() << "\n";
}
void RTFGenerator::beginRTFSection()
{
m_t << "\n";
DBG_RTF(m_t << "{\\comment BeginRTFSection}\n")
m_t << rtf_Style_Reset;
// if we are compact, no extra page breaks...
if (Config_getBool(COMPACT_RTF))
{
m_t << "\\sect\\sbknone\n";
rtfwriteRuler_emboss();
}
else
{
m_t << "\\sect\\sbkpage\n";
}
int level = 2 + m_hierarchyLevel;
m_t << rtf_Style[QCString().sprintf("Heading%d", level).str()].reference() << "\n";
}
void RTFGenerator::startFile(const QCString &name,const QCString &,const QCString &,int,int hierarchyLevel)
{
//setEncoding(QCString().sprintf("CP%s",theTranslator->trRTFansicp()));
QCString fileName=name;
m_relPath = relativePathToRoot(fileName);
m_hierarchyLevel = hierarchyLevel;
if (!fileName.endsWith(".rtf")) fileName+=".rtf";
startPlainFile(fileName);
setRelativePath(m_relPath);
setSourceFileName(stripPath(fileName));
beginRTFDocument();
}
void RTFGenerator::endFile()
{
DBG_RTF(m_t << "{\\comment endFile}\n")
m_t << "}";
endPlainFile();
setSourceFileName("");
}
void RTFGenerator::startProjectNumber()
{
DBG_RTF(m_t << "{\\comment startProjectNumber }\n")
m_t << " ";
}
void RTFGenerator::endProjectNumber()
{
DBG_RTF(m_t << "{\\comment endProjectNumber }\n")
}
void RTFGenerator::startIndexSection(IndexSection is)
{
//QCString paperName;
//m_indentLevel = 0;
switch (is)
{
case IndexSection::isTitlePageStart:
// basic RTFstart
// get readyfor author etc
m_t << "{\\info \n";
m_t << "{\\title {\\comment ";
break;
case IndexSection::isTitlePageAuthor:
m_t << "}\n";
if (!rtf_subject.isEmpty()) m_t << "{\\subject " << rtf_subject << "}\n";
if (!rtf_comments.isEmpty()) m_t << "{\\comment " << rtf_comments << "}\n";
if (!rtf_company.isEmpty()) m_t << "{\\company " << rtf_company << "}\n";
if (!rtf_author.isEmpty()) m_t << "{\\author " << rtf_author << "}\n";
if (!rtf_manager.isEmpty()) m_t << "{\\manager " << rtf_manager << "}\n";
if (!rtf_documentType.isEmpty()) m_t << "{\\category " << rtf_documentType << "}\n";
if (!rtf_keywords.isEmpty()) m_t << "{\\keywords " << rtf_keywords << "}\n";
m_t << "{\\comment ";
break;
case IndexSection::isMainPage:
//Introduction
beginRTFChapter();
break;
case IndexSection::isTopicIndex:
//Topic Index
beginRTFChapter();
break;
case IndexSection::isModuleIndex:
//Module Index
beginRTFChapter();
break;
case IndexSection::isDirIndex:
//Directory Index
beginRTFChapter();
break;
case IndexSection::isNamespaceIndex:
//Namespace Index
beginRTFChapter();
break;
case IndexSection::isConceptIndex:
//Concept Index
beginRTFChapter();
break;
case IndexSection::isClassHierarchyIndex:
//Hierarchical Index
DBG_RTF(m_t << "{\\comment start classhierarchy}\n")
beginRTFChapter();
break;
case IndexSection::isCompoundIndex:
//Annotated Compound Index
beginRTFChapter();
break;
case IndexSection::isFileIndex:
//Annotated File Index
beginRTFChapter();
break;
case IndexSection::isPageIndex:
//Related Page Index
beginRTFChapter();
break;
case IndexSection::isTopicDocumentation:
{
//Topic Documentation
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (!gd->isReference())
{
beginRTFChapter();
break;
}
}
}
break;
case IndexSection::isModuleDocumentation:
{
//Module Documentation
for (const auto &mod : ModuleManager::instance().modules())
{
if (!mod->isReference() && mod->isPrimaryInterface())
{
beginRTFChapter();
break;
}
}
}
break;
case IndexSection::isDirDocumentation:
{
//Directory Documentation
for (const auto &dd : *Doxygen::dirLinkedMap)
{
if (dd->isLinkableInProject())
{
beginRTFChapter();
break;
}
}
}
break;
case IndexSection::isNamespaceDocumentation:
{
// Namespace Documentation
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject())
{
beginRTFChapter();
break;
}
}
}
break;
case IndexSection::isConceptDocumentation:
{
// Concept Documentation
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject())
{
beginRTFChapter();
break;
}
}
}
break;
case IndexSection::isClassDocumentation:
{
//Compound Documentation
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkableInProject() &&
cd->templateMaster()==nullptr &&
!cd->isEmbeddedInOuterScope() &&
!cd->isAlias()
)
{
beginRTFChapter();
break;
}
}
}
break;
case IndexSection::isFileDocumentation:
{
//File Documentation
bool isFirst=TRUE;
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->isLinkableInProject() || fd->generateSourceFile())
{
if (isFirst)
{
beginRTFChapter();
isFirst=FALSE;
break;
}
}
}
if (!isFirst)
{
break;
}
}
}
break;
case IndexSection::isExampleDocumentation:
{
//Example Documentation
beginRTFChapter();
}
break;
case IndexSection::isPageDocumentation:
break;
case IndexSection::isPageDocumentation2:
break;
case IndexSection::isEndIndex:
break;
}
}
void RTFGenerator::endIndexSection(IndexSection is)
{
bool fortranOpt = Config_getBool(OPTIMIZE_FOR_FORTRAN);
bool vhdlOpt = Config_getBool(OPTIMIZE_OUTPUT_VHDL);
QCString projectName = Config_getString(PROJECT_NAME);
switch (is)
{
case IndexSection::isTitlePageStart:
if (!rtf_title.isEmpty())
// User has overridden document title in extensions file
m_t << "}" << rtf_title;
else
m_t << "}" << projectName;
break;
case IndexSection::isTitlePageAuthor:
{
m_t << " doxygen " << getDoxygenVersion() << ".}\n";
m_t << dateToRTFDateString();
DBG_RTF(m_t << "{\\comment end of infoblock}\n");
// setup for this section
m_t << "}";
m_t << rtf_Style_Reset <<"\n";
m_t << "\\sectd\\pgnlcrm\n";
m_t << "{\\footer "<<rtf_Style["Footer"].reference() << "{\\chpgn}}\n";
// the title entry
DBG_RTF(m_t << "{\\comment begin title page}\n")
m_t << rtf_Style_Reset << rtf_Style["SubTitle"].reference() << "\n"; // set to title style
m_t << "\\vertalc\\qc\\par\\par\\par\\par\\par\\par\\par\n";
if (!rtf_logoFilename.isEmpty())
{
m_t << "{\\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"" << rtf_logoFilename;
m_t << "\" \\\\d \\\\*MERGEFORMAT} {\\fldrslt IMAGE }}\\par\\par\n";
}
if (!rtf_company.isEmpty())
{
m_t << rtf_company << "\\par\\par\n";
}
m_t << rtf_Style_Reset << rtf_Style["Title"].reference() << "\n"; // set to title style
if (!rtf_title.isEmpty())
{
// User has overridden document title in extensions file
m_t << "{\\field\\fldedit {\\*\\fldinst TITLE \\\\*MERGEFORMAT}{\\fldrslt " << rtf_title << "}}\\par\n";
}
else
{
auto parser { createDocParser() };
auto ast { validatingParseText(*parser.get(), projectName) };
if (ast)
{
m_t << "{\\field\\fldedit {\\*\\fldinst TITLE \\\\*MERGEFORMAT}{\\fldrslt ";
writeDoc(ast.get(),nullptr,nullptr,0);
m_t << "}}\\par\n";
}
}
m_t << rtf_Style_Reset << rtf_Style["SubTitle"].reference() << "\n"; // set to title style
m_t << "\\par\n";
if (!rtf_documentType.isEmpty())
{
m_t << rtf_documentType << "\\par\n";
}
if (!rtf_documentId.isEmpty())
{
m_t << rtf_documentId << "\\par\n";
}
m_t << "\\par\\par\\par\\par\\par\\par\\par\\par\\par\\par\\par\\par\n";
m_t << rtf_Style_Reset << rtf_Style["SubTitle"].reference() << "\n"; // set to subtitle style
if (!rtf_author.isEmpty())
{
m_t << "{\\field\\fldedit {\\*\\fldinst AUTHOR \\\\*MERGEFORMAT}{\\fldrslt "<< rtf_author << " }}\\par\n";
}
else
{
m_t << "{\\field\\fldedit {\\*\\fldinst AUTHOR \\\\*MERGEFORMAT}{\\fldrslt AUTHOR}}\\par\n";
}
m_t << theTranslator->trVersion() << " " << Config_getString(PROJECT_NUMBER) << "\\par";
switch (Config_getEnum(TIMESTAMP))
{
case TIMESTAMP_t::YES:
case TIMESTAMP_t::DATETIME:
m_t << "{\\field\\fldedit {\\*\\fldinst CREATEDATE \\\\*MERGEFORMAT}"
"{\\fldrslt "<< dateToString(DateTimeType::DateTime) << " }}\\par\n";
break;
case TIMESTAMP_t::DATE:
m_t << "{\\field\\fldedit {\\*\\fldinst CREATEDATE \\\\*MERGEFORMAT}"
"{\\fldrslt "<< dateToString(DateTimeType::Date) << " }}\\par\n";
break;
case TIMESTAMP_t::NO:
break;
}
m_t << "\\page\\page";
DBG_RTF(m_t << "{\\comment End title page}\n")
// table of contents section
DBG_RTF(m_t << "{\\comment Table of contents}\n")
m_t << "\\vertalt\n";
m_t << rtf_Style_Reset << "\n";
m_t << rtf_Style["Heading1"].reference();
m_t << theTranslator->trRTFTableOfContents() << "\\par\n";
m_t << rtf_Style_Reset << "\\par\n";
m_t << "{\\field\\fldedit {\\*\\fldinst TOC \\\\f \\\\*MERGEFORMAT}{\\fldrslt Table of contents}}\\par\n";
m_t << rtf_Style_Reset << "\n";
}
break;
case IndexSection::isMainPage:
if (Doxygen::mainPage)
{
writePageLink(Doxygen::mainPage->getOutputFileBase(), TRUE);
}
break;
case IndexSection::isTopicIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trTopicIndex() << "}\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"topics.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isModuleIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trModuleIndex() << "}\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"modules.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isDirIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trDirIndex() << "}\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"dirs.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isNamespaceIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
if (fortranOpt)
{
m_t << "{\\tc \\v " << theTranslator->trModulesIndex() << "}\n";
}
else
{
m_t << "{\\tc \\v " << theTranslator->trNamespaceIndex() << "}\n";
}
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"namespaces.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isConceptIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trConceptIndex() << "}\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"concepts.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isClassHierarchyIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trHierarchicalIndex() << "}\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"hierarchy.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isCompoundIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
if (fortranOpt)
{
m_t << "{\\tc \\v " << theTranslator->trCompoundIndexFortran() << "}\n";
}
else if (vhdlOpt)
{
m_t << "{\\tc \\v " << theTranslator->trDesignUnitIndex() << "}\n";
}
else
{
m_t << "{\\tc \\v " << theTranslator->trCompoundIndex() << "}\n";
}
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"annotated.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isFileIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trFileIndex() << "}\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"files.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isPageIndex:
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trPageIndex() << "}\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"pages.rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
break;
case IndexSection::isTopicDocumentation:
{
m_t << "{\\tc \\v " << theTranslator->trTopicDocumentation() << "}\n";
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (!gd->isReference() && !gd->isASubGroup())
{
writePageLink(gd->getOutputFileBase(), FALSE);
}
}
}
break;
case IndexSection::isModuleDocumentation:
{
m_t << "{\\tc \\v " << theTranslator->trModuleDocumentation() << "}\n";
for (const auto &mod : ModuleManager::instance().modules())
{
if (!mod->isReference() && mod->isPrimaryInterface())
{
writePageLink(mod->getOutputFileBase(), FALSE);
}
}
}
break;
case IndexSection::isDirDocumentation:
{
bool first=true;
m_t << "{\\tc \\v " << theTranslator->trDirDocumentation() << "}\n";
for (const auto &dd : *Doxygen::dirLinkedMap)
{
if (dd->isLinkableInProject())
{
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!first)
{
beginRTFSection();
}
first=false;
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << dd->getOutputFileBase();
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
}
}
break;
case IndexSection::isNamespaceDocumentation:
{
bool first=true;
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject() && !nd->isAlias())
{
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!first)
{
beginRTFSection();
}
first=false;
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << nd->getOutputFileBase();
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
}
}
break;
case IndexSection::isConceptDocumentation:
{
bool first=true;
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject() && !cd->isAlias())
{
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!first)
{
beginRTFSection();
}
first=false;
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << cd->getOutputFileBase();
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
}
}
break;
case IndexSection::isClassDocumentation:
{
bool first=true;
if (fortranOpt)
{
m_t << "{\\tc \\v " << theTranslator->trTypeDocumentation() << "}\n";
}
else
{
m_t << "{\\tc \\v " << theTranslator->trClassDocumentation() << "}\n";
}
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkableInProject() &&
cd->templateMaster()==nullptr &&
!cd->isEmbeddedInOuterScope() &&
!cd->isAlias()
)
{
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!first)
{
beginRTFSection();
}
first=false;
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << cd->getOutputFileBase();
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
}
}
break;
case IndexSection::isFileDocumentation:
{
bool isFirst=TRUE;
m_t << "{\\tc \\v " << theTranslator->trFileDocumentation() << "}\n";
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->isLinkableInProject())
{
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!isFirst)
{
beginRTFSection();
}
isFirst=FALSE;
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << fd->getOutputFileBase();
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
if (fd->generateSourceFile())
{
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!isFirst)
{
beginRTFSection();
}
isFirst=FALSE;
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << fd->getSourceFileBase();
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
}
}
}
break;
case IndexSection::isExampleDocumentation:
{
//m_t << "}\n";
bool isFirst=true;
m_t << "{\\tc \\v " << theTranslator->trExamples() << "}\n";
for (const auto &pd : *Doxygen::exampleLinkedMap)
{
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!isFirst)
{
beginRTFSection();
}
isFirst=false;
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << pd->getOutputFileBase();
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
}
break;
case IndexSection::isPageDocumentation:
{
m_t << "\\par " << rtf_Style_Reset << "\n";
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (!pd->getGroupDef() && !pd->isReference() && !pd->hasParentPage()
&& Doxygen::mainPage.get() != pd.get())
{
writePageLink(pd->getOutputFileBase(), FALSE);
}
}
}
break;
case IndexSection::isPageDocumentation2:
break;
case IndexSection::isEndIndex:
beginRTFChapter();
m_t << rtf_Style["Heading1"].reference();
m_t << theTranslator->trRTFGeneralIndex() << "\\par \n";
m_t << rtf_Style_Reset << "\n";
m_t << "{\\tc \\v " << theTranslator->trRTFGeneralIndex() << "}\n";
m_t << "{\\field\\fldedit {\\*\\fldinst INDEX \\\\c2 \\\\*MERGEFORMAT}{\\fldrslt INDEX}}\n";
break;
}
}
void RTFGenerator::writePageLink(const QCString &name,bool)
{
m_t << "\\par " << rtf_Style_Reset << "\n";
m_t << "{\\field\\fldedit{\\*\\fldinst INCLUDETEXT \"";
m_t << name;
m_t << ".rtf\" \\\\*MERGEFORMAT}{\\fldrslt includedstuff}}\n";
}
void RTFGenerator::lastIndexPage()
{
DBG_RTF(m_t << "{\\comment Beginning Body of RTF Document}\n")
// end page and setup for rest of document
m_t << "\\sect \\sbkpage \\pgndec \\pgnrestart\n";
m_t << "\\sect \\sectd \\sbknone\n";
// set new footer with arabic numbers
m_t << "{\\footer "<< rtf_Style["Footer"].reference() << "{\\chpgn}}\n";
}
void RTFGenerator::writeStyleInfo(int)
{
}
void RTFGenerator::lineBreak(const QCString &)
{
DBG_RTF(m_t << "{\\comment (lineBreak)}" << "\n")
m_t << "\\par\n";
m_omitParagraph = TRUE;
}
void RTFGenerator::writeString(const QCString &text)
{
m_t << text;
}
void RTFGenerator::startIndexList()
{
DBG_RTF(m_t << "{\\comment (startIndexList)}\n")
m_t << "{\n";
m_t << "\\par\n";
incIndentLevel();
m_t << rtf_Style_Reset << rtf_LCList_DepthStyle() << "\n";
m_omitParagraph = TRUE;
}
void RTFGenerator::endIndexList()
{
DBG_RTF(m_t << "{\\comment (endIndexList)}\n")
if (!m_omitParagraph)
{
m_t << "\\par";
m_omitParagraph = TRUE;
}
m_t << "}";
decIndentLevel();
}
/*! start bullet list */
void RTFGenerator::startItemList()
{
newParagraph();
incIndentLevel();
int level = indentLevel();
DBG_RTF(m_t << "{\\comment (startItemList level=" << level << ") }\n")
m_t << "{";
m_listItemInfo[level].number = 1;
m_listItemInfo[level].isEnum = false;
m_listItemInfo[level].type = '1';
}
/*! end bullet list */
void RTFGenerator::endItemList()
{
newParagraph();
DBG_RTF(m_t << "{\\comment (endItemList level=" << indentLevel() << ")}\n")
m_t << "}";
decIndentLevel();
m_omitParagraph = TRUE;
}
/*! write bullet or enum item */
void RTFGenerator::startItemListItem()
{
DBG_RTF(m_t << "{\\comment (startItemListItem)}\n")
newParagraph();
m_t << rtf_Style_Reset;
int level = indentLevel();
if (m_listItemInfo[level].isEnum)
{
m_t << rtf_EList_DepthStyle() << "\n";
m_t << m_listItemInfo[level].number << ".\\tab ";
m_listItemInfo[level].number++;
}
else
{
m_t << rtf_BList_DepthStyle() << "\n";
}
m_omitParagraph = TRUE;
}
void RTFGenerator::endItemListItem()
{
DBG_RTF(m_t << "{\\comment (endItemListItem)}\n")
}
void RTFGenerator::startIndexItem(const QCString &,const QCString &)
{
DBG_RTF(m_t << "{\\comment (startIndexItem)}\n")
if (!m_omitParagraph)
{
m_t << "\\par\n";
m_omitParagraph = TRUE;
}
}
void RTFGenerator::endIndexItem(const QCString &ref,const QCString &fn)
{
DBG_RTF(m_t << "{\\comment (endIndexItem)}\n")
if (ref.isEmpty() && !fn.isEmpty())
{
m_t << "\\tab ";
writeRTFReference(fn);
m_t << "\n";
}
else
{
m_t << "\n";
}
m_omitParagraph = TRUE;
}
void RTFGenerator::writeStartAnnoItem(const QCString &,const QCString &f,
const QCString &path,const QCString &name)
{
DBG_RTF(m_t << "{\\comment (writeStartAnnoItem)}\n")
m_t << "{\\b ";
if (!path.isEmpty()) docify(path);
if (!f.isEmpty() && Config_getBool(RTF_HYPERLINKS))
{
m_t << "{\\field {\\*\\fldinst { HYPERLINK \\\\l \"";
m_t << rtfFormatBmkStr(stripPath(f));
m_t << "\" }{}";
m_t << "}{\\fldrslt {\\cs37\\ul\\cf2 ";
docify(name);
m_t << "}}}\n";
}
else
{
docify(name);
}
m_t << "} ";
}
void RTFGenerator::startIndexKey()
{
DBG_RTF(m_t << "{\\comment (startIndexKey)}\n")
m_t << "{\\b ";
}
void RTFGenerator::endIndexKey()
{
DBG_RTF(m_t << "{\\comment (endIndexKey)}\n")
}
void RTFGenerator::startIndexValue(bool hasBrief)
{
DBG_RTF(m_t << "{\\comment (startIndexValue)}\n")
m_t << " ";
if (hasBrief) m_t << "(";
}
void RTFGenerator::endIndexValue(const QCString &name,bool hasBrief)
{
DBG_RTF(m_t << "{\\comment (endIndexValue)}\n")
if (hasBrief) m_t << ")";
m_t << "} ";
if (!name.isEmpty())
{
m_t << "\\tab ";
writeRTFReference(name);
m_t << "\n";
}
else
{
m_t << "\n";
}
m_omitParagraph=FALSE;
newParagraph();
}
void RTFGenerator::startCompoundTemplateParams()
{
//beginRTFSubSubSection();
m_t << "\n";
DBG_RTF(m_t << "{\\comment Begin SubSubSection}\n")
m_t << "{\n";
int level = 4 + m_hierarchyLevel;
m_t << rtf_Style_Reset << rtf_Style[QCString().sprintf("Heading%d", level).str()].reference() << "\n";
}
void RTFGenerator::endCompoundTemplateParams()
{
newParagraph();
m_t << "}\n";
}
void RTFGenerator::startTextLink(const QCString &f,const QCString &anchor)
{
if (Config_getBool(RTF_HYPERLINKS))
{
QCString ref;
if (!f.isEmpty())
{
ref+=stripPath(f);
}
if (!anchor.isEmpty())
{
ref+='_';
ref+=anchor;
}
m_t << "{\\field {\\*\\fldinst { HYPERLINK \\\\l \"";
m_t << rtfFormatBmkStr(ref);
m_t << "\" }{}";
m_t << "}{\\fldrslt {\\cs37\\ul\\cf2 ";
}
}
void RTFGenerator::endTextLink()
{
if (Config_getBool(RTF_HYPERLINKS))
{
m_t << "}}}\n";
}
}
static QCString objectLinkToString(const QCString &ref, const QCString &f,
const QCString &anchor, const QCString &text)
{
QCString result;
if (ref.isEmpty() && Config_getBool(RTF_HYPERLINKS))
{
QCString refName;
if (!f.isEmpty())
{
refName+=stripPath(f);
}
if (!anchor.isEmpty())
{
refName+='_';
refName+=anchor;
}
result += "{\\field {\\*\\fldinst { HYPERLINK \\\\l \"";
result += rtfFormatBmkStr(refName);
result += "\" }{}";
result += "}{\\fldrslt {\\cs37\\ul\\cf2 ";
result += docifyToString(text);
result += "}}}\n";
}
else
{
result += "{\\b ";
result += docifyToString(text);
result += "}";
}
return result;
}
void RTFGenerator::writeObjectLink(const QCString &ref, const QCString &f,
const QCString &anchor, const QCString &text)
{
m_t << objectLinkToString(ref,f,anchor,text);
}
void RTFGenerator::startPageRef()
{
m_t << " (";
startEmphasis();
}
void RTFGenerator::endPageRef(const QCString &clname, const QCString &anchor)
{
QCString ref;
if (!clname.isEmpty())
{
ref+=clname;
}
if (!anchor.isEmpty())
{
ref+='_';
ref+=anchor;
}
writeRTFReference(ref);
endEmphasis();
m_t << ")";
}
void RTFGenerator::startTitleHead(const QCString &)
{
DBG_RTF(m_t << "{\\comment startTitleHead}\n")
int level = 2 + m_hierarchyLevel;
QCString heading;
heading.sprintf("Heading%d", level);
// beginRTFSection();
m_t << rtf_Style_Reset << rtf_Style[heading.str()].reference() << "\n";
}
void RTFGenerator::endTitleHead(const QCString &fileName,const QCString &name)
{
DBG_RTF(m_t << "{\\comment endTitleHead}\n")
m_t << "\\par " << rtf_Style_Reset << "\n";
if (!name.isEmpty())
{
// make table of contents entry
int level = 2 + m_hierarchyLevel;
m_t << "{\\tc\\tcl" << level << " \\v ";
docify(name);
m_t << "}\n";
// make an index entry
addIndexItem(name,QCString());
}
if (!fileName.isEmpty())
{
writeAnchor(fileName,QCString());
}
}
void RTFGenerator::startGroupHeader(int extraIndent)
{
DBG_RTF(m_t << "{\\comment startGroupHeader}\n")
m_t << rtf_Style_Reset;
extraIndent += m_hierarchyLevel;
if (extraIndent>=2)
{
m_t << rtf_Style["Heading5"].reference();
}
else if (extraIndent==1)
{
m_t << rtf_Style["Heading4"].reference();
}
else // extraIndent==0
{
m_t << rtf_Style["Heading3"].reference();
}
m_t << "\n";
}
void RTFGenerator::endGroupHeader(int)
{
DBG_RTF(m_t << "{\\comment endGroupHeader}\n")
m_t << "\\par\n";
m_t << rtf_Style_Reset << "\n";
}
void RTFGenerator::startMemberDoc(const QCString &clname,
const QCString &memname,
const QCString &,
const QCString &,
int,
int,
bool showInline)
{
DBG_RTF(m_t << "{\\comment startMemberDoc}\n")
if (!memname.isEmpty() && memname[0]!='@')
{
addIndexItem(memname,clname);
addIndexItem(clname,memname);
}
int level = 4 + m_hierarchyLevel;
if (showInline)
++level;
if (level > 5)
level = 5;
if (level < 1)
level = 1;
m_t << rtf_Style_Reset << rtf_Style[QCString().sprintf("Heading%d", level).str()].reference();
//styleStack.push(rtf_Style_Heading4);
m_t << "{\n";
//printf("RTFGenerator::startMemberDoc() '%s'\n",rtf_Style["Heading4"].reference());
startBold();
m_t << "\n";
}
void RTFGenerator::endMemberDoc(bool)
{
DBG_RTF(m_t << "{\\comment endMemberDoc}\n")
//const QCString &style = styleStack.pop();
//printf("RTFGenerator::endMemberDoc() '%s'\n",style);
//ASSERT(style==rtf_Style["Heading4"].reference());
endBold();
m_t << "}\n";
newParagraph();
}
void RTFGenerator::startDoxyAnchor(const QCString &,const QCString &,
const QCString &,const QCString &,
const QCString &
)
{
DBG_RTF(m_t << "{\\comment startDoxyAnchor}\n")
}
void RTFGenerator::endDoxyAnchor(const QCString &fName,const QCString &anchor)
{
QCString ref;
if (!fName.isEmpty())
{
ref+=stripPath(fName);
}
if (!anchor.isEmpty())
{
ref+='_';
ref+=anchor;
}
DBG_RTF(m_t << "{\\comment endDoxyAnchor}\n")
m_t << "{\\bkmkstart ";
m_t << rtfFormatBmkStr(ref);
m_t << "}\n";
m_t << "{\\bkmkend ";
m_t << rtfFormatBmkStr(ref);
m_t << "}\n";
}
void RTFGenerator::addLabel(const QCString &,const QCString &)
{
DBG_RTF(m_t << "{\\comment addLabel}\n")
}
void RTFGenerator::addIndexItem(const QCString &s1,const QCString &s2)
{
if (!s1.isEmpty())
{
m_t << "{\\xe \\v ";
docify(s1);
if (!s2.isEmpty())
{
m_t << "\\:";
docify(s2);
}
m_t << "}\n";
}
}
void RTFGenerator::startIndent()
{
incIndentLevel();
DBG_RTF(m_t << "{\\comment (startIndent) }\n")
m_t << "{\n";
m_t << rtf_Style_Reset << rtf_CList_DepthStyle() << "\n";
}
void RTFGenerator::endIndent()
{
m_t << "}\n";
decIndentLevel();
}
void RTFGenerator::startMemberDescription(const QCString &,const QCString &,bool)
{
DBG_RTF(m_t << "{\\comment (startMemberDescription)}\n")
m_t << "{\n";
incIndentLevel();
m_t << rtf_Style_Reset << rtf_CList_DepthStyle();
startEmphasis();
}
void RTFGenerator::endMemberDescription()
{
DBG_RTF(m_t << "{\\comment (endMemberDescription)}\n")
endEmphasis();
decIndentLevel();
m_t << "\\par";
m_t << "}\n";
m_omitParagraph = TRUE;
}
void RTFGenerator::startDescForItem()
{
DBG_RTF(m_t << "{\\comment (startDescForItem) }\n")
}
void RTFGenerator::endDescForItem()
{
DBG_RTF(m_t << "{\\comment (endDescForItem) }\n")
}
void RTFGenerator::startSection(const QCString &,const QCString &title,SectionType type)
{
DBG_RTF(m_t << "{\\comment (startSection)}\n")
m_t << "{";
m_t << rtf_Style_Reset;
int num=SectionType::MaxLevel;
switch(type.level())
{
case SectionType::Page: num=2+m_hierarchyLevel; break;
case SectionType::Section: num=3+m_hierarchyLevel; break;
case SectionType::Subsection: // fall through
case SectionType::Subsubsection: // fall through
case SectionType::Paragraph: // fall through
case SectionType::Subparagraph: // fall through
case SectionType::Subsubparagraph: num=4+m_hierarchyLevel; break;
default: ASSERT(0); break;
}
num = std::clamp(num, SectionType::MinLevel, SectionType::MaxLevel);
QCString heading;
heading.sprintf("Heading%d",num);
// set style
m_t << rtf_Style[heading.str()].reference();
// make table of contents entry
m_t << "{\\tc\\tcl" << num << " \\v ";
docify(title);
m_t << "}\n";
}
void RTFGenerator::endSection(const QCString &lab,SectionType)
{
DBG_RTF(m_t << "{\\comment (endSection)}\n")
// make bookmark
m_omitParagraph=FALSE;
newParagraph();
writeAnchor(QCString(),lab);
m_t << "}";
}
void RTFGenerator::docify(const QCString &str)
{
if (str.isEmpty()) return;
m_t << docifyToString(str);
m_omitParagraph = FALSE;
}
void RTFGenerator::writeChar(char c)
{
char cs[2];
cs[0]=c;
cs[1]=0;
docify(cs);
}
void RTFGenerator::startClassDiagram()
{
DBG_RTF(m_t << "{\\comment startClassDiagram }\n")
}
void RTFGenerator::endClassDiagram(const ClassDiagram &d,
const QCString &fileName,const QCString &)
{
newParagraph();
// create a png file
d.writeImage(m_t,dir(),m_relPath,fileName,FALSE);
// display the file
m_t << "{\n";
m_t << rtf_Style_Reset << "\n";
m_t << "\\par\\pard \\qc {\\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"";
m_t << fileName << ".png\"";
m_t << " \\\\d \\\\*MERGEFORMAT}{\\fldrslt IMAGE}}\\par\n";
m_t << "}\n";
}
void RTFGenerator::startMemberItem(const QCString &,MemberItemType,const QCString &)
{
DBG_RTF(m_t << "{\\comment startMemberItem }\n")
m_t << rtf_Style_Reset << rtf_BList_DepthStyle() << "\n"; // set style to appropriate depth
}
void RTFGenerator::endMemberItem(MemberItemType)
{
DBG_RTF(m_t << "{\\comment endMemberItem }\n")
newParagraph();
}
void RTFGenerator::writeAnchor(const QCString &fileName,const QCString &name)
{
QCString anchor;
if (!fileName.isEmpty())
{
anchor+=stripPath(fileName);
}
if (!fileName.isEmpty() && !name.isEmpty())
{
anchor+='_';
}
if (!name.isEmpty())
{
anchor+=name;
}
//printf("writeAnchor(%s->%s)\n",qPrint(anchor),qPrint(rtfFormatBmkStr(anchor)));
DBG_RTF(m_t << "{\\comment writeAnchor (" << anchor << ")}\n")
m_t << "{\\bkmkstart " << rtfFormatBmkStr(anchor) << "}\n";
m_t << "{\\bkmkend " << rtfFormatBmkStr(anchor) << "}\n";
}
void RTFGenerator::writeRTFReference(const QCString &label)
{
m_t << "{\\field\\fldedit {\\*\\fldinst PAGEREF ";
m_t << rtfFormatBmkStr(stripPath(label));
m_t << " \\\\*MERGEFORMAT}{\\fldrslt pagenum}}";
}
void RTFGenerator::writeNonBreakableSpace(int)
{
m_t << "\\~ ";
}
void RTFGenerator::startMemberList()
{
m_t << "\n";
DBG_RTF(m_t << "{\\comment (startMemberList) }\n")
m_t << "{\n";
#ifdef DELETEDCODE
if (!insideTabbing)
m_t << "\\begin{CompactItemize}\n";
#endif
}
void RTFGenerator::endMemberList()
{
DBG_RTF(m_t << "{\\comment (endMemberList) }\n")
m_t << "}\n";
#ifdef DELETEDCODE
if (!insideTabbing)
m_t << "\\end{CompactItemize}\n";
#endif
}
void RTFGenerator::startDescTable(const QCString &title,const bool hasInits)
{
DBG_RTF(m_t << "{\\comment (startDescTable) }\n")
m_t << "{\\par\n";
m_t << "{" << rtf_Style["Heading5"].reference() << "\n";
docify(title);
m_t << ":\\par}\n";
m_t << rtf_Style_Reset << rtf_DList_DepthStyle();
m_t << "\\trowd \\trgaph108\\trleft426\\tblind426"
"\\trbrdrt\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrl\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrb\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrr\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrh\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrv\\brdrs\\brdrw10\\brdrcf15 \n";
int columnPos2[2] = { 25, 100 };
int columnPos3[3] = { 25, 45, 100 };
for (int i=0;i<(hasInits?3:2);i++)
{
m_t << "\\clvertalt\\clbrdrt\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrl\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrb\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrr \\brdrs\\brdrw10\\brdrcf15 "
"\\cltxlrtb "
"\\cellx" << (rtf_pageWidth*(hasInits?columnPos3[i]:columnPos2[i])/100) << "\n";
}
m_t << "\\pard \\widctlpar\\intbl\\adjustright\n";
}
void RTFGenerator::endDescTable()
{
DBG_RTF(m_t << "{\\comment (endDescTable)}\n")
m_t << "}\n";
}
void RTFGenerator::startDescTableRow()
{
}
void RTFGenerator::endDescTableRow()
{
}
void RTFGenerator::startDescTableTitle()
{
DBG_RTF(m_t << "{\\comment (startDescTableTitle) }\n")
m_t << "{";
m_t << rtf_Style["BodyText"].reference();
}
void RTFGenerator::endDescTableTitle()
{
DBG_RTF(m_t << "{\\comment (endDescTableTitle) }\n")
m_t << "\\cell }";
}
void RTFGenerator::startDescTableInit()
{
DBG_RTF(m_t << "{\\comment (startDescTableInit) }" << endl)
m_t << "{";
m_t << rtf_Style["BodyText"].reference();
m_t << "\\qr ";
}
void RTFGenerator::endDescTableInit()
{
DBG_RTF(m_t << "{\\comment (endDescTableInit) }" << endl)
m_t << "\\cell }";
}
void RTFGenerator::startDescTableData()
{
DBG_RTF(m_t << "{\\comment (startDescTableData) }\n")
m_t << "{";
}
void RTFGenerator::endDescTableData()
{
DBG_RTF(m_t << "{\\comment (endDescTableData) }\n")
m_t << "\\cell }{\\row }\n";
}
// a style for list formatted as a "bulleted list"
int RTFGenerator::indentLevel() const
{
return std::min(m_indentLevel,maxIndentLevels-1);
}
void RTFGenerator::incIndentLevel()
{
m_indentLevel++;
if (m_indentLevel>=maxIndentLevels)
{
m_indentLevel = maxIndentLevels-1;
err("Maximum indent level (%d) exceeded while generating RTF output!\n",maxIndentLevels);
}
m_codeGen->setIndentLevel(m_indentLevel);
}
void RTFGenerator::decIndentLevel()
{
m_indentLevel--;
if (m_indentLevel<0)
{
err("Negative indent level while generating RTF output!\n");
m_indentLevel=0;
}
m_codeGen->setIndentLevel(m_indentLevel);
}
// a style for list formatted with "list continue" style
QCString RTFGenerator::rtf_CList_DepthStyle()
{
QCString n=makeIndexName("ListContinue",indentLevel());
return rtf_Style[n.str()].reference();
}
// a style for list formatted as a "latext style" table of contents
QCString RTFGenerator::rtf_LCList_DepthStyle()
{
QCString n=makeIndexName("LatexTOC",indentLevel());
return rtf_Style[n.str()].reference();
}
// a style for list formatted as a "bullet" style
QCString RTFGenerator::rtf_BList_DepthStyle()
{
QCString n=makeIndexName("ListBullet",indentLevel());
return rtf_Style[n.str()].reference();
}
// a style for list formatted as a "enumeration" style
QCString RTFGenerator::rtf_EList_DepthStyle()
{
QCString n=makeIndexName("ListEnum",indentLevel());
return rtf_Style[n.str()].reference();
}
QCString RTFGenerator::rtf_DList_DepthStyle()
{
QCString n=makeIndexName("DescContinue",indentLevel());
return rtf_Style[n.str()].reference();
}
void RTFGenerator::startTextBlock(bool dense)
{
DBG_RTF(m_t << "{\\comment startTextBlock}\n")
m_t << "{\n";
m_t << rtf_Style_Reset;
if (dense) // no spacing between "paragraphs"
{
m_t << rtf_Style["DenseText"].reference();
}
else // some spacing
{
m_t << rtf_Style["BodyText"].reference();
}
}
void RTFGenerator::endTextBlock(bool /*paraBreak*/)
{
newParagraph();
DBG_RTF(m_t << "{\\comment endTextBlock}\n")
m_t << "}\n";
//m_omitParagraph = TRUE;
}
void RTFGenerator::newParagraph()
{
if (!m_omitParagraph)
{
DBG_RTF(m_t << "{\\comment (newParagraph)}\n")
m_t << "\\par\n";
}
m_omitParagraph = FALSE;
}
void RTFGenerator::startParagraph(const QCString &txt)
{
DBG_RTF(m_t << "{\\comment startParagraph}\n")
newParagraph();
m_t << "{\n";
if (QCString(txt) == "reference") m_t << "\\ql\n";
}
void RTFGenerator::endParagraph()
{
DBG_RTF(m_t << "{\\comment endParagraph}\n")
m_t << "}\\par\n";
m_omitParagraph = TRUE;
}
void RTFGenerator::startMemberSubtitle()
{
DBG_RTF(m_t << "{\\comment startMemberSubtitle}\n")
m_t << "{\n";
m_t << rtf_Style_Reset << rtf_CList_DepthStyle() << "\n";
}
void RTFGenerator::endMemberSubtitle()
{
DBG_RTF(m_t << "{\\comment endMemberSubtitle}\n")
newParagraph();
m_t << "}\n";
}
bool isLeadBytes(int c)
{
bool result=false; // for SBCS Codepages (cp1252,1251 etc...);
QCString codePage = theTranslator->trRTFansicp();
if (codePage == "932") // cp932 (Japanese Shift-JIS)
{
result = (0x81<=c && c<=0x9f) || (0xe0<=c && c<=0xfc);
}
else if (codePage == "936") // cp936 (Simplified Chinese GBK)
{
result = 0x81<=c && c<=0xFE;
}
else if (codePage == "949") // cp949 (Korean)
{
result = 0x81<=c && c<=0xFE;
}
else if (codePage == "950") // cp950 (Traditional Chinese Big5)
{
result = 0x81<=c && c<=0xFE;
}
return result;
}
// note: function is not reentrant!
static void encodeForOutput(TextStream &t,const QCString &s)
{
if (s==nullptr) return;
QCString encoding;
bool converted=FALSE;
size_t l = s.length();
static std::vector<char> enc;
if (l*4>enc.size()) enc.resize(l*4); // worst case
encoding.sprintf("CP%s",qPrint(theTranslator->trRTFansicp()));
if (!encoding.isEmpty())
{
// convert from UTF-8 back to the output encoding
void *cd = portable_iconv_open(encoding.data(),"UTF-8");
if (cd!=reinterpret_cast<void *>(-1))
{
size_t iLeft=l;
size_t oLeft=enc.size();
const char *inputPtr = s.data();
char *outputPtr = &enc[0];
if (!portable_iconv(cd, &inputPtr, &iLeft, &outputPtr, &oLeft))
{
enc.resize(enc.size()-oLeft);
converted=TRUE;
}
portable_iconv_close(cd);
}
}
if (!converted) // if we did not convert anything, copy as is.
{
memcpy(enc.data(),s.data(),l);
enc.resize(l);
}
bool multiByte = FALSE;
for (size_t i=0;i<enc.size();i++)
{
uint8_t c = static_cast<uint8_t>(enc.at(i));
if (c>=0x80 || multiByte)
{
char esc[10];
qsnprintf(esc,10,"\\'%X",c); // escape sequence for SBCS and DBCS(1st&2nd bytes).
t << esc;
if (!multiByte)
{
multiByte = isLeadBytes(c); // It may be DBCS Codepages.
}
else
{
multiByte = FALSE; // end of Double Bytes Character.
}
}
else
{
t << c;
}
}
}
/**
* VERY brittle routine inline RTF's included by other RTF's.
* it is recursive and ugly.
*/
static bool preProcessFile(Dir &d,const QCString &infName, TextStream &t, bool bIncludeHeader=true, bool removeFile = true)
{
static bool rtfDebug = Debug::isFlagSet(Debug::Rtf);
std::ifstream f = Portable::openInputStream(infName);
if (!f.is_open())
{
err("problems opening rtf file '%s' for reading\n",infName.data());
return false;
}
const int maxLineLength = 10240;
static QCString lineBuf(maxLineLength, QCString::ExplicitSize);
// scan until find end of header
// this is EXTREEEEEEEMLY brittle. It works on OUR rtf
// files because the first line before the body
// ALWAYS contains "{\comment begin body}"
std::string line;
while (getline(f,line))
{
line+='\n';
if (line.find("\\comment begin body")!=std::string::npos) break;
if (bIncludeHeader) encodeForOutput(t,line.c_str());
}
std::string prevLine;
bool first=true;
while (getline(f,line))
{
line+='\n';
size_t pos=prevLine.find("INCLUDETEXT \"");
if (pos!=std::string::npos)
{
size_t startNamePos = prevLine.find('"',pos)+1;
size_t endNamePos = prevLine.find('"',startNamePos);
std::string fileName = prevLine.substr(startNamePos,endNamePos-startNamePos);
DBG_RTF(t << "{\\comment begin include " << fileName << "}\n")
if (!preProcessFile(d,fileName.c_str(),t,FALSE)) return FALSE;
DBG_RTF(t << "{\\comment end include " << fileName << "}\n")
}
else if (!first) // no INCLUDETEXT on this line
{
encodeForOutput(t,prevLine.c_str());
}
prevLine = line;
first=false;
}
if (!bIncludeHeader) // skip final '}' in case we don't include headers
{
size_t pos = line.rfind('}');
if (pos==std::string::npos)
{
err("Strange, the last char was not a '}'\n");
pos = line.length();
}
encodeForOutput(t,line.substr(0,pos).c_str());
}
else
{
encodeForOutput(t,line.c_str());
}
f.close();
// remove temporary file
if (!rtfDebug && removeFile) removeSet.insert(FileInfo(d.filePath(infName.str())).absFilePath());
return TRUE;
}
void RTFGenerator::startDotGraph()
{
DBG_RTF(m_t << "{\\comment (startDotGraph)}\n")
}
void RTFGenerator::endDotGraph(DotClassGraph &g)
{
newParagraph();
QCString fn = g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Rtf,dir(),fileName(),m_relPath,TRUE,FALSE);
// display the file
m_t << "{\n";
m_t << rtf_Style_Reset << "\n";
m_t << "\\par\\pard \\qc {\\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"";
QCString imgExt = getDotImageExtension();
m_t << fn << "." << imgExt;
m_t << "\" \\\\d \\\\*MERGEFORMAT}{\\fldrslt IMAGE}}\\par\n";
m_t << "}\n";
newParagraph();
DBG_RTF(m_t << "{\\comment (endDotGraph)}\n")
}
void RTFGenerator::startInclDepGraph()
{
DBG_RTF(m_t << "{\\comment (startInclDepGraph)}\n")
}
void RTFGenerator::endInclDepGraph(DotInclDepGraph &g)
{
newParagraph();
QCString fn = g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Rtf,dir(),fileName(),m_relPath,FALSE);
// display the file
m_t << "{\n";
m_t << rtf_Style_Reset << "\n";
m_t << "\\par\\pard \\qc {\\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"";
QCString imgExt = getDotImageExtension();
m_t << fn << "." << imgExt;
m_t << "\" \\\\d \\\\*MERGEFORMAT}{\\fldrslt IMAGE}}\\par\n";
m_t << "}\n";
DBG_RTF(m_t << "{\\comment (endInclDepGraph)}\n")
}
void RTFGenerator::startGroupCollaboration()
{
}
void RTFGenerator::endGroupCollaboration(DotGroupCollaboration &)
{
}
void RTFGenerator::startCallGraph()
{
DBG_RTF(m_t << "{\\comment (startCallGraph)}\n")
}
void RTFGenerator::endCallGraph(DotCallGraph &g)
{
newParagraph();
QCString fn = g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Rtf,dir(),fileName(),m_relPath,FALSE);
// display the file
m_t << "{\n";
m_t << rtf_Style_Reset << "\n";
m_t << "\\par\\pard \\qc {\\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"";
QCString imgExt = getDotImageExtension();
m_t << fn << "." << imgExt;
m_t << "\" \\\\d \\\\*MERGEFORMAT}{\\fldrslt IMAGE}}\\par\n";
m_t << "}\n";
DBG_RTF(m_t << "{\\comment (endCallGraph)}\n")
}
void RTFGenerator::startDirDepGraph()
{
DBG_RTF(m_t << "{\\comment (startDirDepGraph)}\n")
}
void RTFGenerator::endDirDepGraph(DotDirDeps &g)
{
newParagraph();
QCString fn = g.writeGraph(m_t,GraphOutputFormat::BITMAP,EmbeddedOutputFormat::Rtf,dir(),fileName(),m_relPath,FALSE);
// display the file
m_t << "{\n";
m_t << rtf_Style_Reset << "\n";
m_t << "\\par\\pard \\qc {\\field\\flddirty {\\*\\fldinst INCLUDEPICTURE \"";
QCString imgExt = getDotImageExtension();
m_t << fn << "." << imgExt;
m_t << "\" \\\\d \\\\*MERGEFORMAT}{\\fldrslt IMAGE}}\\par\n";
m_t << "}\n";
DBG_RTF(m_t << "{\\comment (endDirDepGraph)}\n")
}
/** Tests the integrity of the result by counting brackets.
*
*/
void testRTFOutput(const QCString &name)
{
int bcount=0;
int line=1;
int c=0;
std::ifstream f = Portable::openInputStream(name);
if (f.is_open())
{
while ((c=f.get())!=-1)
{
if (c=='\\') // escape char
{
c=f.get();
if (c==-1) break;
}
else if (c=='{') // open bracket
{
bcount++;
}
else if (c=='}') // close bracket
{
bcount--;
if (bcount<0)
{
goto err;
break;
}
}
else if (c=='\n') // newline
{
line++;
}
}
}
if (bcount==0) return; // file is OK.
err:
err("RTF integrity test failed at line %d of %s due to a bracket mismatch.\n"
" Please try to create a small code example that produces this error \n"
" and send that to doxygen@gmail.com.\n",line,qPrint(name));
}
/**
* This is an API to a VERY brittle RTF preprocessor that combines nested
* RTF files. This version replaces the infile with the new file
*/
bool RTFGenerator::preProcessFileInplace(const QCString &path,const QCString &name)
{
static bool rtfDebug = Debug::isFlagSet(Debug::Rtf);
Dir d(path.str());
// store the original directory
if (!d.exists())
{
err("Output dir %s does not exist!\n",qPrint(path));
return FALSE;
}
std::string oldDir = Dir::currentDirPath();
// go to the html output directory (i.e. path)
Dir::setCurrent(d.absPath());
Dir thisDir;
QCString combinedName = path+"/combined.rtf";
QCString mainRTFName = path+"/"+name;
std::ofstream f = Portable::openOutputStream(combinedName);
if (!f.is_open())
{
err("Failed to open %s for writing!\n",combinedName.data());
Dir::setCurrent(oldDir);
return FALSE;
}
TextStream outt(&f);
if (!preProcessFile(thisDir,mainRTFName,outt,true,false))
{
// it failed, remove the temp file
outt.flush();
f.close();
if (!rtfDebug) removeSet.insert(FileInfo(thisDir.filePath(combinedName.str())).absFilePath());
Dir::setCurrent(oldDir);
return FALSE;
}
// everything worked, move the files
outt.flush();
f.close();
if (!rtfDebug)
{
thisDir.remove(mainRTFName.str());
}
else
{
thisDir.rename(mainRTFName.str(),mainRTFName.str() + ".org");
}
thisDir.rename(combinedName.str(),mainRTFName.str());
testRTFOutput(mainRTFName);
QCString rtfOutputDir = Dir::currentDirPath();
for (auto &s : removeSet)
{
QCString s1(s.c_str());
if (s1.startsWith(rtfOutputDir)) Portable::unlink(s1);
}
Dir::setCurrent(oldDir);
return TRUE;
}
void RTFGenerator::startMemberGroupHeader(bool hasHeader)
{
DBG_RTF(m_t << "{\\comment startMemberGroupHeader}\n")
m_t << "{\n";
if (hasHeader) incIndentLevel();
m_t << rtf_Style_Reset << rtf_Style["GroupHeader"].reference();
}
void RTFGenerator::endMemberGroupHeader()
{
DBG_RTF(m_t << "{\\comment endMemberGroupHeader}\n")
newParagraph();
m_t << rtf_Style_Reset << rtf_CList_DepthStyle();
}
void RTFGenerator::startMemberGroupDocs()
{
DBG_RTF(m_t << "{\\comment startMemberGroupDocs}\n")
startEmphasis();
}
void RTFGenerator::endMemberGroupDocs()
{
DBG_RTF(m_t << "{\\comment endMemberGroupDocs}\n")
endEmphasis();
newParagraph();
}
void RTFGenerator::startMemberGroup()
{
DBG_RTF(m_t << "{\\comment startMemberGroup}\n")
m_t << rtf_Style_Reset << rtf_BList_DepthStyle() << "\n";
}
void RTFGenerator::endMemberGroup(bool hasHeader)
{
DBG_RTF(m_t << "{\\comment endMemberGroup}\n")
if (hasHeader) decIndentLevel();
m_t << "}";
}
void RTFGenerator::startExamples()
{
DBG_RTF(m_t << "{\\comment (startExamples)}\n")
m_t << "{"; // ends at endDescList
m_t << "{"; // ends at endDescTitle
startBold();
newParagraph();
docify(theTranslator->trExamples());
endBold();
m_t << "}";
newParagraph();
incIndentLevel();
m_t << rtf_Style_Reset << rtf_DList_DepthStyle();
}
void RTFGenerator::endExamples()
{
DBG_RTF(m_t << "{\\comment (endExamples)}\n")
m_omitParagraph = FALSE;
newParagraph();
decIndentLevel();
m_omitParagraph = TRUE;
m_t << "}";
}
void RTFGenerator::startParameterType(bool first,const QCString &key)
{
DBG_RTF(m_t << "{\\comment (startParameterType)}\n")
if (!first && !key.isEmpty())
{
m_t << " " << key << " ";
}
}
void RTFGenerator::endParameterType()
{
DBG_RTF(m_t << "{\\comment (endParameterType)}\n")
m_t << " ";
}
void RTFGenerator::exceptionEntry(const QCString &prefix,bool closeBracket)
{
DBG_RTF(m_t << "{\\comment (exceptionEntry)}\n")
if (!prefix.isEmpty())
{
m_t << " " << prefix << "(";
}
else if (closeBracket)
{
m_t << ")";
}
m_t << " ";
}
void RTFGenerator::writeDoc(const IDocNodeAST *ast,const Definition *ctx,const MemberDef *,int)
{
auto astImpl = dynamic_cast<const DocNodeAST*>(ast);
if (astImpl)
{
RTFDocVisitor visitor(m_t,*m_codeList,ctx?ctx->getDefFileExtension():QCString(""),m_hierarchyLevel);
std::visit(visitor,astImpl->root);
}
m_omitParagraph = TRUE;
}
void RTFGenerator::rtfwriteRuler_doubleline()
{
DBG_RTF(m_t << "{\\comment (rtfwriteRuler_doubleline)}\n")
m_t << "{\\pard\\widctlpar\\brdrb\\brdrdb\\brdrw15\\brsp20 \\adjustright \\par}\n";
}
void RTFGenerator::rtfwriteRuler_emboss()
{
DBG_RTF(m_t << "{\\comment (rtfwriteRuler_emboss)}\n")
m_t << "{\\pard\\widctlpar\\brdrb\\brdremboss\\brdrw15\\brsp20 \\adjustright \\par}\n";
}
void RTFGenerator::rtfwriteRuler_thick()
{
DBG_RTF(m_t << "{\\comment (rtfwriteRuler_thick)}\n")
m_t << "{\\pard\\widctlpar\\brdrb\\brdrs\\brdrw75\\brsp20 \\adjustright \\par}\n";
}
void RTFGenerator::rtfwriteRuler_thin()
{
DBG_RTF(m_t << "{\\comment (rtfwriteRuler_thin)}\n")
m_t << "{\\pard\\widctlpar\\brdrb\\brdrs\\brdrw5\\brsp20 \\adjustright \\par}\n";
}
void RTFGenerator::startConstraintList(const QCString &header)
{
DBG_RTF(m_t << "{\\comment (startConstraintList)}\n")
m_t << "{"; // ends at endConstraintList
m_t << "{";
startBold();
newParagraph();
docify(header);
endBold();
m_t << "}";
newParagraph();
incIndentLevel();
m_t << rtf_Style_Reset << rtf_DList_DepthStyle();
}
void RTFGenerator::startConstraintParam()
{
DBG_RTF(m_t << "{\\comment (startConstraintParam)}\n")
startEmphasis();
}
void RTFGenerator::endConstraintParam()
{
DBG_RTF(m_t << "{\\comment (endConstraintParam)}\n")
endEmphasis();
m_t << " : ";
}
void RTFGenerator::startConstraintType()
{
DBG_RTF(m_t << "{\\comment (startConstraintType)}\n")
startEmphasis();
}
void RTFGenerator::endConstraintType()
{
DBG_RTF(m_t << "{\\comment (endConstraintType)}\n")
endEmphasis();
m_t << " ";
}
void RTFGenerator::startConstraintDocs()
{
DBG_RTF(m_t << "{\\comment (startConstraintDocs)}\n")
}
void RTFGenerator::endConstraintDocs()
{
DBG_RTF(m_t << "{\\comment (endConstraintDocs)}\n")
newParagraph();
}
void RTFGenerator::endConstraintList()
{
DBG_RTF(m_t << "{\\comment (endConstraintList)}\n")
newParagraph();
decIndentLevel();
m_omitParagraph = TRUE;
m_t << "}";
}
void RTFGenerator::startIndexListItem()
{
DBG_RTF(m_t << "{\\comment (startIndexListItem)}\n")
}
void RTFGenerator::endIndexListItem()
{
DBG_RTF(m_t << "{\\comment (endIndexListItem)}\n")
m_t << "\\par\n";
}
void RTFGenerator::startInlineHeader()
{
DBG_RTF(m_t << "{\\comment (startInlineHeader)}\n")
m_t << "{\n";
m_t << rtf_Style_Reset << rtf_Style["Heading5"].reference();
startBold();
}
void RTFGenerator::endInlineHeader()
{
DBG_RTF(m_t << "{\\comment (endInlineHeader)}\n")
endBold();
m_t << "\\par";
m_t << "}\n";
}
void RTFGenerator::startMemberDocSimple(bool isEnum)
{
DBG_RTF(m_t << "{\\comment (startMemberDocSimple)}\n")
m_t << "{\\par\n";
m_t << "{" << rtf_Style["Heading5"].reference() << "\n";
if (isEnum)
{
m_t << theTranslator->trEnumerationValues();
}
else
{
m_t << theTranslator->trCompoundMembers();
}
m_t << ":\\par}\n";
m_t << rtf_Style_Reset << rtf_DList_DepthStyle();
m_t << "\\trowd \\trgaph108\\trleft426\\tblind426"
"\\trbrdrt\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrl\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrb\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrr\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrh\\brdrs\\brdrw10\\brdrcf15 "
"\\trbrdrv\\brdrs\\brdrw10\\brdrcf15 \n";
int n=3,columnPos[3] = { 25, 50, 100 };
if (isEnum)
{
columnPos[0]=30;
columnPos[1]=100;
n=2;
}
for (int i=0;i<n;i++)
{
m_t << "\\clvertalt\\clbrdrt\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrl\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrb\\brdrs\\brdrw10\\brdrcf15 "
"\\clbrdrr \\brdrs\\brdrw10\\brdrcf15 "
"\\cltxlrtb "
"\\cellx" << (rtf_pageWidth*columnPos[i]/100) << "\n";
}
m_t << "\\pard \\widctlpar\\intbl\\adjustright\n";
}
void RTFGenerator::endMemberDocSimple(bool)
{
DBG_RTF(m_t << "{\\comment (endMemberDocSimple)}\n")
m_t << "}\n";
}
void RTFGenerator::startInlineMemberType()
{
DBG_RTF(m_t << "{\\comment (startInlineMemberType)}\n")
m_t << "{\\qr ";
}
void RTFGenerator::endInlineMemberType()
{
DBG_RTF(m_t << "{\\comment (endInlineMemberType)}\n")
m_t << "\\cell }";
}
void RTFGenerator::startInlineMemberName()
{
DBG_RTF(m_t << "{\\comment (startInlineMemberName)}\n")
m_t << "{";
}
void RTFGenerator::endInlineMemberName()
{
DBG_RTF(m_t << "{\\comment (endInlineMemberName)}\n")
m_t << "\\cell }";
}
void RTFGenerator::startInlineMemberDoc()
{
DBG_RTF(m_t << "{\\comment (startInlineMemberDoc)}\n")
m_t << "{";
}
void RTFGenerator::endInlineMemberDoc()
{
DBG_RTF(m_t << "{\\comment (endInlineMemberDoc)}\n")
m_t << "\\cell }{\\row }\n";
}
void RTFGenerator::startLabels()
{
}
void RTFGenerator::writeLabel(const QCString &l,bool isLast)
{
m_t << "{\\f2 [" << l << "]}";
if (!isLast) m_t << ", ";
}
void RTFGenerator::endLabels()
{
}
void RTFGenerator::writeInheritedSectionTitle(
const QCString &/*id*/,const QCString &ref,
const QCString &file, const QCString &anchor,
const QCString &title, const QCString &name)
{
m_t << rtf_Style_Reset;
m_t << rtf_Style["Heading4"].reference();
m_t << "\n";
m_t << theTranslator->trInheritedFrom(docifyToString(title), objectLinkToString(ref, file, anchor, name));
m_t << "\\par\n";
m_t << rtf_Style_Reset << "\n";
}
void RTFGenerator::startParameterList(bool openBracket)
{
if (openBracket) m_t << "(";
}
void RTFGenerator::endParameterExtra(bool last,bool /* emptyList */, bool closeBracket)
{
if (last && closeBracket)
{
m_t << ")";
}
}
//----------------------------------------------------------------------
static std::mutex g_rtfFormatMutex;
static std::unordered_map<std::string,std::string> g_tagMap;
static QCString g_nextTag( "AAAAAAAAAA" );
QCString rtfFormatBmkStr(const QCString &name)
{
std::lock_guard<std::mutex> lock(g_rtfFormatMutex);
// To overcome the 40-character tag limitation, we
// substitute a short arbitrary string for the name
// supplied, and keep track of the correspondence
// between names and strings.
auto it = g_tagMap.find(name.str());
if (it!=g_tagMap.end()) // already known
{
return QCString(it->second);
}
QCString tag = g_nextTag;
auto result = g_tagMap.emplace(name.str(), g_nextTag.str());
if (result.second) // new item was added
{
// increment the next tag.
char* nxtTag = g_nextTag.rawData() + g_nextTag.length() - 1;
for ( unsigned int i = 0; i < g_nextTag.length(); ++i, --nxtTag )
{
if ( ( ++(*nxtTag) ) > 'Z' )
{
*nxtTag = 'A';
}
else
{
// Since there was no carry, we can stop now
break;
}
}
}
Debug::print(Debug::Rtf,0,"Name = %s RTF_tag = %s\n",qPrint(name),qPrint(tag));
return tag;
}
| 77,613
|
C++
|
.cpp
| 2,612
| 25.015697
| 134
| 0.592009
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,427
|
stlsupport.cpp
|
doxygen_doxygen/src/stlsupport.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include "stlsupport.h"
#include "entry.h"
#include "config.h"
/** A struct contained the data for an STL class */
struct STLInfo
{
const char *className;
const char *baseClass1;
const char *baseClass2;
const char *templType1;
const char *templName1;
const char *templType2;
const char *templName2;
bool virtualInheritance;
bool iterators;
};
static STLInfo g_stlinfo[] =
{
// className baseClass1 baseClass2 templType1 templName1 templType2 templName2 virtInheritance // iterators
{ "allocator", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, false },
{ "auto_ptr", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // deprecated
{ "smart_ptr", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++11
{ "unique_ptr", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++11
{ "shared_ptr", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++14
{ "weak_ptr", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++11
{ "atomic", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++11
{ "atomic_ref", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++20
{ "lock_guard", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++11
{ "unique_lock", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++11
{ "shared_lock", nullptr, nullptr, "T", "ptr", nullptr, nullptr, false, false }, // C++14
{ "ios_base", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "error_code", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "error_category", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "system_error", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "error_condition", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "thread", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "jthread", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "mutex", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "timed_mutex", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "recursive_mutex", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "recursive_timed_mutex",nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++11
{ "shared_mutex", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++17
{ "shared_timed_mutex", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }, // C++14
{ "basic_ios", "ios_base", nullptr, "Char", nullptr, nullptr, nullptr, false, false },
{ "basic_istream", "basic_ios<Char>", nullptr, "Char", nullptr, nullptr, nullptr, true, false },
{ "basic_ostream", "basic_ios<Char>", nullptr, "Char", nullptr, nullptr, nullptr, true, false },
{ "basic_iostream", "basic_istream<Char>", "basic_ostream<Char>", "Char", nullptr, nullptr, nullptr, false, false },
{ "basic_ifstream", "basic_istream<Char>", nullptr, "Char", nullptr, nullptr, nullptr, false, false },
{ "basic_ofstream", "basic_ostream<Char>", nullptr, "Char", nullptr, nullptr, nullptr, false, false },
{ "basic_fstream", "basic_iostream<Char>", nullptr, "Char", nullptr, nullptr, nullptr, false, false },
{ "basic_istringstream", "basic_istream<Char>", nullptr, "Char", nullptr, nullptr, nullptr, false, false },
{ "basic_ostringstream", "basic_ostream<Char>", nullptr, "Char", nullptr, nullptr, nullptr, false, false },
{ "basic_stringstream", "basic_iostream<Char>", nullptr, "Char", nullptr, nullptr, nullptr, false, false },
{ "ios", "basic_ios<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wios", "basic_ios<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "istream", "basic_istream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wistream", "basic_istream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "ostream", "basic_ostream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wostream", "basic_ostream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "ifstream", "basic_ifstream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wifstream", "basic_ifstream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "ofstream", "basic_ofstream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wofstream", "basic_ofstream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "fstream", "basic_fstream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wfstream", "basic_fstream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "istringstream", "basic_istringstream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wistringstream", "basic_istringstream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "ostringstream", "basic_ostringstream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wostringstream", "basic_ostringstream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "stringstream", "basic_stringstream<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "wstringstream", "basic_stringstream<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "basic_string", nullptr, nullptr, "Char", nullptr, nullptr, nullptr, false, true },
{ "string", "basic_string<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true },
{ "wstring", "basic_string<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true },
{ "u8string", "basic_string<char8_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++20
{ "u16string", "basic_string<char16_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++11
{ "u32string", "basic_string<char32_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++11
{ "basic_string_view", nullptr, nullptr, "Char", nullptr, nullptr, nullptr, false, true },
{ "string_view", "basic_string_view<char>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++17
{ "wstring_view", "basic_string_view<wchar_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++17
{ "u8string_view", "basic_string_view<char8_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++20
{ "u16string_view", "basic_string_view<char16_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++17
{ "u32string_view", "basic_string_view<char32_t>", nullptr, nullptr, nullptr, nullptr, nullptr, false, true }, // C++17
{ "complex", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "bitset", nullptr, nullptr, "Bits", nullptr, nullptr, nullptr, false, false },
{ "deque", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, true },
{ "list", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, true },
{ "forward_list", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, true }, // C++11
{ "pair", nullptr, nullptr, "T1", "first_type", "T2", "second_type", false, false },
{ "map", nullptr, nullptr, "K", "keys", "T", "elements", false, true },
{ "unordered_map", nullptr, nullptr, "K", "keys", "T", "elements", false, true }, // C++11
{ "multimap", nullptr, nullptr, "K", "keys", "T", "elements", false, true },
{ "unordered_multimap", nullptr, nullptr, "K", "keys", "T", "elements", false, true }, // C++11
{ "set", nullptr, nullptr, "K", "keys", nullptr, nullptr, false, true },
{ "unordered_set", nullptr, nullptr, "K", "keys", nullptr, nullptr, false, true }, // C++11
{ "multiset", nullptr, nullptr, "K", "keys", nullptr, nullptr, false, true },
{ "unordered_multiset", nullptr, nullptr, "K", "keys", nullptr, nullptr, false, true }, // C++11
{ "array", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, true }, // C++11
{ "vector", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, true },
{ "span", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, true }, // C++20
{ "queue", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, false },
{ "priority_queue", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, false },
{ "stack", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, false },
{ "valarray", nullptr, nullptr, "T", "elements", nullptr, nullptr, false, false },
{ "exception", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "bad_alloc", "exception", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "bad_cast", "exception", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "bad_typeid", "exception", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "logic_error", "exception", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "ios_base::failure", "exception", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "runtime_error", "exception", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "bad_exception", "exception", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "domain_error", "logic_error", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "invalid_argument", "logic_error", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "length_error", "logic_error", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "out_of_range", "logic_error", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "range_error", "runtime_error", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "overflow_error", "runtime_error", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ "underflow_error", "runtime_error", nullptr, nullptr, nullptr, nullptr, nullptr, false, false },
{ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, false, false }
};
static void addSTLMember(const std::shared_ptr<Entry> &root,const char *type,const char *name)
{
std::shared_ptr<Entry> memEntry = std::make_shared<Entry>();
memEntry->name = name;
memEntry->type = type;
memEntry->protection = Protection::Public;
memEntry->section = EntryType::makeVariable();
memEntry->brief = "STL member";
memEntry->hidden = false;
memEntry->artificial = true;
root->moveToSubEntryAndKeep(memEntry);
}
static void addSTLIterator(const std::shared_ptr<Entry> &classEntry,const QCString &name)
{
std::shared_ptr<Entry> iteratorClassEntry = std::make_shared<Entry>();
iteratorClassEntry->fileName = "[STL]";
iteratorClassEntry->startLine = 1;
iteratorClassEntry->name = name;
iteratorClassEntry->section = EntryType::makeClass();
iteratorClassEntry->brief = "STL iterator class";
iteratorClassEntry->hidden = false;
iteratorClassEntry->artificial= true;
classEntry->moveToSubEntryAndKeep(iteratorClassEntry);
}
static void addSTLClass(const std::shared_ptr<Entry> &root,const STLInfo *info)
{
//printf("Adding STL class %s\n",info->className);
QCString fullName = info->className;
fullName.prepend("std::");
// add fake Entry for the class
std::shared_ptr<Entry> classEntry = std::make_shared<Entry>();
classEntry->fileName = "[STL]";
classEntry->startLine = 1;
classEntry->name = fullName;
classEntry->section = EntryType::makeClass();
classEntry->brief = "STL class";
classEntry->hidden = false;
classEntry->artificial= true;
// add template arguments to class
if (info->templType1 != nullptr)
{
ArgumentList al;
Argument a;
a.type="typename";
a.name=info->templType1;
al.push_back(a);
if (info->templType2 != nullptr) // another template argument
{
a.type="typename";
a.name=info->templType2;
al.push_back(a);
}
classEntry->tArgLists.push_back(al);
}
// add member variables
if (info->templName1 != nullptr)
{
addSTLMember(classEntry,info->templType1,info->templName1);
}
if (info->templName2 != nullptr)
{
addSTLMember(classEntry,info->templType2,info->templName2);
}
if (fullName=="std::auto_ptr" ||
fullName=="std::smart_ptr" ||
fullName=="std::shared_ptr" ||
fullName=="std::weak_ptr" ||
fullName=="std::unique_ptr")
{
std::shared_ptr<Entry> memEntry = std::make_shared<Entry>();
memEntry->name = "operator->";
memEntry->args = "()";
memEntry->type = "T*";
memEntry->protection = Protection::Public;
memEntry->section = EntryType::makeFunction();
memEntry->brief = "STL member";
memEntry->hidden = false;
memEntry->artificial = false;
classEntry->moveToSubEntryAndKeep(memEntry);
}
Specifier virt = info->virtualInheritance ? Specifier::Virtual : Specifier::Normal;
if (info->baseClass1 != nullptr)
{
classEntry->extends.emplace_back(info->baseClass1, Protection::Public, virt);
}
if (info->baseClass2 != nullptr)
{
classEntry->extends.emplace_back(info->baseClass2, Protection::Public, virt);
}
if (info->iterators)
{
// add iterator class
addSTLIterator(classEntry,fullName+"::iterator");
addSTLIterator(classEntry,fullName+"::const_iterator");
addSTLIterator(classEntry,fullName+"::reverse_iterator");
addSTLIterator(classEntry,fullName+"::const_reverse_iterator");
}
root->moveToSubEntryAndKeep(classEntry);
}
static void addSTLClasses(const std::shared_ptr<Entry> &root)
{
std::shared_ptr<Entry> namespaceEntry = std::make_shared<Entry>();
namespaceEntry->fileName = "[STL]";
namespaceEntry->startLine = 1;
namespaceEntry->name = "std";
namespaceEntry->section = EntryType::makeNamespace();
namespaceEntry->brief = "STL namespace";
namespaceEntry->hidden = false;
namespaceEntry->artificial= true;
STLInfo *info = g_stlinfo;
while (info->className != nullptr)
{
addSTLClass(namespaceEntry,info);
info++;
}
root->moveToSubEntryAndKeep(namespaceEntry);
}
void addSTLSupport(std::shared_ptr<Entry> &root)
{
if (Config_getBool(BUILTIN_STL_SUPPORT))
{
addSTLClasses(root);
}
}
| 23,054
|
C++
|
.cpp
| 259
| 85.864865
| 184
| 0.445527
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,428
|
dotgfxhierarchytable.cpp
|
doxygen_doxygen/src/dotgfxhierarchytable.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2019 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.
*
*/
#include <sstream>
#include "dotgfxhierarchytable.h"
#include "language.h"
#include "util.h"
#include "message.h"
#include "doxygen.h"
#include "classlist.h"
#include "dir.h"
#include "vhdldocgen.h"
QCString DotGfxHierarchyTable::getBaseName() const
{
QCString baseName;
if (m_prefix.isEmpty())
baseName.sprintf("inherit_graph_%d", m_graphId);
else
baseName.sprintf("%sinherit_graph_%d",qPrint(m_prefix), m_graphId);
return baseName;
}
void DotGfxHierarchyTable::computeTheGraph()
{
TextStream md5stream;
writeGraphHeader(md5stream,theTranslator->trGraphicalHierarchy());
md5stream << " rankdir=\"LR\";\n";
for (auto node : m_rootNodes)
{
if (node->subgraphId()==m_rootSubgraphNode->subgraphId())
{
node->clearWriteFlag();
}
}
for (auto node : m_rootNodes)
{
if (node->subgraphId()==m_rootSubgraphNode->subgraphId())
{
node->write(md5stream,GraphType::Hierarchy,GraphOutputFormat::BITMAP,FALSE,TRUE,TRUE);
}
}
writeGraphFooter(md5stream);
m_theGraph = md5stream.str();
}
QCString DotGfxHierarchyTable::getMapLabel() const
{
return escapeCharsInString(m_rootSubgraphNode->label(),FALSE);
}
void DotGfxHierarchyTable::createGraph(DotNode *n,TextStream &out,
const QCString &path,const QCString &fileName,int id)
{
m_rootSubgraphNode = n;
m_graphId = id;
m_noDivTag = TRUE;
m_zoomable = FALSE;
DotGraph::writeGraph(out, GraphOutputFormat::BITMAP, EmbeddedOutputFormat::Html, path, fileName, "", TRUE, 0);
}
void DotGfxHierarchyTable::writeGraph(TextStream &out,
const QCString &path,const QCString &fileName)
{
//printf("DotGfxHierarchyTable::writeGraph(%s)\n",name);
//printf("m_rootNodes=%p count=%d\n",m_rootNodes,m_rootNodes->count());
if (m_rootSubgraphs.empty()) return;
Dir d(path.str());
// store the original directory
if (!d.exists())
{
term("Output dir %s does not exist!\n",qPrint(path));
}
// put each connected subgraph of the hierarchy in a row of the HTML output
out << "<table border=\"0\" cellspacing=\"10\" cellpadding=\"0\">\n";
int count=0;
std::stable_sort(m_rootSubgraphs.begin(),m_rootSubgraphs.end(),
[](auto n1,auto n2) { return qstricmp_sort(n1->label(),n2->label())<0; });
for (auto n : m_rootSubgraphs)
{
out << "<tr><td>";
createGraph(n,out,path,fileName,count++);
out << "</td></tr>\n";
}
out << "</table>\n";
}
void DotGfxHierarchyTable::addHierarchy(DotNode *n,const ClassDef *cd,ClassDefSet &visitedClasses)
{
//printf("addHierarchy '%s' baseClasses=%d\n",qPrint(cd->name()),cd->baseClasses()->count());
for (const auto &bcd : cd->subClasses())
{
ClassDef *bClass=bcd.classDef;
//printf(" Trying sub class='%s' usedNodes=%d\n",qPrint(bClass->name()),m_usedNodes->count());
if (bClass && bClass->isVisibleInHierarchy() && classHasVisibleRoot(bClass->baseClasses()))
{
auto it = m_usedNodes.find(bClass->name().str());
//printf(" Node '%s' Found visible class='%s'\n",qPrint(n->label()),
// qPrint(bClass->name()));
DotNode *root = nullptr;
if (it!=m_usedNodes.end()) // node already present
{
const auto &bn = it->second;
root = bn.get();
const auto &children = n->children();
auto child_it = std::find(children.begin(),children.end(),bn.get());
if (child_it==children.end()) // no arrow yet
{
n->addChild(bn.get(),EdgeInfo::protectionToColor(bcd.prot));
bn->addParent(n);
//printf(" Adding node %s to existing base node %s (c=%d,p=%d)\n",
// qPrint(n->label()),
// qPrint(bn->label()),
// bn->children() ? bn->children()->count() : 0,
// bn->parents() ? bn->parents()->count() : 0
// );
}
//else
//{
// printf(" Class already has an arrow!\n");
//}
}
else
{
QCString tmp_url="";
if (bClass->isLinkable() && !bClass->isHidden())
{
tmp_url=bClass->getReference()+"$"+bClass->getOutputFileBase();
if (!bClass->anchor().isEmpty())
{
tmp_url+="#"+bClass->anchor();
}
}
QCString tooltip = bClass->briefDescriptionAsTooltip();
auto bn = std::make_unique<DotNode>(this,
bClass->displayName(),
tooltip,
tmp_url
);
n->addChild(bn.get(),EdgeInfo::protectionToColor(bcd.prot));
bn->addParent(n);
root = bn.get();
//printf(" Adding node %s to new base node %s (c=%d,p=%d)\n",
// qPrint(n->label()),
// qPrint(bn->label()),
// bn->children() ? bn->children()->count() : 0,
// bn->parents() ? bn->parents()->count() : 0
// );
//printf(" inserting %s (%p)\n",qPrint(bClass->name()),bn);
m_usedNodes.emplace(bClass->name().str(),std::move(bn)); // add node to the used list
}
if (visitedClasses.find(bClass)==visitedClasses.end() && !bClass->subClasses().empty())
{
visitedClasses.insert(bClass);
addHierarchy(root,bClass,visitedClasses);
}
}
}
//printf("end addHierarchy\n");
}
void DotGfxHierarchyTable::addClassList(const ClassLinkedMap &cl,ClassDefSet &visitedClasses)
{
for (const auto &cd : cl)
{
//printf("Trying %s subClasses=%d\n",qPrint(cd->name()),cd->subClasses()->count());
if (cd->getLanguage()==SrcLangExt::VHDL &&
VhdlDocGen::convert(cd->protection())!=VhdlDocGen::ENTITYCLASS
)
{
continue;
}
if (Config_getBool(OPTIMIZE_OUTPUT_SLICE) && cd->compoundType() != m_classType)
{
continue;
}
if (!classHasVisibleRoot(cd->baseClasses()) &&
cd->isVisibleInHierarchy()
) // root node in the forest
{
QCString tmp_url="";
if (cd->isLinkable() && !cd->isHidden())
{
tmp_url=cd->getReference()+"$"+cd->getOutputFileBase();
if (!cd->anchor().isEmpty())
{
tmp_url+="#"+cd->anchor();
}
}
//printf("Inserting root class %s\n",qPrint(cd->name()));
QCString tooltip = cd->briefDescriptionAsTooltip();
auto n = std::make_unique<DotNode>(this,
cd->displayName(),
tooltip,
tmp_url);
DotNode *root = n.get();
m_usedNodes.emplace(cd->name().str(),std::move(n));
m_rootNodes.push_back(root);
if (visitedClasses.find(cd.get())==visitedClasses.end() && !cd->subClasses().empty())
{
addHierarchy(root,cd.get(),visitedClasses);
visitedClasses.insert(cd.get());
}
}
}
}
DotGfxHierarchyTable::DotGfxHierarchyTable(const QCString &prefix,ClassDef::CompoundType ct)
: m_prefix(prefix)
, m_classType(ct)
{
// build a graph with each class as a node and the inheritance relations
// as edges
ClassDefSet visitedClasses;
addClassList(*Doxygen::classLinkedMap,visitedClasses);
addClassList(*Doxygen::hiddenClassLinkedMap,visitedClasses);
// m_usedNodes now contains all nodes in the graph
// color the graph into a set of independent subgraphs
bool done=FALSE;
int curColor=0;
while (!done) // there are still nodes to color
{
done=TRUE; // we are done unless there are still uncolored nodes
for (auto n : m_rootNodes)
{
if (n->subgraphId()==-1) // not yet colored
{
//printf("Starting at node %s (%p): %d\n",qPrint(n->label()),n,curColor);
done=FALSE; // still uncolored nodes
n->setSubgraphId(curColor);
n->markAsVisible();
n->colorConnectedNodes(curColor);
curColor++;
m_rootSubgraphs.push_back(n);
}
}
}
//printf("Number of independent subgraphs: %d\n",curColor);
for (auto n : m_rootSubgraphs)
{
//printf("Node %s color=%d (c=%d,p=%d)\n",
// qPrint(n->label()),n->m_subgraphId,
// n->children()?n->children()->count():0,
// n->parents()?n->parents()->count():0);
int number=0;
n->renumberNodes(number);
}
}
| 8,741
|
C++
|
.cpp
| 251
| 29.49004
| 112
| 0.618272
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,429
|
htmlhelp.cpp
|
doxygen_doxygen/src/htmlhelp.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2020 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.
*
* The original version of this file is largely based on a contribution from
* Harm van der Heijden.
*/
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include "htmlhelp.h"
#include "config.h"
#include "message.h"
#include "doxygen.h"
#include "language.h"
#include "portable.h"
#include "groupdef.h"
#include "memberdef.h"
#include "filedef.h"
#include "util.h"
#include "linkedmap.h"
#include "regex.h"
#include "fileinfo.h"
//----------------------------------------------------------------------------
/** Helper class to deal with recoding the UTF8 encoded text back to the native encoding
* specified by CHM_INDEX_ENCODING.
*/
class HtmlHelpRecoder
{
public:
HtmlHelpRecoder() {}
~HtmlHelpRecoder() { finalize(); }
NON_COPYABLE(HtmlHelpRecoder)
void initialize()
{
QCString str = Config_getString(CHM_INDEX_ENCODING);
if (str.isEmpty()) str = "CP1250"; // use safe and likely default
m_fromUtf8 = portable_iconv_open(str.data(),"UTF-8");
if (m_fromUtf8==m_iconv_null)
{
term("unsupported character conversion for CHM_INDEX_ENCODING: '%s'->'UTF-8'\n", qPrint(str));
}
}
void finalize()
{
if (m_fromUtf8!=m_iconv_null)
{
portable_iconv_close(m_fromUtf8);
m_fromUtf8 = m_iconv_null;
}
}
QCString recode(const QCString &s)
{
size_t iSize = s.length();
size_t oSize = iSize*4;
QCString output(oSize, QCString::ExplicitSize);
size_t iLeft = iSize;
size_t oLeft = oSize;
const char *iPtr = s.data();
char *oPtr = output.rawData();
if (!portable_iconv(m_fromUtf8,&iPtr,&iLeft,&oPtr,&oLeft))
{
oSize -= oLeft;
output.resize(oSize);
output.at(oSize)='\0';
return output;
}
else
{
return s;
}
}
private:
void *m_iconv_null = reinterpret_cast<void*>(-1);
void *m_fromUtf8 = m_iconv_null;
};
//----------------------------------------------------------------------------
/** Class representing a field in the HTML help index. */
struct IndexField
{
IndexField(const QCString &k,const QCString &n,const QCString &u,const QCString &a,bool l,bool r) :
key(k), name(n), url(u), anchor(a), link(l), reversed(r) {}
QCString key;
QCString name;
QCString url;
QCString anchor;
bool link;
bool reversed;
};
/** A helper class for HtmlHelp that manages a two level index in
* alphabetical order.
*/
class HtmlHelpIndex
{
public:
HtmlHelpIndex(HtmlHelpRecoder &recoder);
~HtmlHelpIndex();
NON_COPYABLE(HtmlHelpIndex)
void addItem(const QCString &first,const QCString &second,
const QCString &url, const QCString &anchor,
bool hasLink,bool reversed);
void writeFields(std::ostream &t);
size_t size() const { return m_map.size(); }
private:
LinkedMap<IndexField> m_map;
HtmlHelpRecoder &m_recoder;
};
/*! Constructs a new HtmlHelp index */
HtmlHelpIndex::HtmlHelpIndex(HtmlHelpRecoder &recoder) : m_recoder(recoder)
{
}
/*! Destroys the HtmlHelp index */
HtmlHelpIndex::~HtmlHelpIndex() = default;
/*! Stores an item in the index if it is not already present.
* Items are stored in alphabetical order, by sorting on the
* concatenation of \a level1 and \a level2 (if present).
*
* \param level1 the string at level 1 in the index.
* \param level2 the string at level 2 in the index (or 0 if not applicable).
* \param url the url of the documentation (without .html extension).
* \param anchor the anchor of the documentation within the page.
* \param hasLink if true, the url (without anchor) can be used in the
* level1 item, when writing the header of a list of level2 items.
* \param reversed TRUE if level1 is the member name and level2 the compound
* name.
*/
void HtmlHelpIndex::addItem(const QCString &level1,const QCString &level2,
const QCString &url,const QCString &anchor,bool hasLink,
bool reversed)
{
static const reg::Ex re(R"(@\d+)");
std::string key = level1.str();
if (!level2.isEmpty()) key+= std::string("?") + level2.str();
if (reg::search(key,re)) // skip anonymous stuff
{
return;
}
std::string key_anchor;
if (!anchor.isEmpty())
{
key_anchor = key+anchor.str();
}
else
{
key_anchor = key;
}
m_map.add(key_anchor.c_str(),key.c_str(),url,anchor,hasLink,reversed);
}
static QCString field2URL(const IndexField *f,bool checkReversed)
{
QCString result = f->url;
addHtmlExtensionIfMissing(result);
if (!f->anchor.isEmpty() && (!checkReversed || f->reversed))
{
result+="#"+f->anchor;
}
return result;
}
static QCString convertToHtmlAndTruncate(const QCString &s)
{
/* to prevent
* Warning: Keyword string:
* ...
* is too long. The maximum size is 488 characters.
*/
int maxLen = 400;
size_t maxExpandedLen = maxLen+50;
QCString result = convertToHtml(s,true);
if (result.length()>maxExpandedLen) // we need to truncate the string
{
// in the unlikely case that the string after conversion grows from maxLen to maxExpandedLen, we try smaller parts
// until we end up below the limit
while (maxLen>0 && result.length()>maxExpandedLen)
{
result = convertToHtml(s.left(maxLen));
maxLen-=20;
}
return result+"...";
}
else
{
return result;
}
}
/*! Writes the sorted list of index items into a html like list.
*
* An list of calls with <code>name = level1,level2</code> as follows:
* <pre>
* a1,b1
* a1,b2
* a2,b1
* a2,b2
* a3
* a4,b1
* </pre>
*
* Will result in the following list:
*
* <pre>
* a1 -> link to url if hasLink==TRUE
* b1 -> link to url#anchor
* b2 -> link to url#anchor
* a2 -> link to url if hasLink==TRUE
* b1 -> link to url#anchor
* b2 -> link to url#anchor
* a3 -> link to url if hasLink==TRUE
* a4 -> link to url if hasLink==TRUE
* b1 -> link to url#anchor
* </pre>
*/
void HtmlHelpIndex::writeFields(std::ostream &t)
{
std::stable_sort(std::begin(m_map),
std::end(m_map),
[](const auto &e1,const auto &e2) { return qstricmp_sort(e1->name,e2->name)<0; }
);
QCString prevLevel1;
bool level2Started=FALSE;
for (auto it = std::begin(m_map); it!=std::end(m_map); ++it)
{
auto &f = *it;
QCString level1,level2;
int i = f->name.find('?');
if (i!=-1)
{
level1 = f->name.left(i);
level2 = f->name.right(f->name.length()-i-1);
}
else
{
level1 = f->name;
}
{ // finish old list at level 2
if (level2Started) t << " </UL>\n";
level2Started=FALSE;
// <Antony>
// Added this code so that an item with only one subitem is written
// without any subitem.
// For example:
// a1, b1 -> will create only a1, not separate subitem for b1
// a2, b2
// a2, b3
QCString nextLevel1;
auto it_next = std::next(it);
if (it_next!=std::end(m_map))
{
auto &fnext = *it_next;
int j = fnext->name.find('?');
if (j<0) j=0;
nextLevel1 = fnext->name.left(j);
}
if (!(level1 == prevLevel1 || level1 == nextLevel1))
{
level2 = "";
}
prevLevel1 = level1;
// </Antony>
if (level2.isEmpty())
{
t << " <LI><OBJECT type=\"text/sitemap\">";
t << "<param name=\"Local\" value=\"" << field2URL(f.get(),FALSE);
t << "\">";
t << "<param name=\"Name\" value=\"" << convertToHtmlAndTruncate(m_recoder.recode(level1)) << "\">"
"</OBJECT>\n";
}
else
{
if (f->link)
{
t << " <LI><OBJECT type=\"text/sitemap\">";
t << "<param name=\"Local\" value=\"" << field2URL(f.get(),TRUE);
t << "\">";
t << "<param name=\"Name\" value=\"" << convertToHtmlAndTruncate(m_recoder.recode(level1)) << "\">"
"</OBJECT>\n";
}
else
{
t << " <LI><OBJECT type=\"text/sitemap\">";
t << "<param name=\"See Also\" value=\"" << convertToHtml(m_recoder.recode(level1)) << "\">";
t << "<param name=\"Name\" value=\"" << convertToHtmlAndTruncate(m_recoder.recode(level1)) << "\">"
"</OBJECT>\n";
}
}
}
if (!level2Started && !level2.isEmpty())
{ // start new list at level 2
t << " <UL>\n";
level2Started=TRUE;
}
else if (level2Started && level2.isEmpty())
{ // end list at level 2
t << " </UL>\n";
level2Started=FALSE;
}
if (level2Started)
{
t << " <LI><OBJECT type=\"text/sitemap\">";
t << "<param name=\"Local\" value=\"" << field2URL(f.get(),FALSE);
t << "\">";
t << "<param name=\"Name\" value=\"" << convertToHtmlAndTruncate(m_recoder.recode(level2)) << "\">"
"</OBJECT>\n";
}
}
if (level2Started) t << " </UL>\n";
}
//----------------------------------------------------------------------------
//
class HtmlHelp::Private
{
public:
Private() : index(recoder) {}
void createProjectFile();
std::ofstream cts,kts;
QCString prevFile;
QCString prevAnc;
bool ctsItemPresent = false;
int dc = 0;
StringSet indexFiles;
StringSet imageFiles;
StringSet styleFiles;
HtmlHelpRecoder recoder;
HtmlHelpIndex index;
};
/*! Constructs an html object.
* The object has to be \link initialize() initialized\endlink before it can
* be used.
*/
HtmlHelp::HtmlHelp() : p(std::make_unique<Private>()) {}
HtmlHelp::~HtmlHelp() = default;
/*! This will create a contents file (index.hhc) and a index file (index.hhk)
* and write the header of those files.
* It also creates a project file (index.hhp)
* \sa finalize()
*/
void HtmlHelp::initialize()
{
p->recoder.initialize();
/* open the contents file */
QCString fName = Config_getString(HTML_OUTPUT) + "/" + hhcFileName;
p->cts = Portable::openOutputStream(fName);
if (!p->cts.is_open())
{
term("Could not open file %s for writing\n",qPrint(fName));
}
/* Write the header of the contents file */
p->cts << "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">\n"
"<HTML><HEAD></HEAD><BODY>\n"
"<OBJECT type=\"text/site properties\">\n"
"<param name=\"FrameName\" value=\"right\">\n"
"</OBJECT>\n"
"<UL>\n";
/* open the index file */
fName = Config_getString(HTML_OUTPUT) + "/" + hhkFileName;
p->kts = Portable::openOutputStream(fName);
if (!p->kts.is_open())
{
term("Could not open file %s for writing\n",qPrint(fName));
}
/* Write the header of the contents file */
p->kts << "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\">\n"
"<HTML><HEAD></HEAD><BODY>\n"
"<OBJECT type=\"text/site properties\">\n"
"<param name=\"FrameName\" value=\"right\">\n"
"</OBJECT>\n"
"<UL>\n";
}
void HtmlHelp::Private::createProjectFile()
{
/* Write the project file */
QCString fName = Config_getString(HTML_OUTPUT) + "/" + hhpFileName;
std::ofstream t = Portable::openOutputStream(fName);
if (t.is_open())
{
QCString hhcFile = "\"" + hhcFileName + "\"";
QCString hhkFile = "\"" + hhkFileName + "\"";
bool hhkPresent = index.size()>0;
if (!ctsItemPresent) hhcFile = "";
if (!hhkPresent) hhkFile = "";
QCString indexName="index"+Doxygen::htmlFileExtension;
t << "[OPTIONS]\n";
if (!Config_getString(CHM_FILE).isEmpty())
{
t << "Compiled file=" << Config_getString(CHM_FILE) << "\n";
}
else
{
t << "Compiled file=index.chm\n";
}
t << "Compatibility=1.1\n"
"Full-text search=Yes\n";
if (ctsItemPresent) t << "Contents file=" + hhcFileName + "\n";
t << "Default Window=main\n"
"Default topic=" << indexName << "\n";
if (hhkPresent) t << "Index file=" + hhkFileName + "\n";
t << "Language=" << theTranslator->getLanguageString() << "\n";
if (Config_getBool(BINARY_TOC)) t << "Binary TOC=YES\n";
if (Config_getBool(GENERATE_CHI)) t << "Create CHI file=YES\n";
t << "Title=" << recoder.recode(Config_getString(PROJECT_NAME)) << "\n\n";
t << "[WINDOWS]\n";
// NOTE: the 0x10387e number is a set of bits specifying the buttons
// which should appear in the CHM viewer; that specific value
// means "show all buttons including the font-size one";
// the font-size one is not normally settable by the HTML Help Workshop
// utility but the way to set it is described here:
// http://support.microsoft.com/?scid=kb%3Ben-us%3B240062&x=17&y=18
// NOTE: the 0x70387e number in addition to the above the Next and Prev button
// are shown. They can only be shown in case of a binary toc.
// dee http://www.mif2go.com/xhtml/htmlhelp_0016_943addingtabsandtoolbarbuttonstohtmlhelp.htm#Rz108x95873
// Value has been taken from htmlhelp.h file of the HTML Help Workshop
if (Config_getBool(BINARY_TOC))
{
t << "main=\"" << recoder.recode(Config_getString(PROJECT_NAME)) << "\"," << hhcFile << ","
<< hhkFile << ",\"" << indexName << "\",\"" <<
indexName << "\",,,,,0x23520,,0x70387e,,,,,,,,0\n\n";
}
else
{
t << "main=\"" << recoder.recode(Config_getString(PROJECT_NAME)) << "\"," << hhcFile << ","
<< hhkFile << ",\"" << indexName << "\",\"" <<
indexName << "\",,,,,0x23520,,0x10387e,,,,,,,,0\n\n";
}
t << "[FILES]\n";
for (auto &s : indexFiles)
{
t << s.c_str() << "\n";
}
for (auto &s : imageFiles)
{
t << s.c_str() << "\n";
}
for (auto &s : styleFiles)
{
t << s.c_str() << "\n";
}
t.close();
}
else
{
err("Could not open file %s for writing\n",qPrint(fName));
}
}
void HtmlHelp::addIndexFile(const QCString &s)
{
p->indexFiles.insert(s.str());
}
/*! Finalizes the HTML help. This will finish and close the
* htmlhelp contents file and the htmlhelp index file.
* \sa initialize()
*/
void HtmlHelp::finalize()
{
// end the contents file
p->cts << "</UL>\n";
p->cts << "</BODY>\n";
p->cts << "</HTML>\n";
p->cts.close();
p->index.writeFields(p->kts);
// end the index file
p->kts << "</UL>\n";
p->kts << "</BODY>\n";
p->kts << "</HTML>\n";
p->kts.close();
p->createProjectFile();
p->recoder.finalize();
}
/*! Increase the level of the contents hierarchy.
* This will start a new unnumbered HTML list in contents file.
* \sa decContentsDepth()
*/
void HtmlHelp::incContentsDepth()
{
for (int i=0; i<p->dc+1; i++) p->cts << " ";
p->cts << "<UL>\n";
++p->dc;
}
/*! Decrease the level of the contents hierarchy.
* This will end the unnumber HTML list.
* \sa incContentsDepth()
*/
void HtmlHelp::decContentsDepth()
{
for (int i=0; i<p->dc; i++) p->cts << " ";
p->cts << "</UL>\n";
--p->dc;
}
/*! Add an list item to the contents file.
* \param isDir boolean indicating if this is a dir or file entry
* \param name the name of the item.
* \param ref the URL of to the item.
* \param file the file in which the item is defined.
* \param anchor the anchor of the item.
* \param separateIndex not used.
* \param addToNavIndex not used.
* \param def not used.
*/
void HtmlHelp::addContentsItem(bool isDir,
const QCString &name,
const QCString &ref,
const QCString &file,
const QCString &anchor,
bool /* separateIndex */,
bool /* addToNavIndex */,
const Definition * /* def */)
{
p->ctsItemPresent = true;
for (int i=0; i<p->dc; i++) p->cts << " ";
p->cts << "<LI><OBJECT type=\"text/sitemap\">";
p->cts << "<param name=\"Name\" value=\"" << convertToHtml(p->recoder.recode(name),TRUE) << "\">";
if (!file.isEmpty()) // made file optional param - KPW
{
if (file[0]=='!' || file[0]=='^') // special markers for user defined URLs
{
p->cts << "<param name=\"";
if (file[0]=='^') p->cts << "URL"; else p->cts << "Local";
p->cts << "\" value=\"";
p->cts << &file[1];
p->cts << "\">";
}
else
{
QCString currFile = file;
addHtmlExtensionIfMissing(currFile);
QCString currAnc = anchor;
p->cts << "<param name=\"Local\" value=\"";
if (!ref.isEmpty()) p->cts << externalRef("",ref,true);
p->cts << currFile;
if (p->prevFile == currFile && p->prevAnc.isEmpty() && currAnc.isEmpty())
{
currAnc = "top";
}
if (!currAnc.isEmpty()) p->cts << "#" << currAnc;
p->cts << "\">";
p->prevFile = currFile;
p->prevAnc = currAnc;
}
}
p->cts << "<param name=\"ImageNumber\" value=\"";
if (isDir) // added - KPW
{
p->cts << static_cast<int>(BOOK_CLOSED);
}
else
{
p->cts << static_cast<int>(TEXT);
}
p->cts << "\">";
p->cts << "</OBJECT>\n";
}
void HtmlHelp::addIndexItem(const Definition *context,const MemberDef *md,
const QCString §ionAnchor,const QCString &word)
{
if (context && md)
{
QCString cfname = md->getOutputFileBase();
QCString argStr = md->argsString();
QCString level1 = context->name();
QCString level2 = md->name() + argStr;
QCString anchor = !sectionAnchor.isEmpty() ? sectionAnchor : md->anchor();
p->index.addItem(level1,level2,cfname,anchor,TRUE,FALSE);
p->index.addItem(level2,level1,cfname,anchor,TRUE,TRUE);
}
else if (context)
{
QCString level1 = !word.isEmpty() ? word : context->name();
p->index.addItem(level1,QCString(),context->getOutputFileBase(),sectionAnchor,TRUE,FALSE);
}
}
void HtmlHelp::addStyleSheetFile(const QCString &fileName)
{
p->styleFiles.insert(fileName.str());
}
void HtmlHelp::addImageFile(const QCString &fileName)
{
p->imageFiles.insert(fileName.str());
}
| 18,862
|
C++
|
.cpp
| 584
| 27.458904
| 118
| 0.589106
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,430
|
reflist.cpp
|
doxygen_doxygen/src/reflist.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2020 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.
*
*/
#include <algorithm>
#include <stdio.h>
#include "reflist.h"
#include "util.h"
#include "definition.h"
#include "config.h"
RefList::RefList(const QCString &listName, const QCString &pageTitle, const QCString &secTitle) :
m_listName(listName), m_fileName(convertNameToFile(listName,FALSE,TRUE)),
m_pageTitle(pageTitle), m_secTitle(secTitle)
{
}
RefItem *RefList::add()
{
m_id++;
std::unique_ptr<RefItem> item = std::make_unique<RefItem>(m_id,this);
RefItem *result = item.get();
m_entries.push_back(std::move(item));
m_lookup.emplace(m_id,result);
return result;
}
RefItem *RefList::find(int itemId)
{
auto it = m_lookup.find(itemId);
return it!=m_lookup.end() ? it->second : nullptr;
}
bool RefList::isEnabled() const
{
if (m_listName=="todo" && !Config_getBool(GENERATE_TODOLIST)) return false;
else if (m_listName=="test" && !Config_getBool(GENERATE_TESTLIST)) return false;
else if (m_listName=="bug" && !Config_getBool(GENERATE_BUGLIST)) return false;
else if (m_listName=="deprecated" && !Config_getBool(GENERATE_DEPRECATEDLIST)) return false;
return true;
}
void RefList::generatePage()
{
if (!isEnabled()) return;
std::stable_sort(m_entries.begin(),m_entries.end(),
[](const std::unique_ptr<RefItem> &left,const std::unique_ptr<RefItem> &right)
{ return qstricmp_sort(left->title(),right->title()) < 0; });
//RefItem *item;
QCString doc;
int cnt = 0;
doc += "<dl class=\"reflist\">";
QCString lastGroup;
bool first=true;
for (const std::unique_ptr<RefItem> &item : m_entries)
{
if (item->name().isEmpty()) continue;
cnt++;
bool startNewGroup = item->group()!=lastGroup;
if (startNewGroup)
{
if (!first)
{
doc += "</dd>";
}
doc += " <dt>";
doc += "\n";
if (item->scope())
{
if (item->scope()->name() != "<globalScope>")
{
doc += "\\_setscope ";
doc += item->scope()->name();
doc += " ";
}
}
doc += item->prefix();
doc += " \\_internalref ";
doc += item->name();
// escape \'s in title, see issue #5901
QCString escapedTitle = substitute(item->title(),"\\","\\\\");
doc += " \""+escapedTitle+"\" ";
// write declaration in case a function with arguments
if (!item->args().isEmpty())
{
// escape @'s in argument list, needed for Java annotations (see issue #6208)
// escape \'s in argument list (see issue #6533)
doc += substitute(substitute(item->args(),"@","@@"),"\\","\\\\");
}
doc += "</dt><dd>";
}
else
{
doc += "<p>";
}
doc += " \\anchor ";
doc += item->anchor();
doc += " ";
doc += item->text();
lastGroup = item->group();
first = false;
}
if (!first)
{
doc += "</dd>";
}
doc += "</dl>\n";
//printf("generatePage('%s')\n",doc.data());
if (cnt>0)
{
addRelatedPage(m_listName,m_pageTitle,doc,m_fileName,1,1,RefItemVector(),nullptr,nullptr,TRUE);
}
}
| 3,742
|
C++
|
.cpp
| 118
| 27.347458
| 99
| 0.600387
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,431
|
searchindex.cpp
|
doxygen_doxygen/src/searchindex.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2020 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.
*
*/
#include <ctype.h>
#include <assert.h>
#include <mutex>
#include <map>
#include <unordered_map>
#include "searchindex.h"
#include "config.h"
#include "util.h"
#include "doxygen.h"
#include "language.h"
#include "pagedef.h"
#include "growbuf.h"
#include "message.h"
#include "groupdef.h"
#include "filedef.h"
#include "portable.h"
// file format: (all multi-byte values are stored in big endian format)
// 4 byte header
// 256*256*4 byte index (4 bytes)
// for each index entry: a zero terminated list of words
// for each word: a \0 terminated string + 4 byte offset to the stats info
// padding bytes to align at 4 byte boundary
// for each word: the number of urls (4 bytes)
// + for each url containing the word 8 bytes statistics
// (4 bytes index to url string + 4 bytes frequency counter)
// for each url: a \0 terminated string
const size_t numIndexEntries = 256*256;
static std::mutex g_searchIndexMutex;
//--------------------------------------------------------------------
void SearchIndex::IndexWord::addUrlIndex(int idx,bool hiPriority)
{
//printf("IndexWord::addUrlIndex(%d,%d)\n",idx,hiPriority);
auto it = m_urls.find(idx);
if (it==m_urls.end())
{
//printf("URLInfo::URLInfo(%d)\n",idx);
it = m_urls.emplace(idx,URLInfo(idx,0)).first;
}
it->second.freq+=2;
if (hiPriority) it->second.freq|=1; // mark as high priority document
}
//--------------------------------------------------------------------
SearchIndex::SearchIndex()
{
m_index.resize(numIndexEntries);
}
void SearchIndex::setCurrentDoc(const Definition *ctx,const QCString &anchor,bool isSourceFile)
{
if (ctx==nullptr) return;
std::lock_guard<std::mutex> lock(g_searchIndexMutex);
assert(!isSourceFile || ctx->definitionType()==Definition::TypeFile);
//printf("SearchIndex::setCurrentDoc(%s,%s,%s)\n",name,baseName,anchor);
QCString url=isSourceFile ? (toFileDef(ctx))->getSourceFileBase() : ctx->getOutputFileBase();
url+=Config_getString(HTML_FILE_EXTENSION);
QCString baseUrl = url;
if (!anchor.isEmpty()) url+=QCString("#")+anchor;
if (!isSourceFile) baseUrl=url;
QCString name=ctx->qualifiedName();
if (ctx->definitionType()==Definition::TypeMember)
{
const MemberDef *md = toMemberDef(ctx);
name.prepend((md->getLanguage()==SrcLangExt::Fortran ?
theTranslator->trSubprogram(TRUE,TRUE) :
theTranslator->trMember(TRUE,TRUE))+" ");
}
else // compound type
{
SrcLangExt lang = ctx->getLanguage();
QCString sep = getLanguageSpecificSeparator(lang);
if (sep!="::")
{
name = substitute(name,"::",sep);
}
switch (ctx->definitionType())
{
case Definition::TypePage:
{
const PageDef *pd = toPageDef(ctx);
if (pd->hasTitle())
{
name = theTranslator->trPage(TRUE,TRUE)+" "+pd->title();
}
else
{
name = theTranslator->trPage(TRUE,TRUE)+" "+pd->name();
}
}
break;
case Definition::TypeClass:
{
const ClassDef *cd = toClassDef(ctx);
name.prepend(cd->compoundTypeString()+" ");
}
break;
case Definition::TypeNamespace:
{
if (lang==SrcLangExt::Java || lang==SrcLangExt::CSharp)
{
name = theTranslator->trPackage(name);
}
else if (lang==SrcLangExt::Fortran)
{
name.prepend(theTranslator->trModule(TRUE,TRUE)+" ");
}
else
{
name.prepend(theTranslator->trNamespace(TRUE,TRUE)+" ");
}
}
break;
case Definition::TypeGroup:
{
const GroupDef *gd = toGroupDef(ctx);
if (!gd->groupTitle().isEmpty())
{
name = theTranslator->trGroup(TRUE,TRUE)+" "+gd->groupTitle();
}
else
{
name.prepend(theTranslator->trGroup(TRUE,TRUE)+" ");
}
}
break;
case Definition::TypeModule:
{
name.prepend(theTranslator->trModule(TRUE,TRUE)+" ");
}
break;
default:
break;
}
}
auto it = m_url2IdMap.find(baseUrl.str());
if (it == m_url2IdMap.end()) // new entry
{
m_urlIndex = m_urlMaxIndex++;
m_url2IdMap.emplace(baseUrl.str(),m_urlIndex);
m_urls.emplace(m_urlIndex,URL(name,url));
}
else // existing entry
{
m_urlIndex=it->second;
m_urls.emplace(it->second,URL(name,url));
}
}
static int charsToIndex(const QCString &word)
{
if (word.length()<2) return -1;
// Fast string hashing algorithm
//register uint16_t h=0;
//const char *k = word;
//uint16_t mask=0xfc00;
//while ( *k )
//{
// h = (h&mask)^(h<<6)^(*k++);
//}
//return h;
// Simple hashing that allows for substring searching
uint32_t c1=static_cast<uint8_t>(word[0]);
uint32_t c2=static_cast<uint8_t>(word[1]);
return c1*256+c2;
}
void SearchIndex::addWordRec(const QCString &word,bool hiPriority,bool recurse)
{
if (word.isEmpty()) return;
QCString wStr = QCString(word).lower();
//printf("SearchIndex::addWord(%s,%d) wStr=%s\n",word,hiPriority,qPrint(wStr));
int idx=charsToIndex(wStr);
if (idx<0 || idx>=static_cast<int>(m_index.size())) return;
auto it = m_words.find(wStr.str());
if (it==m_words.end())
{
//fprintf(stderr,"addWord(%s) at index %d\n",word,idx);
m_index[idx].emplace_back(wStr);
it = m_words.emplace( wStr.str(), static_cast<int>(m_index[idx].size())-1 ).first;
}
m_index[idx][it->second].addUrlIndex(m_urlIndex,hiPriority);
bool found=FALSE;
if (!recurse) // the first time we check if we can strip the prefix
{
int i=getPrefixIndex(word);
if (i>0)
{
addWordRec(word.data()+i,hiPriority,TRUE);
found=TRUE;
}
}
if (!found) // no prefix stripped
{
int i=0;
while (word[i]!=0 &&
!((word[i]=='_' || word[i]==':' || (word[i]>='a' && word[i]<='z')) && // [_a-z:]
(word[i+1]>='A' && word[i+1]<='Z'))) // [A-Z]
{
i++;
}
if (word[i]!=0 && i>=1)
{
addWordRec(word.data()+i+1,hiPriority,TRUE);
}
}
}
void SearchIndex::addWord(const QCString &word,bool hiPriority)
{
std::lock_guard<std::mutex> lock(g_searchIndexMutex);
addWordRec(word,hiPriority,FALSE);
}
static void writeInt(std::ostream &f,size_t index)
{
f.put(static_cast<int>((index>>24)&0xff));
f.put(static_cast<int>((index>>16)&0xff));
f.put(static_cast<int>((index>>8)&0xff));
f.put(static_cast<int>(index&0xff));
}
static void writeString(std::ostream &f,const QCString &s)
{
size_t l = s.length();
for (size_t i=0;i<l;i++) f.put(s[i]);
f.put(0);
}
void SearchIndex::write(const QCString &fileName)
{
size_t size=4; // for the header
size+=4*numIndexEntries; // for the index
size_t wordsOffset = size;
// first pass: compute the size of the wordlist
for (size_t i=0;i<numIndexEntries;i++)
{
const auto &wlist = m_index[i];
if (!wlist.empty())
{
for (const auto &iw : wlist)
{
size_t ws = iw.word().length()+1;
size+=ws+4; // word + url info list offset
}
size+=1; // zero list terminator
}
}
// second pass: compute the offsets in the index
size_t indexOffsets[numIndexEntries];
size_t offset=wordsOffset;
for (size_t i=0;i<numIndexEntries;i++)
{
const auto &wlist = m_index[i];
if (!wlist.empty())
{
indexOffsets[i]=offset;
for (const auto &iw : wlist)
{
offset+= iw.word().length()+1;
offset+=4; // word + offset to url info array
}
offset+=1; // zero list terminator
}
else
{
indexOffsets[i]=0;
}
}
size_t padding = size;
size = (size+3)&~3; // round up to 4 byte boundary
padding = size - padding;
std::vector<size_t> wordStatOffsets(m_words.size());
int count=0;
// third pass: compute offset to stats info for each word
for (size_t i=0;i<numIndexEntries;i++)
{
const auto &wlist = m_index[i];
if (!wlist.empty())
{
for (const auto &iw : wlist)
{
//printf("wordStatOffsets[%d]=%d\n",count,size);
wordStatOffsets[count++] = size;
size+=4 + iw.urls().size() * 8; // count + (url_index,freq) per url
}
}
}
std::vector<size_t> urlOffsets(m_urls.size());
for (const auto &udi : m_urls)
{
urlOffsets[udi.first]=size;
size+=udi.second.name.length()+1+
udi.second.url.length()+1;
}
//printf("Total size %x bytes (word=%x stats=%x urls=%x)\n",size,wordsOffset,statsOffset,urlsOffset);
std::ofstream f = Portable::openOutputStream(fileName);
if (f.is_open())
{
// write header
f.put('D'); f.put('O'); f.put('X'); f.put('S');
// write index
for (size_t i=0;i<numIndexEntries;i++)
{
writeInt(f,indexOffsets[i]);
}
// write word lists
count=0;
for (size_t i=0;i<numIndexEntries;i++)
{
const auto &wlist = m_index[i];
if (!wlist.empty())
{
for (const auto &iw : wlist)
{
writeString(f,iw.word());
writeInt(f,wordStatOffsets[count++]);
}
f.put(0);
}
}
// write extra padding bytes
for (size_t i=0;i<padding;i++) f.put(0);
// write word statistics
for (size_t i=0;i<numIndexEntries;i++)
{
const auto &wlist = m_index[i];
if (!wlist.empty())
{
for (const auto &iw : wlist)
{
size_t numUrls = iw.urls().size();
writeInt(f,numUrls);
for (const auto &ui : iw.urls())
{
writeInt(f,urlOffsets[ui.second.urlIdx]);
writeInt(f,ui.second.freq);
}
}
}
}
// write urls
for (const auto &udi : m_urls)
{
writeString(f,udi.second.name);
writeString(f,udi.second.url);
}
}
}
//---------------------------------------------------------------------------
// the following part is for writing an external search index
SearchIndexExternal::SearchIndexExternal()
{
}
static QCString definitionToName(const Definition *ctx)
{
if (ctx && ctx->definitionType()==Definition::TypeMember)
{
const MemberDef *md = toMemberDef(ctx);
if (md->isFunction())
return "function";
else if (md->isSlot())
return "slot";
else if (md->isSignal())
return "signal";
else if (md->isVariable())
return "variable";
else if (md->isTypedef())
return "typedef";
else if (md->isEnumerate())
return "enum";
else if (md->isEnumValue())
return "enumvalue";
else if (md->isProperty())
return "property";
else if (md->isEvent())
return "event";
else if (md->isRelated() || md->isForeign())
return "related";
else if (md->isFriend())
return "friend";
else if (md->isDefine())
return "define";
}
else if (ctx)
{
switch(ctx->definitionType())
{
case Definition::TypeClass:
return (toClassDef(ctx))->compoundTypeString();
case Definition::TypeFile:
return "file";
case Definition::TypeNamespace:
return "namespace";
case Definition::TypeConcept:
return "concept";
case Definition::TypeGroup:
return "group";
case Definition::TypePackage:
return "package";
case Definition::TypePage:
return "page";
case Definition::TypeDir:
return "dir";
case Definition::TypeModule:
return "module";
default:
break;
}
}
return "unknown";
}
void SearchIndexExternal::setCurrentDoc(const Definition *ctx,const QCString &anchor,bool isSourceFile)
{
std::lock_guard<std::mutex> lock(g_searchIndexMutex);
QCString extId = stripPath(Config_getString(EXTERNAL_SEARCH_ID));
QCString url = isSourceFile ? (toFileDef(ctx))->getSourceFileBase() : ctx->getOutputFileBase();
addHtmlExtensionIfMissing(url);
if (!anchor.isEmpty()) url+=QCString("#")+anchor;
QCString key = extId+";"+url;
auto it = m_docEntries.find(key.str());
if (it == m_docEntries.end())
{
SearchDocEntry e;
e.type = isSourceFile ? QCString("source") : definitionToName(ctx);
e.name = ctx->qualifiedName();
if (ctx->definitionType()==Definition::TypeMember)
{
e.args = (toMemberDef(ctx))->argsString();
}
else if (ctx->definitionType()==Definition::TypeGroup)
{
const GroupDef *gd = toGroupDef(ctx);
if (!gd->groupTitle().isEmpty())
{
e.name = filterTitle(gd->groupTitle());
}
}
else if (ctx->definitionType()==Definition::TypePage)
{
const PageDef *pd = toPageDef(ctx);
if (pd->hasTitle())
{
e.name = filterTitle(pd->title());
}
}
e.extId = extId;
e.url = url;
it = m_docEntries.emplace(key.str(),e).first;
//printf("searchIndexExt %s : %s\n",qPrint(e->name),qPrint(e->url));
}
m_current = &it->second;
}
void SearchIndexExternal::addWord(const QCString &word,bool hiPriority)
{
std::lock_guard<std::mutex> lock(g_searchIndexMutex);
if (word.isEmpty() || !isId(word[0]) || m_current==nullptr) return;
GrowBuf *pText = hiPriority ? &m_current->importantText : &m_current->normalText;
if (pText->getPos()>0) pText->addChar(' ');
pText->addStr(word);
//printf("addWord %s\n",word);
}
void SearchIndexExternal::write(const QCString &fileName)
{
std::ofstream t = Portable::openOutputStream(fileName);
if (t.is_open())
{
t << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
t << "<add>\n";
for (auto &[name,doc] : m_docEntries)
{
doc.normalText.addChar(0); // make sure buffer ends with a 0 terminator
doc.importantText.addChar(0); // make sure buffer ends with a 0 terminator
t << " <doc>\n";
t << " <field name=\"type\">" << doc.type << "</field>\n";
t << " <field name=\"name\">" << convertToXML(doc.name) << "</field>\n";
if (!doc.args.isEmpty())
{
t << " <field name=\"args\">" << convertToXML(doc.args) << "</field>\n";
}
if (!doc.extId.isEmpty())
{
t << " <field name=\"tag\">" << convertToXML(doc.extId) << "</field>\n";
}
t << " <field name=\"url\">" << convertToXML(doc.url) << "</field>\n";
t << " <field name=\"keywords\">" << convertToXML(doc.importantText.get()) << "</field>\n";
t << " <field name=\"text\">" << convertToXML(doc.normalText.get()) << "</field>\n";
t << " </doc>\n";
}
t << "</add>\n";
}
else
{
err("Failed to open file %s for writing!\n",qPrint(fileName));
}
}
//---------------------------------------------------------------------------------------------
void initSearchIndexer()
{
bool searchEngine = Config_getBool(SEARCHENGINE);
bool serverBasedSearch = Config_getBool(SERVER_BASED_SEARCH);
bool externalSearch = Config_getBool(EXTERNAL_SEARCH);
if (searchEngine && serverBasedSearch)
{
Doxygen::searchIndex.setKind(externalSearch ? SearchIndexIntf::External : SearchIndexIntf::Internal);
}
}
void finalizeSearchIndexer()
{
Doxygen::searchIndex.setKind(SearchIndexIntf::Disabled);
}
| 15,953
|
C++
|
.cpp
| 516
| 25.825581
| 105
| 0.597247
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,432
|
image.cpp
|
doxygen_doxygen/src/image.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2022 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.
*
*/
#include <vector>
#include <cmath>
#include "image.h"
#include "lodepng.h"
#include "config.h"
typedef unsigned char Byte;
/** Helper struct representing a RGBA color */
struct Color
{
Byte red;
Byte green;
Byte blue;
Byte alpha;
};
const int charSetWidth=80;
const int charHeight=12;
const int numChars=96;
const unsigned short charPos[numChars] =
{
0, 5, 8, 13, 20, 27, 38, 47,
50, 54, 58, 65, 72, 76, 83, 87,
91, 98,105,112,119,126,133,140,
147,154,161,164,167,174,181,188,
195,207,216,224,233,242,250,258,
267,276,279,286,294,301,312,321,
331,339,349,357,365,372,380,389,
400,409,418,427,430,434,437,443,
450,453,460,467,474,481,488,492,
499,506,509,512,518,521,530,537,
544,551,557,562,568,571,578,585,
594,600,607,613,617,620,624,631
};
const unsigned char charWidth[numChars] =
{
5, 3, 5, 7, 7,11, 9, 3,
4, 4, 7, 7, 4, 7, 4, 4,
7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 3, 3, 7, 7, 7, 7,
12, 9, 8, 9, 9, 8, 8, 9,
9, 3, 7, 8, 7,11, 9,10,
8,10, 8, 8, 7, 8, 9,11,
9, 9, 9, 3, 4, 3, 6, 7,
3, 7, 7, 7, 7, 7, 4, 7,
7, 3, 3, 6, 3, 9, 7, 7,
7, 6, 5, 6, 3, 7, 7, 9,
6, 7, 6, 4, 3, 4, 7, 5
};
const unsigned char fontRaw[charSetWidth*charHeight] = {
0x02, 0x50, 0x01, 0x06, 0x20, 0x60, 0xc6, 0x04, 0x00, 0x00, 0x00, 0x27,
0x04, 0x1c, 0x38, 0x11, 0xf1, 0xc7, 0xc7, 0x0e, 0x00, 0x00, 0x00, 0x03,
0x81, 0xf0, 0x10, 0x7c, 0x1e, 0x3e, 0x1f, 0x9f, 0x87, 0x88, 0x24, 0x09,
0x09, 0x02, 0x02, 0x41, 0x0f, 0x0f, 0x83, 0xc3, 0xe1, 0xe7, 0xf4, 0x24,
0x12, 0x22, 0x41, 0x20, 0x9f, 0xce, 0x30, 0x00, 0x10, 0x04, 0x00, 0x01,
0x00, 0x30, 0x08, 0x12, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
0x00, 0x00, 0x00, 0x00, 0x01, 0xac, 0x00, 0x00, 0x02, 0x51, 0x43, 0x89,
0x40, 0x90, 0x49, 0x15, 0x00, 0x00, 0x00, 0x28, 0x9c, 0x22, 0x44, 0x31,
0x02, 0x20, 0x48, 0x91, 0x00, 0x00, 0x00, 0x04, 0x46, 0x08, 0x28, 0x42,
0x21, 0x21, 0x10, 0x10, 0x08, 0x48, 0x24, 0x09, 0x11, 0x03, 0x06, 0x61,
0x10, 0x88, 0x44, 0x22, 0x12, 0x10, 0x84, 0x24, 0x12, 0x22, 0x22, 0x20,
0x80, 0x4a, 0x11, 0x00, 0x20, 0x04, 0x00, 0x01, 0x00, 0x40, 0x08, 0x00,
0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00,
0x02, 0x22, 0x00, 0x00, 0x02, 0x51, 0x45, 0x49, 0x40, 0x90, 0x89, 0x0a,
0x00, 0x00, 0x00, 0x48, 0x84, 0x02, 0x04, 0x51, 0x02, 0x00, 0x88, 0x91,
0x00, 0x00, 0x00, 0x04, 0x44, 0xd4, 0x28, 0x42, 0x40, 0x20, 0x90, 0x10,
0x10, 0x08, 0x24, 0x09, 0x21, 0x03, 0x06, 0x51, 0x20, 0x48, 0x48, 0x12,
0x12, 0x00, 0x84, 0x22, 0x22, 0x22, 0x22, 0x11, 0x00, 0x89, 0x12, 0x80,
0x31, 0xc5, 0x87, 0x0d, 0x1c, 0xe3, 0x4b, 0x12, 0x49, 0x29, 0x16, 0x1c,
0x58, 0x69, 0x4c, 0xe8, 0x91, 0x44, 0x61, 0x44, 0xf2, 0x22, 0x00, 0x00,
0x02, 0x07, 0xe5, 0x06, 0x80, 0x60, 0x10, 0x95, 0x08, 0x00, 0x00, 0x48,
0x84, 0x04, 0x18, 0x51, 0xe2, 0xc0, 0x87, 0x11, 0x24, 0x18, 0x03, 0x00,
0x89, 0x24, 0x44, 0x42, 0x40, 0x20, 0x90, 0x10, 0x10, 0x08, 0x24, 0x09,
0x41, 0x02, 0x8a, 0x51, 0x20, 0x48, 0x48, 0x12, 0x11, 0x80, 0x84, 0x22,
0x21, 0x24, 0x14, 0x11, 0x01, 0x09, 0x14, 0x40, 0x02, 0x26, 0x48, 0x93,
0x22, 0x44, 0xcc, 0x92, 0x51, 0x36, 0x99, 0x22, 0x64, 0x99, 0x92, 0x48,
0x91, 0x44, 0x52, 0x44, 0x12, 0x22, 0x00, 0x00, 0x02, 0x01, 0x43, 0x80,
0x80, 0xa0, 0x10, 0x84, 0x08, 0x00, 0x00, 0x88, 0x84, 0x08, 0x04, 0x90,
0x13, 0x21, 0x08, 0x8f, 0x00, 0x61, 0xf0, 0xc0, 0x8a, 0x24, 0x44, 0x7c,
0x40, 0x20, 0x9f, 0x9f, 0x11, 0xcf, 0xe4, 0x09, 0xc1, 0x02, 0x8a, 0x49,
0x20, 0x4f, 0x88, 0x13, 0xe0, 0x60, 0x84, 0x22, 0x21, 0x54, 0x08, 0x0a,
0x02, 0x08, 0x90, 0x00, 0x00, 0x24, 0x48, 0x11, 0x22, 0x44, 0x48, 0x92,
0x61, 0x24, 0x91, 0x22, 0x44, 0x89, 0x10, 0x48, 0x91, 0x24, 0x8c, 0x44,
0x22, 0x22, 0x64, 0x00, 0x02, 0x07, 0xe1, 0x41, 0x31, 0x14, 0x10, 0x80,
0x3e, 0x07, 0xc0, 0x88, 0x84, 0x10, 0x05, 0x10, 0x12, 0x21, 0x08, 0x81,
0x01, 0x80, 0x00, 0x31, 0x0a, 0x24, 0x7c, 0x42, 0x40, 0x20, 0x90, 0x10,
0x10, 0x48, 0x24, 0x09, 0x21, 0x02, 0x52, 0x45, 0x20, 0x48, 0x08, 0x92,
0x20, 0x10, 0x84, 0x21, 0x41, 0x54, 0x14, 0x04, 0x04, 0x08, 0x90, 0x00,
0x01, 0xe4, 0x48, 0x11, 0x3e, 0x44, 0x48, 0x92, 0x61, 0x24, 0x91, 0x22,
0x44, 0x89, 0x0c, 0x48, 0x8a, 0x24, 0x8c, 0x48, 0x44, 0x21, 0x98, 0x00,
0x02, 0x02, 0x85, 0x41, 0x49, 0x08, 0x10, 0x80, 0x08, 0x00, 0x00, 0x88,
0x84, 0x20, 0x45, 0xf9, 0x12, 0x21, 0x08, 0x81, 0x00, 0x61, 0xf0, 0xc1,
0x0a, 0x68, 0x82, 0x42, 0x40, 0x20, 0x90, 0x10, 0x10, 0x48, 0x24, 0x89,
0x11, 0x02, 0x52, 0x45, 0x20, 0x48, 0x08, 0x52, 0x12, 0x10, 0x84, 0x21,
0x40, 0x88, 0x22, 0x04, 0x08, 0x08, 0x90, 0x00, 0x02, 0x24, 0x48, 0x11,
0x20, 0x44, 0x48, 0x92, 0x51, 0x24, 0x91, 0x22, 0x44, 0x89, 0x02, 0x48,
0x8a, 0x2a, 0x92, 0x28, 0x42, 0x22, 0x00, 0x00, 0x00, 0x02, 0x85, 0x41,
0x49, 0x18, 0x10, 0x80, 0x08, 0x00, 0x01, 0x08, 0x84, 0x20, 0x44, 0x11,
0x12, 0x22, 0x08, 0x91, 0x00, 0x18, 0x03, 0x00, 0x09, 0xb0, 0x82, 0x42,
0x21, 0x21, 0x10, 0x10, 0x08, 0xc8, 0x24, 0x89, 0x09, 0x02, 0x22, 0x43,
0x10, 0x88, 0x04, 0x22, 0x12, 0x10, 0x84, 0x20, 0x80, 0x88, 0x22, 0x04,
0x10, 0x08, 0x50, 0x00, 0x02, 0x26, 0x48, 0x93, 0x22, 0x44, 0xc8, 0x92,
0x49, 0x24, 0x91, 0x22, 0x64, 0x99, 0x12, 0x49, 0x84, 0x11, 0x21, 0x28,
0x82, 0x22, 0x00, 0x00, 0x02, 0x02, 0x83, 0x82, 0x30, 0xe4, 0x10, 0x80,
0x00, 0x20, 0x05, 0x07, 0x04, 0x3e, 0x38, 0x10, 0xe1, 0xc2, 0x07, 0x0e,
0x24, 0x00, 0x00, 0x01, 0x04, 0x00, 0x82, 0x7c, 0x1e, 0x3e, 0x1f, 0x90,
0x07, 0x48, 0x24, 0x71, 0x05, 0xf2, 0x22, 0x41, 0x0f, 0x08, 0x03, 0xd2,
0x11, 0xe0, 0x83, 0xc0, 0x80, 0x88, 0x41, 0x04, 0x1f, 0xc8, 0x50, 0x00,
0x01, 0xd5, 0x87, 0x0d, 0x1c, 0x43, 0x48, 0x92, 0x45, 0x24, 0x91, 0x1c,
0x58, 0x69, 0x0c, 0x66, 0x84, 0x11, 0x21, 0x10, 0xf2, 0x22, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x20, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x03, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x10, 0x02, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0x10, 0x1f, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x04, 0x40, 0x02,
0x00, 0x00, 0x00, 0x00, 0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20,
0x02, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x30, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x04, 0x00, 0x00, 0x00, 0x00,
0x40, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0xac, 0x00, 0x00
};
struct Image::Private
{
uint32_t width;
uint32_t height;
std::vector<uint8_t> data;
std::vector<Color> palette =
{
{ 0xff, 0xff, 0xff, 0x00 },
{ 0x00, 0x00, 0x00, 0xff },
{ 0xff, 0xff, 0xc0, 0xff },
{ 0x9f, 0x9f, 0x60, 0xff },
{ 0xa7, 0x38, 0x30, 0xff },
{ 0x29, 0x70, 0x18, 0xff },
{ 0x97, 0xCC, 0xE8, 0xff },
{ 0xe0, 0xe0, 0xe0, 0xff },
{ 0xff, 0xff, 0xff, 0xff }
};
};
Image::Image(uint32_t w,uint32_t h) : p(std::make_unique<Private>())
{
int hue = Config_getInt(HTML_COLORSTYLE_HUE);
int sat = Config_getInt(HTML_COLORSTYLE_SAT);
int gamma = Config_getInt(HTML_COLORSTYLE_GAMMA);
double red1=0.0 ,green1=0.0 ,blue1=0.0;
double red2=0.0, green2=0.0, blue2=0.0;
ColoredImage::hsl2rgb(hue/360.0, // hue
sat/255.0, // saturation
pow(235/255.0,gamma/100.0), // luma (gamma corrected)
&red1,&green1,&blue1
);
ColoredImage::hsl2rgb(hue/360.0, // hue
sat/255.0, // saturation
pow(138/255.0,gamma/100.0), // luma (gamma corrected)
&red2,&green2,&blue2
);
p->palette[2].red = static_cast<Byte>(red1 * 255.0);
p->palette[2].green = static_cast<Byte>(green1 * 255.0);
p->palette[2].blue = static_cast<Byte>(blue1 * 255.0);
p->palette[3].red = static_cast<Byte>(red2 * 255.0);
p->palette[3].green = static_cast<Byte>(green2 * 255.0);
p->palette[3].blue = static_cast<Byte>(blue2 * 255.0);
p->data.resize(w*h);
p->width = w;
p->height = h;
}
uint32_t Image::width() const { return p->width; }
uint32_t Image::height() const { return p->height; }
Image::~Image() = default;
void Image::setPixel(uint32_t x,uint32_t y,uint8_t val)
{
if (x<p->width && y<p->height) p->data[y*p->width+x] = val;
}
uint8_t Image::getPixel(uint32_t x,uint32_t y) const
{
return (x<p->width && y<p->height) ? p->data[y*p->width+x] : 0;
}
void Image::writeChar(uint32_t x,uint32_t y,char c,uint8_t fg)
{
if (c>=' ')
{
uint32_t ci=c-' ';
uint32_t rowOffset=0;
uint32_t cw = charWidth[ci];
uint32_t cp = charPos[ci];
for (uint32_t yf=0;yf<charHeight;yf++)
{
unsigned short bitPattern=0;
uint32_t bitsLeft=cw;
uint32_t byteOffset = rowOffset+(cp>>3);
uint32_t bitOffset = cp&7;
// get the bit pattern for row yf of the character from the font data
while (bitsLeft>0)
{
uint32_t bits=8-bitOffset;
if (bits>bitsLeft) bits=bitsLeft;
bitPattern<<=bits;
bitPattern|=((fontRaw[byteOffset]<<bitOffset)&0xff)>>(8-bits);
bitsLeft-=bits;
bitOffset=0;
byteOffset++;
}
if (cw>0 && cw<32)
{
uint32_t mask=(uint32_t)1<<(cw-1);
// draw character row yf
for (uint32_t xf=0;xf<cw;xf++)
{
setPixel(x+xf,y+yf,(bitPattern&mask) ? fg : getPixel(x+xf,y+yf));
mask>>=1;
}
rowOffset+=charSetWidth;
}
}
}
}
void Image::writeString(uint32_t x,uint32_t y,const QCString &s,uint8_t fg)
{
if (!s.isEmpty())
{
const char *ps = s.data();
char c = 0;
while ((c=*ps++))
{
writeChar(x,y,c,fg);
x+=charWidth[c-' '];
}
}
}
uint32_t Image::stringLength(const QCString &s)
{
uint32_t w=0;
if (!s.isEmpty())
{
const char *ps = s.data();
char c = 0;
while ((c=*ps++)) w+=charWidth[c-' '];
}
return w;
}
void Image::drawHorzLine(uint32_t y,uint32_t xs,uint32_t xe,uint8_t colIndex,uint32_t mask)
{
uint32_t i=0,j=0;
for (uint32_t x=xs;x<=xe;x++,j++)
{
if (j&1) i++;
if (mask&(1<<(i&0x1f))) setPixel(x,y,colIndex);
}
}
void Image::drawHorzArrow(uint32_t y,uint32_t xs,uint32_t xe,uint8_t colIndex,uint32_t mask)
{
drawHorzLine(y,xs,xe,colIndex,mask);
for (uint32_t i=0;i<6;i++)
{
uint32_t h=i>>1;
drawVertLine(xe-i,y-h,y+h,colIndex,0xffffffff);
}
}
void Image::drawVertLine(uint32_t x,uint32_t ys,uint32_t ye,uint8_t colIndex,uint32_t mask)
{
uint32_t i=0;
for (uint32_t y=ys;y<=ye;y++,i++)
{
if (mask&(1<<(i&0x1f))) setPixel(x,y,colIndex);
}
}
void Image::drawVertArrow(uint32_t x,uint32_t ys,uint32_t ye,uint8_t colIndex,uint32_t mask)
{
drawVertLine(x,ys,ye,colIndex,mask);
for (uint32_t i=0;i<6;i++)
{
uint32_t h=i>>1;
drawHorzLine(ys+i,x-h,x+h,colIndex,0xffffffff);
}
}
void Image::drawRect(uint32_t x,uint32_t y,uint32_t w,uint32_t h,uint8_t colIndex,uint32_t mask)
{
drawHorzLine(y,x,x+w-1,colIndex,mask);
drawHorzLine(y+h-1,x,x+w-1,colIndex,mask);
drawVertLine(x,y,y+h-1,colIndex,mask);
drawVertLine(x+w-1,y,y+h-1,colIndex,mask);
}
void Image::fillRect(uint32_t x,uint32_t y,uint32_t width,uint32_t height,uint8_t colIndex,uint32_t mask)
{
for (uint32_t yp=y,yi=0;yp<y+height;yp++,yi++)
for (uint32_t xp=x,xi=0;xp<x+width;xp++,xi++)
if (mask&(1<<((xi+yi)&0x1f)))
setPixel(xp,yp,colIndex);
else
setPixel(xp,yp,8);
}
bool Image::save(const QCString &fileName)
{
uint8_t* buffer = nullptr;
size_t bufferSize = 0;
LodePNG_Encoder encoder;
LodePNG_Encoder_init(&encoder);
for (const auto &col : p->palette)
{
LodePNG_InfoColor_addPalette(&encoder.infoPng.color,
col.red,col.green,col.blue,col.alpha);
}
encoder.infoPng.color.colorType = 3;
encoder.infoRaw.color.colorType = 3;
LodePNG_encode(&encoder, &buffer, &bufferSize, &p->data[0], p->width, p->height);
LodePNG_saveFile(buffer, bufferSize, fileName.data());
free(buffer);
LodePNG_Encoder_cleanup(&encoder);
return TRUE;
}
//----------------------------------------------------------------
void ColoredImage::hsl2rgb(double h,double s,double l,
double *pRed,double *pGreen,double *pBlue)
{
double r = l; // default to gray
double g = l;
double b = l;
double v = (l <= 0.5) ? (l * (1.0 + s)) : (l + s - l * s);
if (v > 0)
{
double m = l + l - v;
double sv = ( v - m ) / v;
h *= 6.0;
int sextant = static_cast<int>(h);
double fract = h - sextant;
double vsf = v * sv * fract;
double mid1 = m + vsf;
double mid2 = v - vsf;
switch (sextant)
{
case 0:
r = v;
g = mid1;
b = m;
break;
case 1:
r = mid2;
g = v;
b = m;
break;
case 2:
r = m;
g = v;
b = mid1;
break;
case 3:
r = m;
g = mid2;
b = v;
break;
case 4:
r = mid1;
g = m;
b = v;
break;
case 5:
r = v;
g = m;
b = mid2;
break;
}
}
*pRed = r;
*pGreen = g;
*pBlue = b;
}
struct ColoredImage::Private
{
uint32_t width;
uint32_t height;
std::vector<uint8_t> data;
bool hasAlpha;
};
ColoredImage::ColoredImage(uint32_t width,uint32_t height,
const uint8_t *greyLevels,const uint8_t *alphaLevels,
int saturation,int hue,int gamma) : p(std::make_unique<Private>())
{
p->hasAlpha = alphaLevels!=nullptr;
p->width = width;
p->height = height;
p->data.resize(width*height*4);
for (uint32_t i=0;i<width*height;i++)
{
double red=0.0, green=0.0, blue=0.0;
hsl2rgb(hue/360.0, // hue
saturation/255.0, // saturation
pow(greyLevels[i]/255.0,gamma/100.0), // luma (gamma corrected)
&red,&green,&blue);
Byte r = static_cast<Byte>(red *255.0);
Byte g = static_cast<Byte>(green*255.0);
Byte b = static_cast<Byte>(blue *255.0);
Byte a = alphaLevels ? alphaLevels[i] : 255;
p->data[i*4+0]=r;
p->data[i*4+1]=g;
p->data[i*4+2]=b;
p->data[i*4+3]=a;
}
}
ColoredImage::~ColoredImage() = default;
bool ColoredImage::save(const QCString &fileName)
{
uint8_t *buffer = nullptr;
size_t bufferSize = 0;
LodePNG_Encoder encoder;
LodePNG_Encoder_init(&encoder);
encoder.infoPng.color.colorType = p->hasAlpha ? 6 : 2; // 2=RGB 24 bit, 6=RGBA 32 bit
encoder.infoRaw.color.colorType = 6; // 6=RGBA 32 bit
LodePNG_encode(&encoder, &buffer, &bufferSize, &p->data[0], p->width, p->height);
LodePNG_saveFile(buffer, bufferSize, fileName.data());
LodePNG_Encoder_cleanup(&encoder);
free(buffer);
return TRUE;
}
| 16,336
|
C++
|
.cpp
| 435
| 33.050575
| 105
| 0.61005
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,433
|
utf8.cpp
|
doxygen_doxygen/src/utf8.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2021 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.
*
*/
#include <cstdint>
#include <sstream>
#include "utf8.h"
#include "caseconvert.h"
#include "textstream.h"
uint8_t getUTF8CharNumBytes(char c)
{
uint8_t num=1;
unsigned char uc = static_cast<unsigned char>(c);
if (uc>=0x80u) // multibyte character
{
if ((uc&0xE0u)==0xC0u)
{
num=2; // 110x.xxxx: 2 byte character
}
if ((uc&0xF0u)==0xE0u)
{
num=3; // 1110.xxxx: 3 byte character
}
if ((uc&0xF8u)==0xF0u)
{
num=4; // 1111.0xxx: 4 byte character
}
if ((uc&0xFCu)==0xF8u)
{
num=5; // 1111.10xx: 5 byte character
}
if ((uc&0xFEu)==0xFCu)
{
num=6; // 1111.110x: 6 byte character
}
}
return num;
}
//! Decodes a given input of utf8 data to a unicode code point
//! given the number of bytes it's made of
static inline uint32_t decode_utf8( const char* data , int numBytes ) noexcept
{
uint32_t cp = static_cast<unsigned char>(*data);
if (numBytes>1)
{
cp &= 0x7F >> numBytes; // Mask out the header bits
for (int i=1 ; i<numBytes ; i++)
{
cp = (cp<<6) | (static_cast<unsigned char>(data[i])&0x3F);
}
}
return cp;
}
static inline uint32_t convertUTF8CharToUnicode(const char *s,size_t bytesLeft,int &len)
{
if (s==nullptr || bytesLeft==0)
{
len=0;
return 0;
}
unsigned char uc = static_cast<unsigned char>(*s);
if (uc<128) // ASCII case
{
len=1;
return uc;
}
switch (bytesLeft)
{
default:
if ((uc&0xFEu)==0xFCu)// 1111110X six bytes
{
len=6;
return decode_utf8(s,len);
}
// fall through
case 5:
if ((uc&0xFCu)==0xF8u) // 111110XX five bytes
{
len=5;
return decode_utf8(s,len);
}
// fall through
case 4:
if ((uc&0xF8u)==0xF0u) // 11110XXX four bytes
{
len=4;
return decode_utf8(s,len);
}
// fall through
case 3:
if ((uc&0xF0u)==0xE0u) // 1110XXXX three bytes
{
len=3;
return decode_utf8(s,len);
}
// fall through
case 2:
if ((uc&0xE0u)==0xC0u) // 110XXXXX two bytes
{
len=2;
return decode_utf8(s,len);
}
// fall through
case 1:
{
len=1;
return uc;
}
}
}
std::string getUTF8CharAt(const std::string &input,size_t pos)
{
if (input.length()<=pos) return std::string();
int numBytes=getUTF8CharNumBytes(input[pos]);
if (input.length()<pos+numBytes) return std::string();
return input.substr(pos,numBytes);
}
uint32_t getUnicodeForUTF8CharAt(const std::string &input,size_t pos)
{
std::string charS = getUTF8CharAt(input,pos);
int len=0;
return convertUTF8CharToUnicode(charS.c_str(),charS.length(),len);
}
static inline char asciiToLower(uint32_t code)
{
return code>='A' && code<='Z' ? static_cast<char>(code+'a'-'A') : static_cast<char>(code);
}
static inline char asciiToUpper(uint32_t code)
{
return code>='a' && code<='z' ? static_cast<char>(code+'A'-'a') : static_cast<char>(code);
}
static inline std::string caseConvert(const std::string &input,
char (*asciiConversionFunc)(uint32_t code),
const char *(*conversionFunc)(uint32_t code))
{
uint32_t code=0;
std::string result;
result.reserve(input.length()); // assume all ASCII characters
int len=0;
size_t bytesLeft = input.length();
const char *p = input.c_str();
while ((code=convertUTF8CharToUnicode(p,bytesLeft,len)))
{
if (code<128) // ASCII case
{
char c = asciiConversionFunc(code);
result+=c;
}
else // generic case
{
const char *conv = conversionFunc(code);
if (conv==nullptr) // no difference between lower and upper case
{
result.append(p,len);
}
else // replace the input character with the conversion result
{
result.append(conv);
}
}
p+=len;
bytesLeft-=len;
}
return result;
}
std::string convertUTF8ToLower(const std::string &input)
{
return caseConvert(input,asciiToLower,convertUnicodeToLower);
}
std::string convertUTF8ToUpper(const std::string &input)
{
return caseConvert(input,asciiToUpper,convertUnicodeToUpper);
}
const char *writeUTF8Char(TextStream &t,const char *s)
{
if (s==nullptr) return nullptr;
uint8_t len = getUTF8CharNumBytes(*s);
for (uint8_t i=0;i<len;i++)
{
if (s[i]==0) // detect premature end of string (due to invalid UTF8 char)
{
len=i;
}
}
t.write(s,len);
return s+len;
}
bool lastUTF8CharIsMultibyte(const std::string &input)
{
// last byte is part of a multibyte UTF8 char if bit 8 is set and bit 7 is not
return !input.empty() && (static_cast<unsigned char>(input[input.length()-1])&0xC0)==0x80;
}
bool isUTF8CharUpperCase(const std::string &input,size_t pos)
{
if (input.length()<=pos) return false;
int len=0;
// turn the UTF8 character at position pos into a unicode value
uint32_t code = convertUTF8CharToUnicode(input.c_str()+pos,input.length()-pos,len);
// check if the character can be converted to lower case, if so it was an upper case character
return convertUnicodeToLower(code)!=nullptr;
}
int isUTF8NonBreakableSpace(const char *input)
{
return (static_cast<unsigned char>(input[0])==0xC2 &&
static_cast<unsigned char>(input[1])==0xA0) ? 2 : 0;
}
bool isUTF8PunctuationCharacter(uint32_t unicode)
{
bool b = isPunctuationCharacter(unicode);
return b;
}
| 6,134
|
C++
|
.cpp
| 221
| 23.420814
| 96
| 0.643936
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,434
|
xmldocvisitor.cpp
|
doxygen_doxygen/src/xmldocvisitor.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2020 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.
*
*/
#include "xmldocvisitor.h"
#include "docparser.h"
#include "language.h"
#include "doxygen.h"
#include "outputgen.h"
#include "xmlgen.h"
#include "dot.h"
#include "message.h"
#include "util.h"
#include "parserintf.h"
#include "filename.h"
#include "config.h"
#include "htmlentity.h"
#include "emoji.h"
#include "filedef.h"
#include "fileinfo.h"
#include "codefragment.h"
static void startSimpleSect(TextStream &t,const DocSimpleSect &s)
{
t << "<simplesect kind=\"";
switch(s.type())
{
case DocSimpleSect::See:
t << "see"; break;
case DocSimpleSect::Return:
t << "return"; break;
case DocSimpleSect::Author:
t << "author"; break;
case DocSimpleSect::Authors:
t << "authors"; break;
case DocSimpleSect::Version:
t << "version"; break;
case DocSimpleSect::Since:
t << "since"; break;
case DocSimpleSect::Date:
t << "date"; break;
case DocSimpleSect::Note:
t << "note"; break;
case DocSimpleSect::Warning:
t << "warning"; break;
case DocSimpleSect::Pre:
t << "pre"; break;
case DocSimpleSect::Post:
t << "post"; break;
case DocSimpleSect::Copyright:
t << "copyright"; break;
case DocSimpleSect::Invar:
t << "invariant"; break;
case DocSimpleSect::Remark:
t << "remark"; break;
case DocSimpleSect::Attention:
t << "attention"; break;
case DocSimpleSect::Important:
t << "important"; break;
case DocSimpleSect::User:
t << "par"; break;
case DocSimpleSect::Rcs:
t << "rcs"; break;
case DocSimpleSect::Unknown: break;
}
t << "\">";
}
static void endSimpleSect(TextStream &t,const DocSimpleSect &)
{
t << "</simplesect>\n";
}
static void visitCaption(XmlDocVisitor &visitor, const DocNodeList &children)
{
for (const auto &n : children)
{
std::visit(visitor,n);
}
}
static void visitPreStart(TextStream &t, const char *cmd, bool doCaption,
XmlDocVisitor &visitor, const DocNodeList &children,
const QCString &name, bool writeType, DocImage::Type type, const QCString &width,
const QCString &height, const QCString engine = QCString(), const QCString &alt = QCString(), bool inlineImage = FALSE)
{
t << "<" << cmd;
if (writeType)
{
t << " type=\"";
switch(type)
{
case DocImage::Html: t << "html"; break;
case DocImage::Latex: t << "latex"; break;
case DocImage::Rtf: t << "rtf"; break;
case DocImage::DocBook: t << "docbook"; break;
case DocImage::Xml: t << "xml"; break;
}
t << "\"";
}
if (!name.isEmpty())
{
t << " name=\"" << convertToXML(name, TRUE) << "\"";
}
if (!width.isEmpty())
{
t << " width=\"" << convertToXML(width) << "\"";
}
if (!height.isEmpty())
{
t << " height=\"" << convertToXML(height) << "\"";
}
if (!engine.isEmpty())
{
t << " engine=\"" << convertToXML(engine) << "\"";
}
if (!alt.isEmpty())
{
t << " alt=\"" << convertToXML(alt) << "\"";
}
if (inlineImage)
{
t << " inline=\"yes\"";
}
if (doCaption)
{
t << " caption=\"";
visitCaption(visitor, children);
t << "\"";
}
t << ">";
}
static void visitPostEnd(TextStream &t, const char *cmd)
{
t << "</" << cmd << ">\n";
}
XmlDocVisitor::XmlDocVisitor(TextStream &t,OutputCodeList &ci,const QCString &langExt)
: m_t(t), m_ci(ci), m_insidePre(FALSE), m_hide(FALSE),
m_langExt(langExt), m_sectionLevel(0)
{
}
//--------------------------------------
// visitor functions for leaf nodes
//--------------------------------------
void XmlDocVisitor::operator()(const DocWord &w)
{
if (m_hide) return;
filter(w.word());
}
void XmlDocVisitor::operator()(const DocLinkedWord &w)
{
if (m_hide) return;
startLink(w.ref(),w.file(),w.anchor());
filter(w.word());
endLink();
}
void XmlDocVisitor::operator()(const DocWhiteSpace &w)
{
if (m_hide) return;
if (m_insidePre)
{
m_t << w.chars();
}
else
{
m_t << " ";
}
}
void XmlDocVisitor::operator()(const DocSymbol &s)
{
if (m_hide) return;
const char *res = HtmlEntityMapper::instance().xml(s.symbol());
if (res)
{
m_t << res;
}
else
{
err("XML: non supported HTML-entity found: %s\n",HtmlEntityMapper::instance().html(s.symbol(),TRUE));
}
}
void XmlDocVisitor::operator()(const DocEmoji &s)
{
if (m_hide) return;
const char *res = EmojiEntityMapper::instance().name(s.index());
if (res)
{
QCString name=res;
name = name.mid(1,name.length()-2);
m_t << "<emoji name=\"" << name << "\" unicode=\"";
filter(EmojiEntityMapper::instance().unicode(s.index()));
m_t << "\"/>";
}
else
{
m_t << s.name();
}
}
void XmlDocVisitor::operator()(const DocURL &u)
{
if (m_hide) return;
m_t << "<ulink url=\"";
if (u.isEmail()) m_t << "mailto:";
filter(u.url());
m_t << "\">";
filter(u.url());
m_t << "</ulink>";
}
void XmlDocVisitor::operator()(const DocLineBreak &)
{
if (m_hide) return;
m_t << "<linebreak/>\n";
}
void XmlDocVisitor::operator()(const DocHorRuler &)
{
if (m_hide) return;
m_t << "<hruler/>\n";
}
void XmlDocVisitor::operator()(const DocStyleChange &s)
{
if (m_hide) return;
switch (s.style())
{
case DocStyleChange::Bold:
if (s.enable()) m_t << "<bold>"; else m_t << "</bold>";
break;
case DocStyleChange::S:
if (s.enable()) m_t << "<s>"; else m_t << "</s>";
break;
case DocStyleChange::Strike:
if (s.enable()) m_t << "<strike>"; else m_t << "</strike>";
break;
case DocStyleChange::Del:
if (s.enable()) m_t << "<del>"; else m_t << "</del>";
break;
case DocStyleChange::Underline:
if (s.enable()) m_t << "<underline>"; else m_t << "</underline>";
break;
case DocStyleChange::Ins:
if (s.enable()) m_t << "<ins>"; else m_t << "</ins>";
break;
case DocStyleChange::Italic:
if (s.enable()) m_t << "<emphasis>"; else m_t << "</emphasis>";
break;
case DocStyleChange::Kbd:
case DocStyleChange::Code:
if (s.enable()) m_t << "<computeroutput>"; else m_t << "</computeroutput>";
break;
case DocStyleChange::Subscript:
if (s.enable()) m_t << "<subscript>"; else m_t << "</subscript>";
break;
case DocStyleChange::Superscript:
if (s.enable()) m_t << "<superscript>"; else m_t << "</superscript>";
break;
case DocStyleChange::Center:
if (s.enable()) m_t << "<center>"; else m_t << "</center>";
break;
case DocStyleChange::Small:
if (s.enable()) m_t << "<small>"; else m_t << "</small>";
break;
case DocStyleChange::Cite:
if (s.enable()) m_t << "<cite>"; else m_t << "</cite>";
break;
case DocStyleChange::Preformatted:
if (s.enable())
{
m_t << "<preformatted>";
m_insidePre=TRUE;
}
else
{
m_t << "</preformatted>";
m_insidePre=FALSE;
}
break;
case DocStyleChange::Div: /* HTML only */ break;
case DocStyleChange::Span: /* HTML only */ break;
}
}
void XmlDocVisitor::operator()(const DocVerbatim &s)
{
if (m_hide) return;
QCString lang = m_langExt;
if (!s.language().isEmpty()) // explicit language setting
{
lang = s.language();
}
SrcLangExt langExt = getLanguageFromCodeLang(lang);
switch(s.type())
{
case DocVerbatim::Code:
m_t << "<programlisting";
if (!s.language().isEmpty())
m_t << " filename=\"" << lang << "\">";
else
m_t << ">";
getCodeParser(lang).parseCode(m_ci,s.context(),s.text(),langExt,
Config_getBool(STRIP_CODE_COMMENTS),
s.isExample(),s.exampleFile());
m_t << "</programlisting>";
break;
case DocVerbatim::JavaDocLiteral:
m_t << "<javadocliteral>";
filter(s.text());
m_t << "</javadocliteral>";
break;
case DocVerbatim::JavaDocCode:
m_t << "<javadoccode>";
filter(s.text());
m_t << "</javadoccode>";
break;
case DocVerbatim::Verbatim:
m_t << "<verbatim>";
filter(s.text());
m_t << "</verbatim>";
break;
case DocVerbatim::HtmlOnly:
if (s.isBlock())
{
m_t << "<htmlonly block=\"yes\">";
}
else
{
m_t << "<htmlonly>";
}
filter(s.text());
m_t << "</htmlonly>";
break;
case DocVerbatim::RtfOnly:
m_t << "<rtfonly>";
filter(s.text());
m_t << "</rtfonly>";
break;
case DocVerbatim::ManOnly:
m_t << "<manonly>";
filter(s.text());
m_t << "</manonly>";
break;
case DocVerbatim::LatexOnly:
m_t << "<latexonly>";
filter(s.text());
m_t << "</latexonly>";
break;
case DocVerbatim::DocbookOnly:
m_t << "<docbookonly>";
filter(s.text());
m_t << "</docbookonly>";
break;
case DocVerbatim::XmlOnly:
m_t << s.text();
break;
case DocVerbatim::Dot:
visitPreStart(m_t, "dot", s.hasCaption(), *this, s.children(), QCString(""), FALSE, DocImage::Html, s.width(), s.height());
filter(s.text());
visitPostEnd(m_t, "dot");
break;
case DocVerbatim::Msc:
visitPreStart(m_t, "msc", s.hasCaption(), *this, s.children(), QCString(""), FALSE, DocImage::Html, s.width(), s.height());
filter(s.text());
visitPostEnd(m_t, "msc");
break;
case DocVerbatim::PlantUML:
visitPreStart(m_t, "plantuml", s.hasCaption(), *this, s.children(), QCString(""), FALSE, DocImage::Html, s.width(), s.height(), s.engine());
filter(s.text());
visitPostEnd(m_t, "plantuml");
break;
}
}
void XmlDocVisitor::operator()(const DocAnchor &anc)
{
if (m_hide) return;
m_t << "<anchor id=\"" << anc.file() << "_1" << anc.anchor() << "\"/>";
}
void XmlDocVisitor::operator()(const DocInclude &inc)
{
if (m_hide) return;
SrcLangExt langExt = getLanguageFromFileName(inc.extension());
//printf("XMLDocVisitor: DocInclude type=%d trimleft=%d\n",inc.type(),inc.trimLeft());
switch(inc.type())
{
case DocInclude::IncWithLines:
{
m_t << "<programlisting filename=\"" << inc.file() << "\">";
FileInfo cfi( inc.file().str() );
auto fd = createFileDef( cfi.dirPath(), cfi.fileName());
getCodeParser(inc.extension()).parseCode(m_ci,inc.context(),
inc.text(),
langExt,
inc.stripCodeComments(),
inc.isExample(),
inc.exampleFile(),
fd.get(), // fileDef,
-1, // start line
-1, // end line
FALSE, // inline fragment
nullptr, // memberDef
TRUE // show line numbers
);
m_t << "</programlisting>";
}
break;
case DocInclude::Include:
m_t << "<programlisting filename=\"" << inc.file() << "\">";
getCodeParser(inc.extension()).parseCode(m_ci,inc.context(),
inc.text(),
langExt,
inc.stripCodeComments(),
inc.isExample(),
inc.exampleFile(),
nullptr, // fileDef
-1, // startLine
-1, // endLine
TRUE, // inlineFragment
nullptr, // memberDef
FALSE // show line numbers
);
m_t << "</programlisting>";
break;
case DocInclude::DontInclude:
case DocInclude::DontIncWithLines:
break;
case DocInclude::HtmlInclude:
if (inc.isBlock())
{
m_t << "<htmlonly block=\"yes\">";
}
else
{
m_t << "<htmlonly>";
}
filter(inc.text());
m_t << "</htmlonly>";
break;
case DocInclude::LatexInclude:
m_t << "<latexonly>";
filter(inc.text());
m_t << "</latexonly>";
break;
case DocInclude::RtfInclude:
m_t << "<rtfonly>";
filter(inc.text());
m_t << "</rtfonly>";
break;
case DocInclude::ManInclude:
m_t << "<manonly>";
filter(inc.text());
m_t << "</manonly>";
break;
case DocInclude::XmlInclude:
filter(inc.text());
break;
case DocInclude::DocbookInclude:
m_t << "<docbookonly>";
filter(inc.text());
m_t << "</docbookonly>";
break;
case DocInclude::VerbInclude:
m_t << "<verbatim>";
filter(inc.text());
m_t << "</verbatim>";
break;
case DocInclude::Snippet:
case DocInclude::SnippetWithLines:
m_t << "<programlisting filename=\"" << inc.file() << "\">";
CodeFragmentManager::instance().parseCodeFragment(m_ci,
inc.file(),
inc.blockId(),
inc.context(),
inc.type()==DocInclude::SnippetWithLines,
inc.trimLeft(),
inc.stripCodeComments()
);
m_t << "</programlisting>";
break;
}
}
void XmlDocVisitor::operator()(const DocIncOperator &op)
{
//printf("DocIncOperator: type=%d first=%d, last=%d text='%s'\n",
// op.type(),op.isFirst(),op.isLast(),qPrint(op.text()));
if (op.isFirst())
{
if (!m_hide)
{
m_t << "<programlisting filename=\"" << op.includeFileName() << "\">";
}
pushHidden(m_hide);
m_hide = TRUE;
}
QCString locLangExt = getFileNameExtension(op.includeFileName());
if (locLangExt.isEmpty()) locLangExt = m_langExt;
SrcLangExt langExt = getLanguageFromFileName(locLangExt);
if (op.type()!=DocIncOperator::Skip)
{
m_hide = popHidden();
if (!m_hide)
{
std::unique_ptr<FileDef> fd;
if (!op.includeFileName().isEmpty())
{
FileInfo cfi( op.includeFileName().str() );
fd = createFileDef( cfi.dirPath(), cfi.fileName() );
}
getCodeParser(locLangExt).parseCode(m_ci,op.context(),
op.text(),langExt,
op.stripCodeComments(),
op.isExample(),
op.exampleFile(),
fd.get(), // fileDef
op.line(), // startLine
-1, // endLine
FALSE, // inline fragment
nullptr, // memberDef
op.showLineNo() // show line numbers
);
}
pushHidden(m_hide);
m_hide=TRUE;
}
if (op.isLast())
{
m_hide = popHidden();
if (!m_hide) m_t << "</programlisting>";
}
else
{
if (!m_hide) m_t << "\n";
}
}
void XmlDocVisitor::operator()(const DocFormula &f)
{
if (m_hide) return;
m_t << "<formula id=\"" << f.id() << "\">";
filter(f.text());
m_t << "</formula>";
}
void XmlDocVisitor::operator()(const DocIndexEntry &ie)
{
if (m_hide) return;
m_t << "<indexentry>"
"<primaryie>";
filter(ie.entry());
m_t << "</primaryie>"
"<secondaryie></secondaryie>"
"</indexentry>";
}
void XmlDocVisitor::operator()(const DocSimpleSectSep &sep)
{
const DocSimpleSect *sect = std::get_if<DocSimpleSect>(sep.parent());
if (sect)
{
endSimpleSect(m_t,*sect);
startSimpleSect(m_t,*sect);
}
}
void XmlDocVisitor::operator()(const DocCite &cite)
{
if (m_hide) return;
if (!cite.file().isEmpty()) startLink(cite.ref(),cite.file(),cite.anchor());
filter(cite.text());
if (!cite.file().isEmpty()) endLink();
}
//--------------------------------------
// visitor functions for compound nodes
//--------------------------------------
void XmlDocVisitor::operator()(const DocAutoList &l)
{
if (m_hide) return;
if (l.isEnumList())
{
m_t << "<orderedlist>\n";
}
else
{
m_t << "<itemizedlist>\n";
}
visitChildren(l);
if (l.isEnumList())
{
m_t << "</orderedlist>\n";
}
else
{
m_t << "</itemizedlist>\n";
}
}
void XmlDocVisitor::operator()(const DocAutoListItem &li)
{
if (m_hide) return;
switch (li.itemNumber())
{
case DocAutoList::Unchecked: // unchecked
m_t << "<listitem override=\"unchecked\">";
break;
case DocAutoList::Checked_x: // checked with x
case DocAutoList::Checked_X: // checked with X
m_t << "<listitem override=\"checked\">";
break;
default:
m_t << "<listitem>";
break;
}
visitChildren(li);
m_t << "</listitem>";
}
void XmlDocVisitor::operator()(const DocPara &p)
{
if (m_hide) return;
m_t << "<para>";
visitChildren(p);
m_t << "</para>\n";
}
void XmlDocVisitor::operator()(const DocRoot &r)
{
visitChildren(r);
}
void XmlDocVisitor::operator()(const DocSimpleSect &s)
{
if (m_hide) return;
startSimpleSect(m_t,s);
if (s.title())
{
std::visit(*this,*s.title());
}
visitChildren(s);
endSimpleSect(m_t,s);
}
void XmlDocVisitor::operator()(const DocTitle &t)
{
if (m_hide) return;
m_t << "<title>";
visitChildren(t);
m_t << "</title>";
}
void XmlDocVisitor::operator()(const DocSimpleList &l)
{
if (m_hide) return;
m_t << "<itemizedlist>\n";
visitChildren(l);
m_t << "</itemizedlist>\n";
}
void XmlDocVisitor::operator()(const DocSimpleListItem &li)
{
if (m_hide) return;
m_t << "<listitem>";
if (li.paragraph())
{
std::visit(*this,*li.paragraph());
}
m_t << "</listitem>\n";
}
void XmlDocVisitor::operator()(const DocSection &s)
{
if (m_hide) return;
int orgSectionLevel = m_sectionLevel;
QCString sectId = s.file();
if (!s.anchor().isEmpty()) sectId += "_1"+s.anchor();
while (m_sectionLevel+1<s.level()) // fix missing intermediate levels
{
m_sectionLevel++;
m_t << "<sect" << m_sectionLevel << " id=\"" << sectId << "_1s" << m_sectionLevel << "\">";
}
m_sectionLevel++;
m_t << "<sect" << s.level() << " id=\"" << sectId << "\">\n";
if (s.title())
{
std::visit(*this,*s.title());
}
visitChildren(s);
m_t << "</sect" << s.level() << ">";
m_sectionLevel--;
while (orgSectionLevel<m_sectionLevel) // fix missing intermediate levels
{
m_t << "</sect" << m_sectionLevel << ">";
m_sectionLevel--;
}
m_t << "\n";
}
void XmlDocVisitor::operator()(const DocHtmlList &s)
{
if (m_hide) return;
if (s.type()==DocHtmlList::Ordered)
{
m_t << "<orderedlist";
for (const auto &opt : s.attribs())
{
m_t << " " << opt.name << "=\"" << opt.value << "\"";
}
m_t << ">\n";
}
else
{
m_t << "<itemizedlist>\n";
}
visitChildren(s);
if (s.type()==DocHtmlList::Ordered)
{
m_t << "</orderedlist>\n";
}
else
{
m_t << "</itemizedlist>\n";
}
}
void XmlDocVisitor::operator()(const DocHtmlListItem &l)
{
if (m_hide) return;
m_t << "<listitem";
for (const auto &opt : l.attribs())
{
if (opt.name=="value")
{
m_t << " " << opt.name << "=\"" << opt.value << "\"";
}
}
m_t << ">\n";
visitChildren(l);
m_t << "</listitem>\n";
}
void XmlDocVisitor::operator()(const DocHtmlDescList &dl)
{
if (m_hide) return;
m_t << "<variablelist>\n";
visitChildren(dl);
m_t << "</variablelist>\n";
}
void XmlDocVisitor::operator()(const DocHtmlDescTitle &dt)
{
if (m_hide) return;
m_t << "<varlistentry><term>";
visitChildren(dt);
m_t << "</term></varlistentry>\n";
}
void XmlDocVisitor::operator()(const DocHtmlDescData &dd)
{
if (m_hide) return;
m_t << "<listitem>";
visitChildren(dd);
m_t << "</listitem>\n";
}
void XmlDocVisitor::operator()(const DocHtmlTable &t)
{
if (m_hide) return;
m_t << "<table rows=\"" << t.numRows()
<< "\" cols=\"" << t.numColumns() << "\"" ;
for (const auto &opt : t.attribs())
{
if (opt.name=="width")
{
m_t << " " << opt.name << "=\"" << opt.value << "\"";
}
}
m_t << ">";
if (t.caption())
{
std::visit(*this,*t.caption());
}
visitChildren(t);
m_t << "</table>\n";
}
void XmlDocVisitor::operator()(const DocHtmlRow &r)
{
if (m_hide) return;
m_t << "<row>\n";
visitChildren(r);
m_t << "</row>\n";
}
void XmlDocVisitor::operator()(const DocHtmlCell &c)
{
if (m_hide) return;
if (c.isHeading()) m_t << "<entry thead=\"yes\""; else m_t << "<entry thead=\"no\"";
for (const auto &opt : c.attribs())
{
if (opt.name=="colspan" || opt.name=="rowspan")
{
m_t << " " << opt.name << "=\"" << opt.value.toInt() << "\"";
}
else if (opt.name=="align" &&
(opt.value=="right" || opt.value=="left" || opt.value=="center"))
{
m_t << " align=\"" << opt.value << "\"";
}
else if (opt.name=="valign" &&
(opt.value == "bottom" || opt.value == "top" || opt.value == "middle"))
{
m_t << " valign=\"" << opt.value << "\"";
}
else if (opt.name=="width")
{
m_t << " width=\"" << opt.value << "\"";
}
else if (opt.name=="class") // handle markdown generated attributes
{
if (opt.value.startsWith("markdownTable")) // handle markdown generated attributes
{
if (opt.value.endsWith("Right"))
{
m_t << " align='right'";
}
else if (opt.value.endsWith("Left"))
{
m_t << " align='left'";
}
else if (opt.value.endsWith("Center"))
{
m_t << " align='center'";
}
// skip 'markdownTable*' value ending with "None"
}
else if (!opt.value.isEmpty())
{
m_t << " class=\"" << convertToXML(opt.value) << "\"";
}
}
}
m_t << ">";
visitChildren(c);
m_t << "</entry>";
}
void XmlDocVisitor::operator()(const DocHtmlCaption &c)
{
if (m_hide) return;
m_t << "<caption";
if (!c.file().isEmpty())
{
m_t << " id=\"" << stripPath(c.file()) << "_1" << c.anchor() << "\"";
}
m_t << ">";
visitChildren(c);
m_t << "</caption>\n";
}
void XmlDocVisitor::operator()(const DocInternal &i)
{
if (m_hide) return;
m_t << "<internal>";
visitChildren(i);
m_t << "</internal>\n";
}
void XmlDocVisitor::operator()(const DocHRef &href)
{
if (m_hide) return;
m_t << "<ulink url=\"" << convertToXML(href.url(), TRUE) << "\">";
visitChildren(href);
m_t << "</ulink>";
}
void XmlDocVisitor::operator()(const DocHtmlSummary &s)
{
if (m_hide) return;
m_t << "<summary>";
visitChildren(s);
m_t << "</summary>";
}
void XmlDocVisitor::operator()(const DocHtmlDetails &d)
{
if (m_hide) return;
m_t << "<details>";
auto summary = d.summary();
if (summary)
{
std::visit(*this,*summary);
}
visitChildren(d);
m_t << "</details>";
}
void XmlDocVisitor::operator()(const DocHtmlHeader &header)
{
if (m_hide) return;
m_t << "<heading level=\"" << header.level() << "\">";
visitChildren(header);
m_t << "</heading>\n";
}
void XmlDocVisitor::operator()(const DocImage &img)
{
if (m_hide) return;
QCString url = img.url();
QCString baseName;
if (url.isEmpty())
{
baseName = img.relPath()+img.name();
}
else
{
baseName = correctURL(url,img.relPath());
}
HtmlAttribList attribs = img.attribs();
auto it = std::find_if(attribs.begin(),attribs.end(),
[](const auto &att) { return att.name=="alt"; });
QCString altValue = it!=attribs.end() ? it->value : "";
visitPreStart(m_t, "image", FALSE, *this, img.children(), baseName, TRUE,
img.type(), img.width(), img.height(), QCString(),
altValue, img.isInlineImage());
// copy the image to the output dir
FileDef *fd = nullptr;
bool ambig;
if (url.isEmpty() && (fd=findFileDef(Doxygen::imageNameLinkedMap,img.name(),ambig)))
{
copyFile(fd->absFilePath(),Config_getString(XML_OUTPUT)+"/"+baseName);
}
visitChildren(img);
visitPostEnd(m_t, "image");
}
void XmlDocVisitor::operator()(const DocDotFile &df)
{
if (m_hide) return;
copyFile(df.file(),Config_getString(XML_OUTPUT)+"/"+stripPath(df.file()));
visitPreStart(m_t, "dotfile", FALSE, *this, df.children(), stripPath(df.file()), FALSE, DocImage::Html, df.width(), df.height());
visitChildren(df);
visitPostEnd(m_t, "dotfile");
}
void XmlDocVisitor::operator()(const DocMscFile &df)
{
if (m_hide) return;
copyFile(df.file(),Config_getString(XML_OUTPUT)+"/"+stripPath(df.file()));
visitPreStart(m_t, "mscfile", FALSE, *this, df.children(), stripPath(df.file()), FALSE, DocImage::Html, df.width(), df.height());
visitChildren(df);
visitPostEnd(m_t, "mscfile");
}
void XmlDocVisitor::operator()(const DocDiaFile &df)
{
if (m_hide) return;
copyFile(df.file(),Config_getString(XML_OUTPUT)+"/"+stripPath(df.file()));
visitPreStart(m_t, "diafile", FALSE, *this, df.children(), stripPath(df.file()), FALSE, DocImage::Html, df.width(), df.height());
visitChildren(df);
visitPostEnd(m_t, "diafile");
}
void XmlDocVisitor::operator()(const DocPlantUmlFile &df)
{
if (m_hide) return;
copyFile(df.file(),Config_getString(XML_OUTPUT)+"/"+stripPath(df.file()));
visitPreStart(m_t, "plantumlfile", FALSE, *this, df.children(), stripPath(df.file()), FALSE, DocImage::Html, df.width(), df.height());
visitChildren(df);
visitPostEnd(m_t, "plantumlfile");
}
void XmlDocVisitor::operator()(const DocLink &lnk)
{
if (m_hide) return;
startLink(lnk.ref(),lnk.file(),lnk.anchor());
visitChildren(lnk);
endLink();
}
void XmlDocVisitor::operator()(const DocRef &ref)
{
if (m_hide) return;
if (!ref.file().isEmpty())
{
startLink(ref.ref(),ref.file(),ref.isSubPage() ? QCString() : ref.anchor());
}
if (!ref.hasLinkText()) filter(ref.targetTitle());
visitChildren(ref);
if (!ref.file().isEmpty()) endLink();
}
void XmlDocVisitor::operator()(const DocSecRefItem &ref)
{
if (m_hide) return;
m_t << "<tocitem id=\"" << ref.file();
if (!ref.anchor().isEmpty()) m_t << "_1" << ref.anchor();
m_t << "\"";
m_t << ">";
visitChildren(ref);
m_t << "</tocitem>\n";
}
void XmlDocVisitor::operator()(const DocSecRefList &l)
{
if (m_hide) return;
m_t << "<toclist>\n";
visitChildren(l);
m_t << "</toclist>\n";
}
void XmlDocVisitor::operator()(const DocParamSect &s)
{
if (m_hide) return;
m_t << "<parameterlist kind=\"";
switch(s.type())
{
case DocParamSect::Param:
m_t << "param"; break;
case DocParamSect::RetVal:
m_t << "retval"; break;
case DocParamSect::Exception:
m_t << "exception"; break;
case DocParamSect::TemplateParam:
m_t << "templateparam"; break;
default:
ASSERT(0);
}
m_t << "\">";
visitChildren(s);
m_t << "</parameterlist>\n";
}
void XmlDocVisitor::operator()(const DocSeparator &)
{
m_t << "</parametertype>\n";
m_t << "<parametertype>";
}
void XmlDocVisitor::operator()(const DocParamList &pl)
{
if (m_hide) return;
m_t << "<parameteritem>\n";
m_t << "<parameternamelist>\n";
for (const auto ¶m : pl.parameters())
{
if (!pl.paramTypes().empty())
{
m_t << "<parametertype>";
for (const auto &type : pl.paramTypes())
{
std::visit(*this,type);
}
m_t << "</parametertype>\n";
}
m_t << "<parametername";
if (pl.direction()!=DocParamSect::Unspecified)
{
m_t << " direction=\"";
if (pl.direction()==DocParamSect::In)
{
m_t << "in";
}
else if (pl.direction()==DocParamSect::Out)
{
m_t << "out";
}
else if (pl.direction()==DocParamSect::InOut)
{
m_t << "inout";
}
m_t << "\"";
}
m_t << ">";
std::visit(*this,param);
m_t << "</parametername>\n";
}
m_t << "</parameternamelist>\n";
m_t << "<parameterdescription>\n";
for (const auto &par : pl.paragraphs())
{
std::visit(*this,par);
}
m_t << "</parameterdescription>\n";
m_t << "</parameteritem>\n";
}
void XmlDocVisitor::operator()(const DocXRefItem &x)
{
if (m_hide) return;
if (x.title().isEmpty()) return;
m_t << "<xrefsect id=\"";
m_t << x.file() << "_1" << x.anchor();
m_t << "\">";
m_t << "<xreftitle>";
filter(x.title());
m_t << "</xreftitle>";
m_t << "<xrefdescription>";
visitChildren(x);
if (x.title().isEmpty()) return;
m_t << "</xrefdescription>";
m_t << "</xrefsect>";
}
void XmlDocVisitor::operator()(const DocInternalRef &ref)
{
if (m_hide) return;
startLink(QCString(),ref.file(),ref.anchor());
visitChildren(ref);
endLink();
m_t << " ";
}
void XmlDocVisitor::operator()(const DocText &t)
{
visitChildren(t);
}
void XmlDocVisitor::operator()(const DocHtmlBlockQuote &q)
{
if (m_hide) return;
m_t << "<blockquote>";
visitChildren(q);
m_t << "</blockquote>";
}
void XmlDocVisitor::operator()(const DocVhdlFlow &)
{
}
void XmlDocVisitor::operator()(const DocParBlock &pb)
{
if (m_hide) return;
m_t << "<parblock>";
visitChildren(pb);
m_t << "</parblock>";
}
void XmlDocVisitor::filter(const QCString &str)
{
m_t << convertToXML(str);
}
void XmlDocVisitor::startLink(const QCString &ref,const QCString &file,const QCString &anchor)
{
//printf("XmlDocVisitor: file=%s anchor=%s\n",qPrint(file),qPrint(anchor));
m_t << "<ref refid=\"" << file;
if (!anchor.isEmpty()) m_t << "_1" << anchor;
m_t << "\" kindref=\"";
if (!anchor.isEmpty()) m_t << "member"; else m_t << "compound";
m_t << "\"";
if (!ref.isEmpty()) m_t << " external=\"" << ref << "\"";
m_t << ">";
}
void XmlDocVisitor::endLink()
{
m_t << "</ref>";
}
| 30,941
|
C++
|
.cpp
| 1,111
| 22.319532
| 147
| 0.552714
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,435
|
vhdljjparser.cpp
|
doxygen_doxygen/src/vhdljjparser.cpp
|
/******************************************************************************
*
* Copyright (C) 2014 by M. Kreis
*
* 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.
*
*/
#include <string>
#include "qcstring.h"
#include "containers.h"
#include "vhdljjparser.h"
#include "vhdldocgen.h"
#include "message.h"
#include "config.h"
#include "doxygen.h"
#include "util.h"
#include "language.h"
#include "commentscan.h"
#include "definition.h"
#include "searchindex.h"
#include "outputlist.h"
#include "arguments.h"
#include "types.h"
#include "growbuf.h"
#include "markdown.h"
#include "VhdlParserTokenManager.h"
#include "VhdlParserErrorHandler.hpp"
#include "regex.h"
using namespace vhdl::parser;
struct VHDLDocInfo
{
QCString doc;
bool brief;
bool pending = false;
int iDocLine = 1;
};
static bool isConstraintFile(const QCString &fileName,const QCString &ext)
{
return fileName.right(ext.length())==ext;
}
//-------------------------------------
static EntryList g_instFiles;
struct VHDLOutlineParser::Private
{
void parseVhdlfile(const QCString &fileName,const QCString &inputBuffer,bool inLine);
VHDLOutlineParser *thisParser = nullptr;
VhdlParser *vhdlParser = nullptr;
CommentScanner commentScanner;
QCString yyFileName;
int yyLineNr = 1;
IntVector lineParse;
int iDocLine = -1;
QCString inputString;
Entry* gBlock = nullptr;
Entry* previous = nullptr;
//-------------------------------------------------------
Entry* oldEntry = nullptr;
bool varr = FALSE;
QCString varName;
EntryList libUse;
EntryList lineEntry;
QCString strComment;
int iCodeLen;
VHDLDocInfo str_doc;
VhdlParser::SharedState shared;
QCString forL;
int code = 0;
};
void VHDLOutlineParser::Private::parseVhdlfile(const QCString &fileName,
const QCString &inputBuffer,bool inLine)
{
QCString s =inputBuffer;
CharStream *stream = new CharStream(reinterpret_cast<const JJChar*>(s.data()), (int)s.size(), 1, 1);
VhdlParserTokenManager *tokenManager = new VhdlParserTokenManager(stream);
VhdlTokenManagerErrorHandler *tokErrHandler=new VhdlTokenManagerErrorHandler(fileName.data());
vhdlParser=new VhdlParser(tokenManager);
vhdlParser->setOutlineParser(thisParser);
vhdlParser->setSharedState(&shared);
tokenManager->setLexParser(vhdlParser);
tokenManager->ReInit(stream,0);
tokenManager->setErrorHandler(tokErrHandler);
VhdlErrorHandler *parserErrHandler=new VhdlErrorHandler(fileName.data());
vhdlParser->setErrorHandler(parserErrHandler);
try
{
if(inLine)
{
vhdlParser->parseInline();
}
else
{
// vhdlParser->interface_variable_declaration(); //interface_declaration() ;
vhdlParser->design_file();
}
}
catch( std::exception &){ /* fprintf(stderr,"\n[%s]",e.what()); */ }
// fprintf(stderr,"\n\nparsed lines: %d\n",yyLineNr);
// fprintf(stderr,"\n\nerrors : %d\n\n",myErr->getErrorCount());
//
delete vhdlParser;
delete tokenManager;
delete stream;
}
VHDLOutlineParser::VHDLOutlineParser() : p(std::make_unique<Private>())
{
}
VHDLOutlineParser::~VHDLOutlineParser()
{
}
void VHDLOutlineParser::parseInput(const QCString &fileName,const char *fileBuf,
const std::shared_ptr<Entry> &root, ClangTUParser *)
{
VhdlParser::SharedState *s = &p->shared;
p->thisParser=this;
p->inputString=fileBuf;
// fprintf(stderr,"\n ============= %s\n ==========\n",fileBuf);
bool inLine = fileName.isEmpty();
if (!inLine) msg("Parsing file %s...\n",qPrint(fileName));
p->yyFileName=fileName;
bool xilinx_ucf=isConstraintFile(p->yyFileName,".ucf");
bool altera_qsf=isConstraintFile(p->yyFileName,".qsf");
// support XILINX(ucf) and ALTERA (qsf) file
if (xilinx_ucf)
{
VhdlDocGen::parseUCF(fileBuf,root.get(),p->yyFileName,FALSE);
return;
}
if (altera_qsf)
{
VhdlDocGen::parseUCF(fileBuf,root.get(),p->yyFileName,TRUE);
return;
}
p->yyLineNr=1;
s->current_root=root;
s->lastCompound=nullptr;
s->lastEntity=nullptr;
p->oldEntry = nullptr;
s->current=std::make_shared<Entry>();
initEntry(s->current.get());
p->commentScanner.enterFile(fileName,p->yyLineNr);
p->lineParse.reserve(200);
p->parseVhdlfile(fileName,fileBuf,inLine);
p->commentScanner.leaveFile(fileName,p->yyLineNr);
s->current.reset();
if (!inLine)
mapLibPackage(root.get());
p->yyFileName.clear();
p->libUse.clear();
}
void VHDLOutlineParser::lineCount()
{
p->yyLineNr++;
}
void VHDLOutlineParser::lineCount(const QCString &text)
{
if (!text.isEmpty())
{
for (const char* c=text.data() ; *c ; ++c )
{
if (*c == '\n') p->yyLineNr++;
}
}
}
void VHDLOutlineParser::initEntry(Entry *e)
{
e->fileName = p->yyFileName;
e->lang = SrcLangExt::VHDL;
if (p->str_doc.pending)
{
p->str_doc.pending=FALSE;
p->oldEntry=nullptr; // prevents endless recursion
p->iDocLine=p->str_doc.iDocLine;
handleCommentBlock(p->str_doc.doc,p->str_doc.brief);
p->iDocLine=-1;
}
p->commentScanner.initGroupInfo(e);
}
void VHDLOutlineParser::newEntry()
{
VhdlParser::SharedState *s = &p->shared;
p->previous = s->current.get();
if (s->current->vhdlSpec==VhdlSpecifier::ENTITY ||
s->current->vhdlSpec==VhdlSpecifier::PACKAGE ||
s->current->vhdlSpec==VhdlSpecifier::ARCHITECTURE ||
s->current->vhdlSpec==VhdlSpecifier::PACKAGE_BODY)
{
s->current_root->moveToSubEntryAndRefresh(s->current);
}
else
{
if (s->lastCompound)
{
s->lastCompound->moveToSubEntryAndRefresh(s->current);
}
else
{
if (s->lastEntity)
{
s->lastEntity->moveToSubEntryAndRefresh(s->current);
}
else
{
s->current_root->moveToSubEntryAndRefresh(s->current);
}
}
}
initEntry(s->current.get());
}
static int idCounter;
/** returns a unique id for each record member.
*
* type first_rec is record
* RE: data_type;
* end;
*
* type second_rec is record
* RE: data_type;
* end;
*/
QCString VHDLOutlineParser::getNameID()
{
return QCString().setNum(idCounter++);
}
void VHDLOutlineParser::handleFlowComment(const QCString &doc)
{
lineCount(doc);
if (VhdlDocGen::getFlowMember())
{
QCString qcs(doc);
qcs=qcs.stripWhiteSpace();
qcs.stripPrefix("--#");
FlowChart::addFlowChart(FlowChart::COMMENT_NO,QCString(),QCString(),qcs);
}
}
int VHDLOutlineParser::checkInlineCode(QCString &doc)
{
static const reg::Ex csRe(R"([\\@]code)");
static const reg::Ex cendRe(R"(\s*[\\@]endcode)");
static const reg::Ex cbriefRe(R"([\\@]brief)");
// helper to simulate behavior of QString.find(const QRegExp &re,int pos)
auto findRe = [](const QCString &str,const reg::Ex &re,int pos=0) -> int
{
if ((int)str.length()<pos) return -1;
reg::Match match;
const std::string s = str.str();
if (reg::search(s,match,re,pos)) // match found
{
return (int)match.position();
}
else // not found
{
return -1;
}
};
auto replaceRe = [](const QCString &str,const reg::Ex &re,const QCString &replacement) -> QCString
{
return reg::replace(str.str(), re, replacement.str());
};
int index = findRe(doc,csRe);
if (findRe(doc,cendRe)!=-1)
return 1;
if (index < 0)
return index;
VhdlParser::SharedState *s = &p->shared;
p->strComment += doc;
p->code = findRe(p->inputString,csRe, p->code + 1);
int com = p->inputString.find(p->strComment.data());
int ref = findRe(p->inputString,cendRe, p->code + 1);
int len = static_cast<int>(p->strComment.size());
int ll = com + len;
int diff = ref - ll - 3;
QCString code = p->inputString.mid(ll, diff);
int iLine = 0;
code = stripLeadingAndTrailingEmptyLines(code, iLine);
int val = code.contains('\n');
VhdlDocGen::prepareComment(p->strComment);
StringVector ql = split(p->strComment.str(),"\n");
QCString co;
QCString na;
for (const auto &qcs_ : ql)
{
QCString qcs(qcs_);
qcs = qcs.simplifyWhiteSpace();
if (findRe(qcs,csRe)!=-1)
{
int i = qcs.find('{');
int j = qcs.find('}');
if (i > 0 && j > 0 && j > i)
{
na = qcs.mid(i + 1, (j - i - 1));
}
continue;
}
qcs = replaceRe(qcs,cbriefRe, "");
co += qcs;
co += '\n';
}
VhdlDocGen::prepareComment(co);
Entry gBlock;
if (!na.isEmpty())
gBlock.name = na;
else
gBlock.name = "misc" + VhdlDocGen::getRecordNumber();
gBlock.startLine = p->yyLineNr+iLine-1;
gBlock.bodyLine = p->yyLineNr+iLine-1 ;
gBlock.doc = code;
gBlock.inbodyDocs = code;
gBlock.brief = co;
gBlock.section = EntryType::makeVariable();
gBlock.vhdlSpec = VhdlSpecifier::MISCELLANEOUS;
gBlock.fileName = p->yyFileName;
gBlock.endBodyLine = p->yyLineNr + val +iLine;
gBlock.lang = SrcLangExt::VHDL;
std::shared_ptr<Entry> compound;
if (s->lastEntity)
compound = s->lastEntity;
else if (s->lastCompound)
compound = s->lastCompound;
else
compound = nullptr;
if (compound)
{
compound->copyToSubEntry(&gBlock);
}
else
{
gBlock.type = "misc"; // global code like library ieee...
s->current_root->copyToSubEntry(&gBlock);
}
p->strComment.clear();
return 1;
}
void VHDLOutlineParser::handleCommentBlock(const QCString &doc1, bool brief)
{
int position = 0;
bool needsEntry = FALSE;
VhdlParser::SharedState *s = &p->shared;
QCString doc = doc1;
if (doc.isEmpty())
return;
if (checkMultiComment(doc, p->yyLineNr))
{
p->strComment.clear();
return;
}
if (checkInlineCode(doc) > 0)
{
return;
}
Protection protection = Protection::Public;
VhdlDocGen::prepareComment(doc);
if (doc.isEmpty()) return;
if (p->oldEntry == s->current.get())
{
p->str_doc.doc = doc;
p->str_doc.iDocLine = p->iDocLine;
p->str_doc.brief = brief;
p->str_doc.pending = TRUE;
return;
}
p->oldEntry = s->current.get();
if (brief)
{
s->current->briefLine = p->yyLineNr;
}
else
{
s->current->docLine = p->yyLineNr;
}
Markdown markdown(p->yyFileName,p->iDocLine);
int lineNr = p->iDocLine;
GuardedSectionStack guards;
QCString processedDoc = Config_getBool(MARKDOWN_SUPPORT) ? markdown.process(doc,lineNr) : doc;
while (p->commentScanner.parseCommentBlock(
p->thisParser,
s->current.get(),
processedDoc, // text
p->yyFileName, // file
lineNr, // line of block start
brief,
0,
FALSE,
protection,
position,
needsEntry,
Config_getBool(MARKDOWN_SUPPORT),
&guards
))
{
if (needsEntry)
newEntry();
}
if (needsEntry)
{
if (p->varr)
{
p->varr = FALSE;
s->current->name = p->varName;
s->current->section = EntryType::makeVariableDoc();
p->varName = "";
}
newEntry();
}
p->iDocLine = -1;
p->strComment.clear();
}
void VHDLOutlineParser::parsePrototype(const QCString &text)
{
p->varName=text;
p->varr=TRUE;
}
void VHDLOutlineParser::addCompInst(const QCString &n, const QCString &instName, const QCString &comp,int iLine)
{
VhdlParser::SharedState *s = &p->shared;
s->current->vhdlSpec=VhdlSpecifier::INSTANTIATION;
s->current->section=EntryType::makeVariable();
s->current->startLine=iLine;
s->current->bodyLine=iLine;
s->current->type=instName; // foo:instname e.g proto or work. proto(ttt)
s->current->exception=s->genLabels.lower(); // |arch|label1:label2...
s->current->name=n; // foo
if (s->lastCompound)
{
s->current->args=s->lastCompound->name; // architecture name
}
s->current->includeName=comp; // component/entity/configuration
int u=s->genLabels.find("|",1);
if (u>0)
{
s->current->write=s->genLabels.right(s->genLabels.length()-u);
s->current->read=s->genLabels.left(u);
}
//printf (" \n genlabel: [%s] inst: [%s] name: [%s] %d\n",n,instName,comp,iLine);
if (s->lastCompound)
{
s->current->args=s->lastCompound->name;
if (true) // !findInstant(current->type))
{
initEntry(s->current.get());
// TODO: protect with mutex
g_instFiles.emplace_back(std::make_shared<Entry>(*s->current));
// TODO: end protect with mutex
}
s->current=std::make_shared<Entry>();
}
else
{
newEntry();
}
}
void VHDLOutlineParser::addVhdlType(const QCString &n,int startLine,EntryType section,
VhdlSpecifier spec,const QCString &args,const QCString &type,Protection prot)
{
VhdlParser::SharedState *s = &p->shared;
QCString name(n);
if (isFuncProcProced() || VhdlDocGen::getFlowMember()) return;
if (s->parse_sec==VhdlSection::GEN_SEC)
{
spec=VhdlSpecifier::GENERIC;
}
StringVector ql=split(name.str(),",");
for (size_t u=0;u<ql.size();u++)
{
s->current->name=ql[u];
s->current->startLine=startLine;
s->current->bodyLine=startLine;
s->current->section=section;
s->current->vhdlSpec=spec;
s->current->fileName=p->yyFileName;
if (s->current->args.isEmpty())
{
s->current->args=args;
}
s->current->type=type;
s->current->protection=prot;
if (!s->lastCompound && section.isVariable() && (spec == VhdlSpecifier::USE || spec == VhdlSpecifier::LIBRARY) )
{
p->libUse.emplace_back(std::make_shared<Entry>(*s->current));
s->current->reset();
}
newEntry();
}
}
void VHDLOutlineParser::createFunction(const QCString &impure,VhdlSpecifier spec,const QCString &fname)
{
VhdlParser::SharedState *s = &p->shared;
s->current->vhdlSpec=spec;
s->current->section=EntryType::makeFunction();
if (impure=="impure" || impure=="pure")
{
s->current->exception=impure;
}
if (s->parse_sec==VhdlSection::GEN_SEC)
{
s->current->vhdlSpec=VhdlSpecifier::GENERIC;
s->current->section=EntryType::makeFunction();
}
if (s->currP==VhdlSpecifier::PROCEDURE)
{
s->current->name=impure;
s->current->exception="";
}
else
{
s->current->name=fname;
}
if (spec==VhdlSpecifier::PROCESS)
{
s->current->args=fname;
s->current->name=impure;
VhdlDocGen::deleteAllChars(s->current->args,' ');
if (!fname.isEmpty())
{
StringVector q1=split(fname.str(),",");
for (const auto &name : q1)
{
Argument arg;
arg.name=name;
s->current->argList.push_back(arg);
}
}
}
}
bool VHDLOutlineParser::isFuncProcProced()
{
VhdlParser::SharedState *s = &p->shared;
if (s->currP==VhdlSpecifier::FUNCTION ||
s->currP==VhdlSpecifier::PROCEDURE ||
s->currP==VhdlSpecifier::PROCESS
)
{
return TRUE;
}
return FALSE;
}
void VHDLOutlineParser::pushLabel( QCString &label,QCString & val)
{
label+="|";
label+=val;
}
QCString VHDLOutlineParser::popLabel(QCString & q)
{
int i=q.findRev("|");
if (i<0) return QCString();
q = q.left(i);
return q;
}
void VHDLOutlineParser::addProto(const QCString &s1,const QCString &s2,const QCString &s3,
const QCString &s4,const QCString &s5,const QCString &s6)
{
VhdlParser::SharedState *s = &p->shared;
(void)s5; // avoid unused warning
QCString name=s2;
StringVector ql=split(name.str(),",");
for (const auto &n : ql)
{
Argument arg;
arg.name=n;
if (!s3.isEmpty())
{
arg.type=s3;
}
arg.type+=" ";
arg.type+=s4;
if (!s6.isEmpty())
{
arg.type+=s6;
}
if (s->parse_sec==VhdlSection::GEN_SEC && s->param_sec==VhdlSection::UNKNOWN)
{
arg.defval="generic";
}
if (s->parse_sec==VhdlSection::PARAM_SEC)
{
// assert(false);
}
arg.defval+=s1;
arg.attrib="";//s6;
s->current->argList.push_back(arg);
s->current->args+=s2;
s->current->args+=",";
}
}
/*
* adds the library|use statements to the next class (entity|package|architecture|package body
* library ieee
* entity xxx
* .....
* library
* package
* entity zzz
* .....
* and so on..
*/
void VHDLOutlineParser::mapLibPackage( Entry* root)
{
for (const auto &rt : p->libUse)
{
if (addLibUseClause(rt->name))
{
bool bFound=FALSE;
for (const auto ¤t : root->children())
{
if (VhdlDocGen::isVhdlClass(current.get()))
{
if (current->startLine > rt->startLine)
{
bFound=TRUE;
current->copyToSubEntry(rt);
break;
}
}
}//for
if (!bFound)
{
root->copyToSubEntry(rt);
}
} //if
}// for
}//MapLib
bool VHDLOutlineParser::addLibUseClause(const QCString &type)
{
bool showIEEESTD=Config_getBool(FORCE_LOCAL_INCLUDES);
if (showIEEESTD) // all standard packages and libraries will not be shown
{
if (type.lower().stripPrefix("ieee")) return FALSE;
if (type.lower().stripPrefix("std")) return FALSE;
}
return TRUE;
}
int VHDLOutlineParser::getLine()
{
return p->yyLineNr;
}
void VHDLOutlineParser::setLineParsed(int tok)
{
if ((int)p->lineParse.size()<=tok) p->lineParse.resize(tok+1);
p->lineParse[tok]=p->yyLineNr;
}
int VHDLOutlineParser::getLine(int tok)
{
int val=p->lineParse[tok];
if (val<0) val=0;
//assert(val>=0 && val<=yyLineNr);
return val;
}
void VHDLOutlineParser::createFlow()
{
VhdlParser::SharedState *s = &p->shared;
if (!VhdlDocGen::getFlowMember())
{
return;
}
QCString q,ret;
if (s->currP==VhdlSpecifier::FUNCTION)
{
q=":function( ";
FlowChart::alignFuncProc(q,s->tempEntry->argList,true);
q+=")";
}
else if (s->currP==VhdlSpecifier::PROCEDURE)
{
q=":procedure (";
FlowChart::alignFuncProc(q,s->tempEntry->argList,false);
q+=")";
}
else
{
q=":process( "+s->tempEntry->args;
q+=")";
}
q.prepend(VhdlDocGen::getFlowMember()->name());
FlowChart::addFlowChart(FlowChart::START_NO,q,QCString());
if (s->currP==VhdlSpecifier::FUNCTION)
{
ret="end function ";
}
else if (s->currP==VhdlSpecifier::PROCEDURE)
{
ret="end procedure";
}
else
{
ret="end process ";
}
FlowChart::addFlowChart(FlowChart::END_NO,ret,QCString());
// FlowChart::printFlowList();
FlowChart::writeFlowChart();
s->currP=VhdlSpecifier::UNKNOWN;
}
void VHDLOutlineParser::setMultCommentLine()
{
p->iDocLine=p->yyLineNr;
}
void VHDLOutlineParser::oneLineComment(QCString qcs)
{
int j=qcs.find("--!");
qcs=qcs.right(qcs.length()-3-j);
if (!checkMultiComment(qcs,p->iDocLine))
{
handleCommentBlock(qcs,TRUE);
}
}
bool VHDLOutlineParser::checkMultiComment(QCString& qcs,int line)
{
VhdlParser::SharedState *s = &p->shared;
insertEntryAtLine(s->current_root,line);
if (p->lineEntry.empty()) return false;
VhdlDocGen::prepareComment(qcs);
while (!p->lineEntry.empty())
{
std::shared_ptr<Entry> e=p->lineEntry.back();
e->briefLine=line;
e->brief+=qcs;
p->lineEntry.pop_back();
}
return true;
}
// returns the vhdl parsed types at line xxx
void VHDLOutlineParser::insertEntryAtLine(std::shared_ptr<Entry> ce,int line)
{
for (const auto &rt : ce->children())
{
if (rt->bodyLine==line)
{
p->lineEntry.push_back(rt);
}
insertEntryAtLine(rt,line);
}
}
const EntryList &getVhdlInstList()
{
return g_instFiles;
}
void VHDLOutlineParser::error_skipto(int kind)
{
Token *op;
do
{
p->vhdlParser->getNextToken(); // step to next token
op=p->vhdlParser->getToken(1); // get first token
if (op==nullptr) break;
//fprintf(stderr,"\n %s",qPrint(t->image));
} while (op->kind != kind);
p->vhdlParser->clearError();
// The above loop consumes tokens all the way up to a token of
// "kind". We use a do-while loop rather than a while because the
// current token is the one immediately before the erroneous token
// (in our case the token immediately before what should have been
// "if"/"while".
}
QCString filter2008VhdlComment(const QCString &s)
{
if (s.length()<4) return s;
GrowBuf growBuf;
const char *p=s.data()+3; // skip /*!
char c='\0';
while (*p == ' ' || *p == '\t') p++;
while ((c=*p++))
{
growBuf.addChar(c);
if (c == '\n')
{
// special handling of space followed by * at beginning of line
while (*p == ' ' || *p == '\t') p++;
while (*p == '*') p++;
// special attention in case character at end is /
if (*p == '/') p++;
}
}
// special attention in case */ at end of last line
size_t len = growBuf.getPos();
if (len>=2 && growBuf.at(len-1) == '/' && growBuf.at(len-2) == '*')
{
len -= 2;
while (len>0 && growBuf.at(len-1) == '*') len--;
while (len>0 && ((c = growBuf.at(len-1)) == ' ' || c == '\t')) len--;
growBuf.setPos(len);
}
growBuf.addChar(0);
return growBuf.get();
}
| 21,459
|
C++
|
.cpp
| 786
| 23.483461
| 117
| 0.641554
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,436
|
latexdocvisitor.cpp
|
doxygen_doxygen/src/latexdocvisitor.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2022 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.
*
*/
#include <algorithm>
#include <array>
#include "htmlattrib.h"
#include "latexdocvisitor.h"
#include "latexgen.h"
#include "docparser.h"
#include "language.h"
#include "doxygen.h"
#include "outputgen.h"
#include "outputlist.h"
#include "dot.h"
#include "util.h"
#include "message.h"
#include "parserintf.h"
#include "msc.h"
#include "dia.h"
#include "cite.h"
#include "filedef.h"
#include "config.h"
#include "htmlentity.h"
#include "emoji.h"
#include "plantuml.h"
#include "fileinfo.h"
#include "regex.h"
#include "portable.h"
#include "codefragment.h"
static const int g_maxLevels = 7;
static const std::array<const char *,g_maxLevels> g_secLabels =
{ "doxysection",
"doxysubsection",
"doxysubsubsection",
"doxysubsubsubsection",
"doxysubsubsubsubsection",
"doxysubsubsubsubsubsection",
"doxysubsubsubsubsubsubsection"
};
static const char *g_paragraphLabel = "doxyparagraph";
static const char *g_subparagraphLabel = "doxysubparagraph";
const char *LatexDocVisitor::getSectionName(int level) const
{
bool compactLatex = Config_getBool(COMPACT_LATEX);
int l = level;
if (compactLatex) l++;
if (l < g_maxLevels)
{
l += m_hierarchyLevel; /* May be -1 if generating main page */
// Sections get special treatment because they inherit the parent's level
if (l >= g_maxLevels)
{
l = g_maxLevels - 1;
}
else if (l < 0)
{
/* Should not happen; level is always >= 1 and hierarchyLevel >= -1 */
l = 0;
}
return g_secLabels[l];
}
else if (l == 7)
{
return g_paragraphLabel;
}
else
{
return g_subparagraphLabel;
}
}
static void insertDimension(TextStream &t, QCString dimension, const char *orientationString)
{
// dimensions for latex images can be a percentage, in this case they need some extra
// handling as the % symbol is used for comments
static const reg::Ex re(R"((\d+)%)");
std::string s = dimension.str();
reg::Match match;
if (reg::search(s,match,re))
{
bool ok = false;
double percent = QCString(match[1].str()).toInt(&ok);
if (ok)
{
t << percent/100.0 << "\\text" << orientationString;
return;
}
}
t << dimension;
}
static void visitPreStart(TextStream &t, bool hasCaption, QCString name, QCString width, QCString height, bool inlineImage = FALSE)
{
if (inlineImage)
{
t << "\n\\begin{DoxyInlineImage}\n";
}
else
{
if (hasCaption)
{
t << "\n\\begin{DoxyImage}\n";
}
else
{
t << "\n\\begin{DoxyImageNoCaption}\n"
" \\mbox{";
}
}
t << "\\includegraphics";
if (!width.isEmpty() || !height.isEmpty())
{
t << "[";
}
if (!width.isEmpty())
{
t << "width=";
insertDimension(t, width, "width");
}
if (!width.isEmpty() && !height.isEmpty())
{
t << ",";
}
if (!height.isEmpty())
{
t << "height=";
insertDimension(t, height, "height");
}
if (width.isEmpty() && height.isEmpty())
{
/* default setting */
if (inlineImage)
{
t << "[height=\\baselineskip,keepaspectratio=true]";
}
else
{
t << "[width=\\textwidth,height=\\textheight/2,keepaspectratio=true]";
}
}
else
{
t << "]";
}
t << "{" << name << "}";
if (hasCaption)
{
if (!inlineImage)
{
if (Config_getBool(PDF_HYPERLINKS))
{
t << "\n\\doxyfigcaption{";
}
else
{
t << "\n\\doxyfigcaptionnolink{";
}
}
else
{
t << "%"; // to catch the caption
}
}
}
static void visitPostEnd(TextStream &t, bool hasCaption, bool inlineImage = FALSE)
{
if (inlineImage)
{
t << "\n\\end{DoxyInlineImage}\n";
}
else
{
t << "}\n"; // end mbox or caption
if (hasCaption)
{
t << "\\end{DoxyImage}\n";
}
else
{
t << "\\end{DoxyImageNoCaption}\n";
}
}
}
static QCString makeShortName(const QCString &name)
{
QCString shortName = name;
int i = shortName.findRev('/');
if (i!=-1)
{
shortName=shortName.mid(i+1);
}
return shortName;
}
static QCString makeBaseName(const QCString &name)
{
QCString baseName = makeShortName(name);
int i=baseName.find('.');
if (i!=-1)
{
baseName=baseName.left(i);
}
return baseName;
}
void LatexDocVisitor::visitCaption(const DocNodeList &children)
{
for (const auto &n : children)
{
std::visit(*this,n);
}
}
QCString LatexDocVisitor::escapeMakeIndexChars(const char *s)
{
QCString result;
const char *p=s;
char str[2]; str[1]=0;
char c = 0;
if (p)
{
while ((c=*p++))
{
switch (c)
{
case '!': m_t << "\"!"; break;
case '"': m_t << "\"\""; break;
case '@': m_t << "\"@"; break;
case '|': m_t << "\\texttt{\"|}"; break;
case '[': m_t << "["; break;
case ']': m_t << "]"; break;
case '{': m_t << "\\lcurly{}"; break;
case '}': m_t << "\\rcurly{}"; break;
default: str[0]=c; filter(str); break;
}
}
}
return result;
}
LatexDocVisitor::LatexDocVisitor(TextStream &t,OutputCodeList &ci,LatexCodeGenerator &lcg,
const QCString &langExt, int hierarchyLevel)
: m_t(t), m_ci(ci), m_lcg(lcg), m_insidePre(FALSE),
m_insideItem(FALSE), m_hide(FALSE),
m_langExt(langExt), m_hierarchyLevel(hierarchyLevel)
{
}
//--------------------------------------
// visitor functions for leaf nodes
//--------------------------------------
void LatexDocVisitor::operator()(const DocWord &w)
{
if (m_hide) return;
filter(w.word());
}
void LatexDocVisitor::operator()(const DocLinkedWord &w)
{
if (m_hide) return;
startLink(w.ref(),w.file(),w.anchor());
filter(w.word());
endLink(w.ref(),w.file(),w.anchor());
}
void LatexDocVisitor::operator()(const DocWhiteSpace &w)
{
if (m_hide) return;
if (m_insidePre)
{
m_t << w.chars();
}
else
{
m_t << " ";
}
}
void LatexDocVisitor::operator()(const DocSymbol &s)
{
if (m_hide) return;
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
const char *res = HtmlEntityMapper::instance().latex(s.symbol());
if (res)
{
if (((s.symbol() == HtmlEntityMapper::Sym_lt) || (s.symbol() == HtmlEntityMapper::Sym_Less))&& (!m_insidePre))
{
if (pdfHyperlinks)
{
m_t << "\\texorpdfstring{$<$}{<}";
}
else
{
m_t << "$<$";
}
}
else if (((s.symbol() == HtmlEntityMapper::Sym_gt) || (s.symbol() == HtmlEntityMapper::Sym_Greater)) && (!m_insidePre))
{
if (pdfHyperlinks)
{
m_t << "\\texorpdfstring{$>$}{>}";
}
else
{
m_t << "$>$";
}
}
else
{
m_t << res;
}
}
else
{
err("LaTeX: non supported HTML-entity found: %s\n",HtmlEntityMapper::instance().html(s.symbol(),TRUE));
}
}
void LatexDocVisitor::operator()(const DocEmoji &s)
{
if (m_hide) return;
QCString emojiName = EmojiEntityMapper::instance().name(s.index());
if (!emojiName.isEmpty())
{
QCString imageName=emojiName.mid(1,emojiName.length()-2); // strip : at start and end
if (m_texOrPdf != TexOrPdf::PDF) m_t << "\\doxygenemoji{";
filter(emojiName);
if (m_texOrPdf != TexOrPdf::PDF) m_t << "}{" << imageName << "}";
}
else
{
m_t << s.name();
}
}
void LatexDocVisitor::operator()(const DocURL &u)
{
if (m_hide) return;
if (Config_getBool(PDF_HYPERLINKS))
{
m_t << "\\href{";
if (u.isEmail()) m_t << "mailto:";
m_t << latexFilterURL(u.url()) << "}";
}
m_t << "{\\texttt{ ";
filter(u.url());
m_t << "}}";
}
void LatexDocVisitor::operator()(const DocLineBreak &)
{
if (m_hide) return;
m_t << "~\\newline\n";
}
void LatexDocVisitor::operator()(const DocHorRuler &)
{
if (m_hide) return;
if (insideTable())
m_t << "\\DoxyHorRuler{1}\n";
else
m_t << "\\DoxyHorRuler{0}\n";
}
void LatexDocVisitor::operator()(const DocStyleChange &s)
{
if (m_hide) return;
switch (s.style())
{
case DocStyleChange::Bold:
if (s.enable()) m_t << "{\\bfseries{"; else m_t << "}}";
break;
case DocStyleChange::S:
case DocStyleChange::Strike:
case DocStyleChange::Del:
if (s.enable()) m_t << "\\sout{"; else m_t << "}";
break;
case DocStyleChange::Underline:
case DocStyleChange::Ins:
if (s.enable()) m_t << "\\uline{"; else m_t << "}";
break;
case DocStyleChange::Italic:
if (s.enable()) m_t << "{\\itshape "; else m_t << "}";
break;
case DocStyleChange::Kbd:
case DocStyleChange::Code:
if (s.enable()) m_t << "{\\ttfamily "; else m_t << "}";
break;
case DocStyleChange::Subscript:
if (s.enable()) m_t << "\\textsubscript{"; else m_t << "}";
break;
case DocStyleChange::Superscript:
if (s.enable()) m_t << "\\textsuperscript{"; else m_t << "}";
break;
case DocStyleChange::Center:
if (s.enable()) m_t << "\\begin{center}"; else m_t << "\\end{center} ";
break;
case DocStyleChange::Small:
if (s.enable()) m_t << "\n\\footnotesize "; else m_t << "\n\\normalsize ";
break;
case DocStyleChange::Cite:
if (s.enable()) m_t << "{\\itshape "; else m_t << "}";
break;
case DocStyleChange::Preformatted:
if (s.enable())
{
m_t << "\n\\begin{DoxyPre}";
m_insidePre=TRUE;
}
else
{
m_insidePre=FALSE;
m_t << "\\end{DoxyPre}\n";
}
break;
case DocStyleChange::Div: /* HTML only */ break;
case DocStyleChange::Span: /* HTML only */ break;
}
}
void LatexDocVisitor::operator()(const DocVerbatim &s)
{
if (m_hide) return;
QCString lang = m_langExt;
if (!s.language().isEmpty()) // explicit language setting
{
lang = s.language();
}
SrcLangExt langExt = getLanguageFromCodeLang(lang);
switch(s.type())
{
case DocVerbatim::Code:
{
m_ci.startCodeFragment("DoxyCode");
getCodeParser(lang).parseCode(m_ci,s.context(),s.text(),langExt,
Config_getBool(STRIP_CODE_COMMENTS),
s.isExample(),s.exampleFile());
m_ci.endCodeFragment("DoxyCode");
}
break;
case DocVerbatim::JavaDocLiteral:
filter(s.text(), true);
break;
case DocVerbatim::JavaDocCode:
m_t << "{\\ttfamily ";
filter(s.text(), true);
m_t << "}";
break;
case DocVerbatim::Verbatim:
m_t << "\\begin{DoxyVerb}";
m_t << s.text();
m_t << "\\end{DoxyVerb}\n";
break;
case DocVerbatim::HtmlOnly:
case DocVerbatim::XmlOnly:
case DocVerbatim::ManOnly:
case DocVerbatim::RtfOnly:
case DocVerbatim::DocbookOnly:
/* nothing */
break;
case DocVerbatim::LatexOnly:
m_t << s.text();
break;
case DocVerbatim::Dot:
{
static int dotindex = 1;
QCString fileName(4096, QCString::ExplicitSize);
fileName.sprintf("%s%d%s",
qPrint(Config_getString(LATEX_OUTPUT)+"/inline_dotgraph_"),
dotindex++,
".dot"
);
std::ofstream file = Portable::openOutputStream(fileName);
if (!file.is_open())
{
err("Could not open file %s for writing\n",qPrint(fileName));
}
else
{
file.write( s.text().data(), s.text().length() );
file.close();
startDotFile(fileName,s.width(),s.height(),s.hasCaption(),s.srcFile(),s.srcLine());
visitChildren(s);
endDotFile(s.hasCaption());
if (Config_getBool(DOT_CLEANUP)) Dir().remove(fileName.str());
}
}
break;
case DocVerbatim::Msc:
{
static int mscindex = 1;
QCString baseName(4096, QCString::ExplicitSize);
baseName.sprintf("%s%d",
qPrint(Config_getString(LATEX_OUTPUT)+"/inline_mscgraph_"),
mscindex++
);
QCString fileName = baseName+".msc";
std::ofstream file = Portable::openOutputStream(fileName);
if (!file.is_open())
{
err("Could not open file %s for writing\n",qPrint(fileName));
}
else
{
QCString text = "msc {";
text+=s.text();
text+="}";
file.write( text.data(), text.length() );
file.close();
writeMscFile(baseName, s);
if (Config_getBool(DOT_CLEANUP)) Dir().remove(fileName.str());
}
}
break;
case DocVerbatim::PlantUML:
{
QCString latexOutput = Config_getString(LATEX_OUTPUT);
QCString baseName = PlantumlManager::instance().writePlantUMLSource(
latexOutput,s.exampleFile(),s.text(),
s.useBitmap() ? PlantumlManager::PUML_BITMAP : PlantumlManager::PUML_EPS,
s.engine(),s.srcFile(),s.srcLine(),true);
writePlantUMLFile(baseName, s);
}
break;
}
}
void LatexDocVisitor::operator()(const DocAnchor &anc)
{
if (m_hide) return;
m_t << "\\label{" << stripPath(anc.file()) << "_" << anc.anchor() << "}%\n";
if (!anc.file().isEmpty() && Config_getBool(PDF_HYPERLINKS))
{
m_t << "\\Hypertarget{" << stripPath(anc.file()) << "_" << anc.anchor()
<< "}%\n";
}
}
void LatexDocVisitor::operator()(const DocInclude &inc)
{
if (m_hide) return;
SrcLangExt langExt = getLanguageFromFileName(inc.extension());
switch(inc.type())
{
case DocInclude::IncWithLines:
{
m_ci.startCodeFragment("DoxyCodeInclude");
FileInfo cfi( inc.file().str() );
auto fd = createFileDef( cfi.dirPath(), cfi.fileName() );
getCodeParser(inc.extension()).parseCode(m_ci,inc.context(),
inc.text(),
langExt,
inc.stripCodeComments(),
inc.isExample(),
inc.exampleFile(),
fd.get(), // fileDef,
-1, // start line
-1, // end line
FALSE, // inline fragment
nullptr, // memberDef
TRUE // show line numbers
);
m_ci.endCodeFragment("DoxyCodeInclude");
}
break;
case DocInclude::Include:
{
m_ci.startCodeFragment("DoxyCodeInclude");
getCodeParser(inc.extension()).parseCode(m_ci,inc.context(),
inc.text(),langExt,
inc.stripCodeComments(),
inc.isExample(),
inc.exampleFile(),
nullptr, // fileDef
-1, // startLine
-1, // endLine
TRUE, // inlineFragment
nullptr, // memberDef
FALSE
);
m_ci.endCodeFragment("DoxyCodeInclude");
}
break;
case DocInclude::DontInclude:
case DocInclude::DontIncWithLines:
case DocInclude::HtmlInclude:
case DocInclude::RtfInclude:
case DocInclude::ManInclude:
case DocInclude::XmlInclude:
case DocInclude::DocbookInclude:
break;
case DocInclude::LatexInclude:
m_t << inc.text();
break;
case DocInclude::VerbInclude:
m_t << "\n\\begin{DoxyVerbInclude}\n";
m_t << inc.text();
m_t << "\\end{DoxyVerbInclude}\n";
break;
case DocInclude::Snippet:
case DocInclude::SnippetWithLines:
{
m_ci.startCodeFragment("DoxyCodeInclude");
CodeFragmentManager::instance().parseCodeFragment(m_ci,
inc.file(),
inc.blockId(),
inc.context(),
inc.type()==DocInclude::SnippetWithLines,
inc.trimLeft(),
inc.stripCodeComments()
);
m_ci.endCodeFragment("DoxyCodeInclude");
}
break;
}
}
void LatexDocVisitor::operator()(const DocIncOperator &op)
{
//printf("DocIncOperator: type=%d first=%d, last=%d text='%s'\n",
// op.type(),op.isFirst(),op.isLast(),qPrint(op.text()));
if (op.isFirst())
{
if (!m_hide) m_ci.startCodeFragment("DoxyCodeInclude");
pushHidden(m_hide);
m_hide = TRUE;
}
QCString locLangExt = getFileNameExtension(op.includeFileName());
if (locLangExt.isEmpty()) locLangExt = m_langExt;
SrcLangExt langExt = getLanguageFromFileName(locLangExt);
if (op.type()!=DocIncOperator::Skip)
{
m_hide = popHidden();
if (!m_hide)
{
std::unique_ptr<FileDef> fd;
if (!op.includeFileName().isEmpty())
{
FileInfo cfi( op.includeFileName().str() );
fd = createFileDef( cfi.dirPath(), cfi.fileName() );
}
getCodeParser(locLangExt).parseCode(m_ci,op.context(),op.text(),langExt,
op.stripCodeComments(),
op.isExample(),op.exampleFile(),
fd.get(), // fileDef
op.line(), // startLine
-1, // endLine
FALSE, // inline fragment
nullptr, // memberDef
op.showLineNo() // show line numbers
);
}
pushHidden(m_hide);
m_hide=TRUE;
}
if (op.isLast())
{
m_hide=popHidden();
if (!m_hide) m_ci.endCodeFragment("DoxyCodeInclude");
}
else
{
if (!m_hide) m_t << "\n";
}
}
void LatexDocVisitor::operator()(const DocFormula &f)
{
if (m_hide) return;
QCString s = f.text();
const char *p = s.data();
char c = 0;
if (p)
{
while ((c=*p++))
{
switch (c)
{
case '\'': m_t << "\\textnormal{\\textquotesingle}"; break;
default: m_t << c; break;
}
}
}
}
void LatexDocVisitor::operator()(const DocIndexEntry &i)
{
if (m_hide) return;
m_t << "\\index{";
m_t << latexEscapeLabelName(i.entry());
m_t << "@{";
m_t << latexEscapeIndexChars(i.entry());
m_t << "}}";
}
void LatexDocVisitor::operator()(const DocSimpleSectSep &)
{
}
void LatexDocVisitor::operator()(const DocCite &cite)
{
if (m_hide) return;
if (!cite.file().isEmpty())
{
//startLink(cite.ref(),cite.file(),cite.anchor());
QCString anchor = cite.anchor();
QCString anchorPrefix = CitationManager::instance().anchorPrefix();
anchor = anchor.mid(anchorPrefix.length()); // strip prefix
m_t << "\\cite{" << anchor << "}";
}
else
{
m_t << "{\\bfseries [";
filter(cite.text());
m_t << "]}";
}
}
//--------------------------------------
// visitor functions for compound nodes
//--------------------------------------
void LatexDocVisitor::operator()(const DocAutoList &l)
{
if (m_hide) return;
if (m_indentLevel>=maxIndentLevels-1) return;
if (l.isEnumList())
{
m_t << "\n\\begin{DoxyEnumerate}";
m_listItemInfo[indentLevel()].isEnum = true;
}
else
{
m_listItemInfo[indentLevel()].isEnum = false;
m_t << "\n\\begin{DoxyItemize}";
}
visitChildren(l);
if (l.isEnumList())
{
m_t << "\n\\end{DoxyEnumerate}";
}
else
{
m_t << "\n\\end{DoxyItemize}";
}
}
void LatexDocVisitor::operator()(const DocAutoListItem &li)
{
if (m_hide) return;
switch (li.itemNumber())
{
case DocAutoList::Unchecked: // unchecked
m_t << "\n\\item[\\DoxyUnchecked] ";
break;
case DocAutoList::Checked_x: // checked with x
case DocAutoList::Checked_X: // checked with X
m_t << "\n\\item[\\DoxyChecked] ";
break;
default:
m_t << "\n\\item ";
break;
}
incIndentLevel();
visitChildren(li);
decIndentLevel();
}
void LatexDocVisitor::operator()(const DocPara &p)
{
if (m_hide) return;
visitChildren(p);
if (!p.isLast() && // omit <p> for last paragraph
!(p.parent() && // and for parameter sections
std::get_if<DocParamSect>(p.parent())
)
) m_t << "\n\n";
}
void LatexDocVisitor::operator()(const DocRoot &r)
{
visitChildren(r);
}
void LatexDocVisitor::operator()(const DocSimpleSect &s)
{
if (m_hide) return;
switch(s.type())
{
case DocSimpleSect::See:
m_t << "\\begin{DoxySeeAlso}{";
filter(theTranslator->trSeeAlso());
break;
case DocSimpleSect::Return:
m_t << "\\begin{DoxyReturn}{";
filter(theTranslator->trReturns());
break;
case DocSimpleSect::Author:
m_t << "\\begin{DoxyAuthor}{";
filter(theTranslator->trAuthor(TRUE,TRUE));
break;
case DocSimpleSect::Authors:
m_t << "\\begin{DoxyAuthor}{";
filter(theTranslator->trAuthor(TRUE,FALSE));
break;
case DocSimpleSect::Version:
m_t << "\\begin{DoxyVersion}{";
filter(theTranslator->trVersion());
break;
case DocSimpleSect::Since:
m_t << "\\begin{DoxySince}{";
filter(theTranslator->trSince());
break;
case DocSimpleSect::Date:
m_t << "\\begin{DoxyDate}{";
filter(theTranslator->trDate());
break;
case DocSimpleSect::Note:
m_t << "\\begin{DoxyNote}{";
filter(theTranslator->trNote());
break;
case DocSimpleSect::Warning:
m_t << "\\begin{DoxyWarning}{";
filter(theTranslator->trWarning());
break;
case DocSimpleSect::Pre:
m_t << "\\begin{DoxyPrecond}{";
filter(theTranslator->trPrecondition());
break;
case DocSimpleSect::Post:
m_t << "\\begin{DoxyPostcond}{";
filter(theTranslator->trPostcondition());
break;
case DocSimpleSect::Copyright:
m_t << "\\begin{DoxyCopyright}{";
filter(theTranslator->trCopyright());
break;
case DocSimpleSect::Invar:
m_t << "\\begin{DoxyInvariant}{";
filter(theTranslator->trInvariant());
break;
case DocSimpleSect::Remark:
m_t << "\\begin{DoxyRemark}{";
filter(theTranslator->trRemarks());
break;
case DocSimpleSect::Attention:
m_t << "\\begin{DoxyAttention}{";
filter(theTranslator->trAttention());
break;
case DocSimpleSect::Important:
m_t << "\\begin{DoxyImportant}{";
filter(theTranslator->trImportant());
break;
case DocSimpleSect::User:
m_t << "\\begin{DoxyParagraph}{";
break;
case DocSimpleSect::Rcs:
m_t << "\\begin{DoxyParagraph}{";
break;
case DocSimpleSect::Unknown: break;
}
if (s.title())
{
m_insideItem=TRUE;
std::visit(*this,*s.title());
m_insideItem=FALSE;
}
m_t << "}\n";
incIndentLevel();
visitChildren(s);
switch(s.type())
{
case DocSimpleSect::See:
m_t << "\n\\end{DoxySeeAlso}\n";
break;
case DocSimpleSect::Return:
m_t << "\n\\end{DoxyReturn}\n";
break;
case DocSimpleSect::Author:
m_t << "\n\\end{DoxyAuthor}\n";
break;
case DocSimpleSect::Authors:
m_t << "\n\\end{DoxyAuthor}\n";
break;
case DocSimpleSect::Version:
m_t << "\n\\end{DoxyVersion}\n";
break;
case DocSimpleSect::Since:
m_t << "\n\\end{DoxySince}\n";
break;
case DocSimpleSect::Date:
m_t << "\n\\end{DoxyDate}\n";
break;
case DocSimpleSect::Note:
m_t << "\n\\end{DoxyNote}\n";
break;
case DocSimpleSect::Warning:
m_t << "\n\\end{DoxyWarning}\n";
break;
case DocSimpleSect::Pre:
m_t << "\n\\end{DoxyPrecond}\n";
break;
case DocSimpleSect::Post:
m_t << "\n\\end{DoxyPostcond}\n";
break;
case DocSimpleSect::Copyright:
m_t << "\n\\end{DoxyCopyright}\n";
break;
case DocSimpleSect::Invar:
m_t << "\n\\end{DoxyInvariant}\n";
break;
case DocSimpleSect::Remark:
m_t << "\n\\end{DoxyRemark}\n";
break;
case DocSimpleSect::Attention:
m_t << "\n\\end{DoxyAttention}\n";
break;
case DocSimpleSect::Important:
m_t << "\n\\end{DoxyImportant}\n";
break;
case DocSimpleSect::User:
m_t << "\n\\end{DoxyParagraph}\n";
break;
case DocSimpleSect::Rcs:
m_t << "\n\\end{DoxyParagraph}\n";
break;
default:
break;
}
decIndentLevel();
}
void LatexDocVisitor::operator()(const DocTitle &t)
{
if (m_hide) return;
visitChildren(t);
}
void LatexDocVisitor::operator()(const DocSimpleList &l)
{
if (m_hide) return;
m_t << "\\begin{DoxyItemize}\n";
m_listItemInfo[indentLevel()].isEnum = false;
visitChildren(l);
m_t << "\\end{DoxyItemize}\n";
}
void LatexDocVisitor::operator()(const DocSimpleListItem &li)
{
if (m_hide) return;
m_t << "\\item ";
incIndentLevel();
if (li.paragraph())
{
visit(*this,*li.paragraph());
}
decIndentLevel();
}
void LatexDocVisitor::operator()(const DocSection &s)
{
if (m_hide) return;
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
if (pdfHyperlinks)
{
m_t << "\\hypertarget{" << stripPath(s.file()) << "_" << s.anchor() << "}{}";
}
m_t << "\\" << getSectionName(s.level()) << "{";
if (pdfHyperlinks)
{
m_t << "\\texorpdfstring{";
}
if (s.title())
{
if (pdfHyperlinks) m_texOrPdf = TexOrPdf::TEX;
std::visit(*this,*s.title());
m_texOrPdf = TexOrPdf::NO;
}
if (pdfHyperlinks)
{
m_t << "}{";
if (s.title())
{
if (pdfHyperlinks) m_texOrPdf = TexOrPdf::PDF;
std::visit(*this,*s.title());
m_texOrPdf = TexOrPdf::NO;
}
m_t << "}";
}
m_t << "}\\label{" << stripPath(s.file()) << "_" << s.anchor() << "}\n";
visitChildren(s);
}
void LatexDocVisitor::operator()(const DocHtmlList &s)
{
if (m_hide) return;
if (m_indentLevel>=maxIndentLevels-1) return;
m_listItemInfo[indentLevel()].isEnum = s.type()==DocHtmlList::Ordered;
if (s.type()==DocHtmlList::Ordered)
{
bool first = true;
m_t << "\n\\begin{DoxyEnumerate}";
for (const auto &opt : s.attribs())
{
if (opt.name=="type")
{
if (opt.value=="1")
{
m_t << (first ? "[": ",");
m_t << "label=\\arabic*";
first = false;
}
else if (opt.value=="a")
{
m_t << (first ? "[": ",");
m_t << "label=\\enumalphalphcnt*";
first = false;
}
else if (opt.value=="A")
{
m_t << (first ? "[": ",");
m_t << "label=\\enumAlphAlphcnt*";
first = false;
}
else if (opt.value=="i")
{
m_t << (first ? "[": ",");
m_t << "label=\\roman*";
first = false;
}
else if (opt.value=="I")
{
m_t << (first ? "[": ",");
m_t << "label=\\Roman*";
first = false;
}
}
else if (opt.name=="start")
{
m_t << (first ? "[": ",");
bool ok = false;
int val = opt.value.toInt(&ok);
if (ok) m_t << "start=" << val;
first = false;
}
}
if (!first) m_t << "]\n";
}
else
{
m_t << "\n\\begin{DoxyItemize}";
}
visitChildren(s);
if (m_indentLevel>=maxIndentLevels-1) return;
if (s.type()==DocHtmlList::Ordered)
m_t << "\n\\end{DoxyEnumerate}";
else
m_t << "\n\\end{DoxyItemize}";
}
void LatexDocVisitor::operator()(const DocHtmlListItem &l)
{
if (m_hide) return;
if (m_listItemInfo[indentLevel()].isEnum)
{
for (const auto &opt : l.attribs())
{
if (opt.name=="value")
{
bool ok = false;
int val = opt.value.toInt(&ok);
if (ok)
{
m_t << "\n\\setcounter{DoxyEnumerate" << integerToRoman(indentLevel()+1,false) << "}{" << (val - 1) << "}";
}
}
}
}
m_t << "\n\\item ";
incIndentLevel();
visitChildren(l);
decIndentLevel();
}
static bool classEqualsReflist(const DocHtmlDescList &dl)
{
HtmlAttribList attrs = dl.attribs();
auto it = std::find_if(attrs.begin(),attrs.end(),
[](const auto &att) { return att.name=="class"; });
if (it!=attrs.end() && it->value == "reflist") return true;
return false;
}
static bool listIsNested(const DocHtmlDescList &dl)
{
bool isNested=false;
const DocNodeVariant *n = dl.parent();
while (n && !isNested)
{
if (std::get_if<DocHtmlDescList>(n))
{
isNested = !classEqualsReflist(std::get<DocHtmlDescList>(*n));
}
n = ::parent(n);
}
return isNested;
}
void LatexDocVisitor::operator()(const DocHtmlDescList &dl)
{
if (m_hide) return;
bool eq = classEqualsReflist(dl);
if (eq)
{
m_t << "\n\\begin{DoxyRefList}";
}
else
{
if (listIsNested(dl)) m_t << "\n\\hfill";
m_t << "\n\\begin{DoxyDescription}";
}
visitChildren(dl);
if (eq)
{
m_t << "\n\\end{DoxyRefList}";
}
else
{
m_t << "\n\\end{DoxyDescription}";
}
}
void LatexDocVisitor::operator()(const DocHtmlDescTitle &dt)
{
if (m_hide) return;
m_t << "\n\\item[";
m_insideItem=TRUE;
visitChildren(dt);
m_insideItem=FALSE;
m_t << "]";
}
void LatexDocVisitor::operator()(const DocHtmlDescData &dd)
{
incIndentLevel();
if (!m_insideItem) m_t << "\\hfill";
m_t << " \\\\\n";
visitChildren(dd);
decIndentLevel();
}
static bool tableIsNested(const DocNodeVariant *n)
{
bool isNested=FALSE;
while (n && !isNested)
{
isNested = holds_one_of_alternatives<DocHtmlTable,DocParamSect>(*n);
n = ::parent(n);
}
return isNested;
}
static void writeStartTableCommand(TextStream &t,const DocNodeVariant *n,size_t cols)
{
if (tableIsNested(n))
{
t << "{\\begin{tabularx}{\\linewidth}{|*{" << cols << "}{>{\\raggedright\\arraybackslash}X|}}";
}
else
{
t << "\\tabulinesep=1mm\n\\begin{longtabu}spread 0pt [c]{*{" << cols << "}{|X[-1]}|}\n";
}
//return isNested ? "TabularNC" : "TabularC";
}
static void writeEndTableCommand(TextStream &t,const DocNodeVariant *n)
{
if (tableIsNested(n))
{
t << "\\end{tabularx}}\n";
}
else
{
t << "\\end{longtabu}\n";
}
//return isNested ? "TabularNC" : "TabularC";
}
void LatexDocVisitor::operator()(const DocHtmlTable &t)
{
if (m_hide) return;
pushTableState();
const DocHtmlCaption *c = t.caption() ? &std::get<DocHtmlCaption>(*t.caption()) : nullptr;
if (c)
{
bool pdfHyperLinks = Config_getBool(PDF_HYPERLINKS);
if (!c->file().isEmpty() && pdfHyperLinks)
{
m_t << "\\hypertarget{" << stripPath(c->file()) << "_" << c->anchor()
<< "}{}";
}
m_t << "\n";
}
writeStartTableCommand(m_t,t.parent(),t.numColumns());
if (c)
{
m_t << "\\caption{";
std::visit(*this, *t.caption());
m_t << "}";
m_t << "\\label{" << stripPath(c->file()) << "_" << c->anchor() << "}";
m_t << "\\\\\n";
}
setNumCols(t.numColumns());
m_t << "\\hline\n";
// check if first row is a heading and then render the row already here
// and end it with \endfirsthead (triggered via m_firstRow==TRUE)
// then repeat the row as normal and end it with \endhead (m_firstRow==FALSE)
const DocHtmlRow *firstRow = std::get_if<DocHtmlRow>(t.firstRow());
if (firstRow && firstRow->isHeading())
{
setFirstRow(TRUE);
if (!tableIsNested(t.parent()))
{
std::visit(*this,*t.firstRow());
}
setFirstRow(FALSE);
}
visitChildren(t);
writeEndTableCommand(m_t,t.parent());
popTableState();
}
void LatexDocVisitor::operator()(const DocHtmlCaption &c)
{
if (m_hide) return;
visitChildren(c);
}
void LatexDocVisitor::operator()(const DocHtmlRow &row)
{
if (m_hide) return;
setCurrentColumn(0);
visitChildren(row);
size_t c=currentColumn();
while (c<=numCols()) // end of row while inside a row span?
{
for (const auto &span : rowSpans())
{
//printf(" found row span: column=%d rs=%d cs=%d rowIdx=%d cell->rowIdx=%d i=%d c=%d\n",
// span->column, span->rowSpan,span->colSpan,row.rowIndex(),span->cell->rowIndex(),i,c);
if (span.rowSpan>0 && span.column==c && // we are at a cell in a row span
row.rowIndex()>span.cell.rowIndex() // but not the row that started the span
)
{
m_t << "&";
if (span.colSpan>1) // row span is also part of a column span
{
m_t << "\\multicolumn{" << span.colSpan << "}{";
m_t << "}|}{}";
}
else // solitary row span
{
m_t << "\\multicolumn{1}{c|}{}";
}
}
}
c++;
}
m_t << "\\\\";
size_t col = 1;
for (auto &span : rowSpans())
{
if (span.rowSpan>0) span.rowSpan--;
if (span.rowSpan<=0)
{
// inactive span
}
else if (span.column>col)
{
m_t << "\\cline{" << col << "-" << (span.column-1) << "}";
col = span.column+span.colSpan;
}
else
{
col = span.column+span.colSpan;
}
}
if (col <= numCols())
{
m_t << "\\cline{" << col << "-" << numCols() << "}";
}
m_t << "\n";
const DocNodeVariant *n = ::parent(row.parent());
if (row.isHeading() && row.rowIndex()==1 && !tableIsNested(n))
{
if (firstRow())
{
m_t << "\\endfirsthead\n";
m_t << "\\hline\n";
m_t << "\\endfoot\n";
m_t << "\\hline\n";
}
else
{
m_t << "\\endhead\n";
}
}
}
void LatexDocVisitor::operator()(const DocHtmlCell &c)
{
if (m_hide) return;
const DocHtmlRow *row = std::get_if<DocHtmlRow>(c.parent());
setCurrentColumn(currentColumn()+1);
//Skip columns that span from above.
for (const auto &span : rowSpans())
{
if (span.rowSpan>0 && span.column==currentColumn())
{
if (row && span.colSpan>1)
{
m_t << "\\multicolumn{" << span.colSpan << "}{";
if (currentColumn() /*c.columnIndex()*/==1) // add extra | for first column
{
m_t << "|";
}
m_t << "l|}{" << (c.isHeading()? "\\columncolor{\\tableheadbgcolor}" : "") << "}"; // alignment not relevant, empty column
setCurrentColumn(currentColumn()+span.colSpan);
}
else
{
setCurrentColumn(currentColumn()+1);
}
m_t << "&";
}
}
int cs = c.colSpan();
int a = c.alignment();
if (cs>1 && row)
{
setInColSpan(TRUE);
m_t << "\\multicolumn{" << cs << "}{";
if (c.columnIndex()==1) // add extra | for first column
{
m_t << "|";
}
switch (a)
{
case DocHtmlCell::Right:
m_t << "r|}{";
break;
case DocHtmlCell::Center:
m_t << "c|}{";
break;
default:
m_t << "l|}{";
break;
}
}
int rs = c.rowSpan();
int va = c.valignment();
if (rs>0)
{
setInRowSpan(TRUE);
m_t << "\\multirow";
switch(va)
{
case DocHtmlCell::Top:
m_t << "[t]";
break;
case DocHtmlCell::Bottom:
m_t << "[b]";
break;
case DocHtmlCell::Middle:
break; // No alignment option needed
default:
break;
}
//printf("adding row span: cell={r=%d c=%d rs=%d cs=%d} curCol=%d\n",
// c.rowIndex(),c.columnIndex(),c.rowSpan(),c.colSpan(),
// currentColumn());
addRowSpan(ActiveRowSpan(c,rs,cs,currentColumn()));
m_t << "{" << rs << "}{*}{";
}
if (a==DocHtmlCell::Center)
{
m_t << "\\PBS\\centering ";
}
else if (a==DocHtmlCell::Right)
{
m_t << "\\PBS\\raggedleft ";
}
if (c.isHeading())
{
m_t << "\\cellcolor{\\tableheadbgcolor}\\textbf{ ";
}
if (cs>1)
{
setCurrentColumn(currentColumn()+cs-1);
}
visitChildren(c);
if (c.isHeading())
{
m_t << "}";
}
if (inRowSpan())
{
setInRowSpan(FALSE);
m_t << "}";
}
if (inColSpan())
{
setInColSpan(FALSE);
m_t << "}";
}
if (!c.isLast()) m_t << "&";
}
void LatexDocVisitor::operator()(const DocInternal &i)
{
if (m_hide) return;
visitChildren(i);
}
void LatexDocVisitor::operator()(const DocHRef &href)
{
if (m_hide) return;
if (Config_getBool(PDF_HYPERLINKS))
{
m_t << "\\href{";
m_t << latexFilterURL(href.url());
m_t << "}";
}
m_t << "{\\texttt{ ";
visitChildren(href);
m_t << "}}";
}
void LatexDocVisitor::operator()(const DocHtmlSummary &d)
{
if (m_hide) return;
m_t << "{\\bfseries{";
visitChildren(d);
m_t << "}}";
}
void LatexDocVisitor::operator()(const DocHtmlDetails &d)
{
if (m_hide) return;
m_t << "\n\n";
auto summary = d.summary();
if (summary)
{
std::visit(*this,*summary);
m_t << "\\begin{adjustwidth}{1em}{0em}\n";
}
visitChildren(d);
if (summary)
{
m_t << "\\end{adjustwidth}\n";
}
else
{
m_t << "\n\n";
}
}
void LatexDocVisitor::operator()(const DocHtmlHeader &header)
{
if (m_hide) return;
m_t << "\\" << getSectionName(header.level()) << "*{";
visitChildren(header);
m_t << "}";
}
void LatexDocVisitor::operator()(const DocImage &img)
{
if (img.type()==DocImage::Latex)
{
if (m_hide) return;
QCString gfxName = img.name();
if (gfxName.endsWith(".eps") || gfxName.endsWith(".pdf"))
{
gfxName=gfxName.left(gfxName.length()-4);
}
visitPreStart(m_t,img.hasCaption(), gfxName, img.width(), img.height(), img.isInlineImage());
visitChildren(img);
visitPostEnd(m_t,img.hasCaption(), img.isInlineImage());
}
else // other format -> skip
{
}
}
void LatexDocVisitor::operator()(const DocDotFile &df)
{
if (m_hide) return;
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(LATEX_OUTPUT)+"/"+stripPath(df.file()));
startDotFile(df.file(),df.width(),df.height(),df.hasCaption(),df.srcFile(),df.srcLine());
visitChildren(df);
endDotFile(df.hasCaption());
}
void LatexDocVisitor::operator()(const DocMscFile &df)
{
if (m_hide) return;
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(LATEX_OUTPUT)+"/"+stripPath(df.file()));
startMscFile(df.file(),df.width(),df.height(),df.hasCaption(),df.srcFile(),df.srcLine());
visitChildren(df);
endMscFile(df.hasCaption());
}
void LatexDocVisitor::operator()(const DocDiaFile &df)
{
if (m_hide) return;
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(LATEX_OUTPUT)+"/"+stripPath(df.file()));
startDiaFile(df.file(),df.width(),df.height(),df.hasCaption(),df.srcFile(),df.srcLine());
visitChildren(df);
endDiaFile(df.hasCaption());
}
void LatexDocVisitor::operator()(const DocPlantUmlFile &df)
{
if (m_hide) return;
if (!Config_getBool(DOT_CLEANUP)) copyFile(df.file(),Config_getString(LATEX_OUTPUT)+"/"+stripPath(df.file()));
startPlantUmlFile(df.file(),df.width(),df.height(),df.hasCaption(),df.srcFile(),df.srcLine());
visitChildren(df);
endPlantUmlFile(df.hasCaption());
}
void LatexDocVisitor::operator()(const DocLink &lnk)
{
if (m_hide) return;
startLink(lnk.ref(),lnk.file(),lnk.anchor());
visitChildren(lnk);
endLink(lnk.ref(),lnk.file(),lnk.anchor());
}
void LatexDocVisitor::operator()(const DocRef &ref)
{
if (m_hide) return;
// when ref.isSubPage()==TRUE we use ref.file() for HTML and
// ref.anchor() for LaTeX/RTF
if (ref.isSubPage())
{
startLink(ref.ref(),QCString(),ref.anchor());
}
else
{
if (!ref.file().isEmpty()) startLink(ref.ref(),ref.file(),ref.anchor(),ref.refToTable(),ref.refToSection());
}
if (!ref.hasLinkText())
{
filter(ref.targetTitle());
}
visitChildren(ref);
if (ref.isSubPage())
{
endLink(ref.ref(),QCString(),ref.anchor());
}
else
{
if (!ref.file().isEmpty()) endLink(ref.ref(),ref.file(),ref.anchor(),ref.refToTable(),ref.refToSection(),ref.sectionType());
}
}
void LatexDocVisitor::operator()(const DocSecRefItem &ref)
{
if (m_hide) return;
m_t << "\\item \\contentsline{section}{";
if (ref.isSubPage())
{
startLink(ref.ref(),QCString(),ref.anchor());
}
else
{
if (!ref.file().isEmpty())
{
startLink(ref.ref(),ref.file(),ref.anchor(),ref.refToTable());
}
}
visitChildren(ref);
if (ref.isSubPage())
{
endLink(ref.ref(),QCString(),ref.anchor());
}
else
{
if (!ref.file().isEmpty()) endLink(ref.ref(),ref.file(),ref.anchor(),ref.refToTable());
}
m_t << "}{\\ref{";
if (!ref.file().isEmpty()) m_t << stripPath(ref.file());
if (!ref.file().isEmpty() && !ref.anchor().isEmpty()) m_t << "_";
if (!ref.anchor().isEmpty()) m_t << ref.anchor();
m_t << "}}{}\n";
}
void LatexDocVisitor::operator()(const DocSecRefList &l)
{
if (m_hide) return;
m_t << "\\footnotesize\n";
m_t << "\\begin{multicols}{2}\n";
m_t << "\\begin{DoxyCompactList}\n";
incIndentLevel();
visitChildren(l);
decIndentLevel();
m_t << "\\end{DoxyCompactList}\n";
m_t << "\\end{multicols}\n";
m_t << "\\normalsize\n";
}
void LatexDocVisitor::operator()(const DocParamSect &s)
{
if (m_hide) return;
bool hasInOutSpecs = s.hasInOutSpecifier();
bool hasTypeSpecs = s.hasTypeSpecifier();
m_lcg.incUsedTableLevel();
switch(s.type())
{
case DocParamSect::Param:
m_t << "\n\\begin{DoxyParams}";
if (hasInOutSpecs && hasTypeSpecs) m_t << "[2]"; // 2 extra cols
else if (hasInOutSpecs || hasTypeSpecs) m_t << "[1]"; // 1 extra col
m_t << "{";
filter(theTranslator->trParameters());
break;
case DocParamSect::RetVal:
m_t << "\n\\begin{DoxyRetVals}{";
filter(theTranslator->trReturnValues());
break;
case DocParamSect::Exception:
m_t << "\n\\begin{DoxyExceptions}{";
filter(theTranslator->trExceptions());
break;
case DocParamSect::TemplateParam:
m_t << "\n\\begin{DoxyTemplParams}{";
filter(theTranslator->trTemplateParameters());
break;
default:
ASSERT(0);
incIndentLevel();
}
m_t << "}\n";
visitChildren(s);
m_lcg.decUsedTableLevel();
switch(s.type())
{
case DocParamSect::Param:
m_t << "\\end{DoxyParams}\n";
break;
case DocParamSect::RetVal:
m_t << "\\end{DoxyRetVals}\n";
break;
case DocParamSect::Exception:
m_t << "\\end{DoxyExceptions}\n";
break;
case DocParamSect::TemplateParam:
m_t << "\\end{DoxyTemplParams}\n";
break;
default:
ASSERT(0);
decIndentLevel();
}
}
void LatexDocVisitor::operator()(const DocSeparator &sep)
{
m_t << " " << sep.chars() << " ";
}
void LatexDocVisitor::operator()(const DocParamList &pl)
{
if (m_hide) return;
DocParamSect::Type parentType = DocParamSect::Unknown;
const DocParamSect *sect = std::get_if<DocParamSect>(pl.parent());
if (sect)
{
parentType = sect->type();
}
bool useTable = parentType==DocParamSect::Param ||
parentType==DocParamSect::RetVal ||
parentType==DocParamSect::Exception ||
parentType==DocParamSect::TemplateParam;
if (!useTable)
{
m_t << "\\item[";
}
if (sect && sect->hasInOutSpecifier())
{
if (pl.direction()!=DocParamSect::Unspecified)
{
m_t << "\\mbox{\\texttt{ ";
if (pl.direction()==DocParamSect::In)
{
m_t << "in";
}
else if (pl.direction()==DocParamSect::Out)
{
m_t << "out";
}
else if (pl.direction()==DocParamSect::InOut)
{
m_t << "in,out";
}
m_t << "}} ";
}
if (useTable) m_t << " & ";
}
if (sect && sect->hasTypeSpecifier())
{
for (const auto &type : pl.paramTypes())
{
std::visit(*this,type);
}
if (useTable) m_t << " & ";
}
m_t << "{\\em ";
bool first=TRUE;
for (const auto ¶m : pl.parameters())
{
if (!first) m_t << ","; else first=FALSE;
m_insideItem=TRUE;
std::visit(*this,param);
m_insideItem=FALSE;
}
m_t << "}";
if (useTable)
{
m_t << " & ";
}
else
{
m_t << "]";
}
for (const auto &par : pl.paragraphs())
{
std::visit(*this,par);
}
if (useTable)
{
m_t << "\\\\\n"
<< "\\hline\n";
}
}
void LatexDocVisitor::operator()(const DocXRefItem &x)
{
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
if (m_hide) return;
if (x.title().isEmpty()) return;
incIndentLevel();
m_t << "\\begin{DoxyRefDesc}{";
filter(x.title());
m_t << "}\n";
bool anonymousEnum = x.file()=="@";
m_t << "\\item[";
if (pdfHyperlinks && !anonymousEnum)
{
m_t << "\\mbox{\\hyperlink{" << stripPath(x.file()) << "_" << x.anchor() << "}{";
}
else
{
m_t << "\\textbf{ ";
}
m_insideItem=TRUE;
filter(x.title());
m_insideItem=FALSE;
if (pdfHyperlinks && !anonymousEnum)
{
m_t << "}";
}
m_t << "}]";
visitChildren(x);
if (x.title().isEmpty()) return;
decIndentLevel();
m_t << "\\end{DoxyRefDesc}\n";
}
void LatexDocVisitor::operator()(const DocInternalRef &ref)
{
if (m_hide) return;
startLink(QCString(),ref.file(),ref.anchor());
visitChildren(ref);
endLink(QCString(),ref.file(),ref.anchor());
}
void LatexDocVisitor::operator()(const DocText &t)
{
if (m_hide) return;
visitChildren(t);
}
void LatexDocVisitor::operator()(const DocHtmlBlockQuote &q)
{
if (m_hide) return;
m_t << "\\begin{quote}\n";
incIndentLevel();
visitChildren(q);
m_t << "\\end{quote}\n";
decIndentLevel();
}
void LatexDocVisitor::operator()(const DocVhdlFlow &)
{
}
void LatexDocVisitor::operator()(const DocParBlock &pb)
{
if (m_hide) return;
visitChildren(pb);
}
void LatexDocVisitor::filter(const QCString &str, const bool retainNewLine)
{
//printf("LatexDocVisitor::filter(%s) m_insideTabbing=%d\n",qPrint(str),m_ci.insideTabbing());
filterLatexString(m_t,str,
m_lcg.insideTabbing(),
m_insidePre,
m_insideItem,
m_lcg.usedTableLevel()>0, // insideTable
false, // keepSpaces
retainNewLine
);
}
void LatexDocVisitor::startLink(const QCString &ref,const QCString &file,const QCString &anchor,
bool refToTable,bool refToSection)
{
bool pdfHyperLinks = Config_getBool(PDF_HYPERLINKS);
if (ref.isEmpty() && pdfHyperLinks) // internal PDF link
{
if (refToTable)
{
m_t << "\\doxytablelink{";
}
else if (refToSection)
{
if (m_texOrPdf == TexOrPdf::TEX) m_t << "\\protect";
if (m_texOrPdf != TexOrPdf::PDF) m_t << "\\doxysectlink{";
}
else
{
if (m_texOrPdf == TexOrPdf::TEX) m_t << "\\protect";
if (m_texOrPdf != TexOrPdf::PDF) m_t << "\\doxylink{";
}
if (refToTable || m_texOrPdf != TexOrPdf::PDF)
{
if (!file.isEmpty()) m_t << stripPath(file);
if (!file.isEmpty() && !anchor.isEmpty()) m_t << "_";
if (!anchor.isEmpty()) m_t << anchor;
m_t << "}";
}
m_t << "{";
}
else if (ref.isEmpty() && refToSection)
{
m_t << "\\doxysectref{";
}
else if (ref.isEmpty() && refToTable)
{
m_t << "\\doxytableref{";
}
else if (ref.isEmpty()) // internal non-PDF link
{
m_t << "\\doxyref{";
}
else // external link
{
m_t << "\\textbf{ ";
}
}
void LatexDocVisitor::endLink(const QCString &ref,const QCString &file,const QCString &anchor,bool /*refToTable*/,bool refToSection, SectionType sectionType)
{
m_t << "}";
bool pdfHyperLinks = Config_getBool(PDF_HYPERLINKS);
if (ref.isEmpty() && !pdfHyperLinks)
{
m_t << "{";
filter(theTranslator->trPageAbbreviation());
m_t << "}{" << file;
if (!file.isEmpty() && !anchor.isEmpty()) m_t << "_";
m_t << anchor << "}";
if (refToSection)
{
m_t << "{" << sectionType.level() << "}";
}
}
if (ref.isEmpty() && pdfHyperLinks) // internal PDF link
{
if (refToSection)
{
if (m_texOrPdf != TexOrPdf::PDF) m_t << "{" << sectionType.level() << "}";
}
}
}
void LatexDocVisitor::startDotFile(const QCString &fileName,
const QCString &width,
const QCString &height,
bool hasCaption,
const QCString &srcFile,
int srcLine
)
{
QCString baseName=makeBaseName(fileName);
baseName.prepend("dot_");
QCString outDir = Config_getString(LATEX_OUTPUT);
QCString name = fileName;
writeDotGraphFromFile(name,outDir,baseName,GraphOutputFormat::EPS,srcFile,srcLine);
visitPreStart(m_t,hasCaption, baseName, width, height);
}
void LatexDocVisitor::endDotFile(bool hasCaption)
{
if (m_hide) return;
visitPostEnd(m_t,hasCaption);
}
void LatexDocVisitor::startMscFile(const QCString &fileName,
const QCString &width,
const QCString &height,
bool hasCaption,
const QCString &srcFile,
int srcLine
)
{
QCString baseName=makeBaseName(fileName);
baseName.prepend("msc_");
QCString outDir = Config_getString(LATEX_OUTPUT);
writeMscGraphFromFile(fileName,outDir,baseName,MscOutputFormat::EPS,srcFile,srcLine);
visitPreStart(m_t,hasCaption, baseName, width, height);
}
void LatexDocVisitor::endMscFile(bool hasCaption)
{
if (m_hide) return;
visitPostEnd(m_t,hasCaption);
}
void LatexDocVisitor::writeMscFile(const QCString &baseName, const DocVerbatim &s)
{
QCString shortName = makeShortName(baseName);
QCString outDir = Config_getString(LATEX_OUTPUT);
writeMscGraphFromFile(baseName+".msc",outDir,shortName,MscOutputFormat::EPS,s.srcFile(),s.srcLine());
visitPreStart(m_t, s.hasCaption(), shortName, s.width(),s.height());
visitCaption(s.children());
visitPostEnd(m_t, s.hasCaption());
}
void LatexDocVisitor::startDiaFile(const QCString &fileName,
const QCString &width,
const QCString &height,
bool hasCaption,
const QCString &srcFile,
int srcLine
)
{
QCString baseName=makeBaseName(fileName);
baseName.prepend("dia_");
QCString outDir = Config_getString(LATEX_OUTPUT);
writeDiaGraphFromFile(fileName,outDir,baseName,DiaOutputFormat::EPS,srcFile,srcLine);
visitPreStart(m_t,hasCaption, baseName, width, height);
}
void LatexDocVisitor::endDiaFile(bool hasCaption)
{
if (m_hide) return;
visitPostEnd(m_t,hasCaption);
}
void LatexDocVisitor::writeDiaFile(const QCString &baseName, const DocVerbatim &s)
{
QCString shortName = makeShortName(baseName);
QCString outDir = Config_getString(LATEX_OUTPUT);
writeDiaGraphFromFile(baseName+".dia",outDir,shortName,DiaOutputFormat::EPS,s.srcFile(),s.srcLine());
visitPreStart(m_t, s.hasCaption(), shortName, s.width(), s.height());
visitCaption(s.children());
visitPostEnd(m_t, s.hasCaption());
}
void LatexDocVisitor::writePlantUMLFile(const QCString &baseName, const DocVerbatim &s)
{
QCString shortName = makeShortName(baseName);
if (s.useBitmap())
{
if (shortName.find('.')==-1) shortName += ".png";
}
QCString outDir = Config_getString(LATEX_OUTPUT);
PlantumlManager::instance().generatePlantUMLOutput(baseName,outDir,
s.useBitmap() ? PlantumlManager::PUML_BITMAP : PlantumlManager::PUML_EPS);
visitPreStart(m_t, s.hasCaption(), shortName, s.width(), s.height());
visitCaption(s.children());
visitPostEnd(m_t, s.hasCaption());
}
void LatexDocVisitor::startPlantUmlFile(const QCString &fileName,
const QCString &width,
const QCString &height,
bool hasCaption,
const QCString &srcFile,
int srcLine
)
{
QCString outDir = Config_getString(LATEX_OUTPUT);
std::string inBuf;
readInputFile(fileName,inBuf);
bool useBitmap = inBuf.find("@startditaa") != std::string::npos;
QCString baseName = PlantumlManager::instance().writePlantUMLSource(
outDir,QCString(),inBuf.c_str(),
useBitmap ? PlantumlManager::PUML_BITMAP : PlantumlManager::PUML_EPS,
QCString(),srcFile,srcLine,false);
baseName=makeBaseName(baseName);
QCString shortName = makeShortName(baseName);
if (useBitmap)
{
if (shortName.find('.')==-1) shortName += ".png";
}
PlantumlManager::instance().generatePlantUMLOutput(baseName,outDir,
useBitmap ? PlantumlManager::PUML_BITMAP : PlantumlManager::PUML_EPS);
visitPreStart(m_t,hasCaption, shortName, width, height);
}
void LatexDocVisitor::endPlantUmlFile(bool hasCaption)
{
if (m_hide) return;
visitPostEnd(m_t,hasCaption);
}
int LatexDocVisitor::indentLevel() const
{
return std::min(m_indentLevel,maxIndentLevels-1);
}
void LatexDocVisitor::incIndentLevel()
{
m_indentLevel++;
if (m_indentLevel>=maxIndentLevels)
{
err("Maximum indent level (%d) exceeded while generating LaTeX output!\n",maxIndentLevels-1);
}
}
void LatexDocVisitor::decIndentLevel()
{
if (m_indentLevel>0)
{
m_indentLevel--;
}
}
| 54,862
|
C++
|
.cpp
| 1,974
| 21.837386
| 157
| 0.569118
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,437
|
latexgen.cpp
|
doxygen_doxygen/src/latexgen.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 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.
*
*/
#include <cstdlib>
#include "latexgen.h"
#include "config.h"
#include "message.h"
#include "doxygen.h"
#include "util.h"
#include "diagram.h"
#include "language.h"
#include "version.h"
#include "dot.h"
#include "dotcallgraph.h"
#include "dotclassgraph.h"
#include "dotdirdeps.h"
#include "dotgroupcollaboration.h"
#include "dotincldepgraph.h"
#include "pagedef.h"
#include "docparser.h"
#include "docnode.h"
#include "latexdocvisitor.h"
#include "dirdef.h"
#include "cite.h"
#include "groupdef.h"
#include "classlist.h"
#include "namespacedef.h"
#include "filename.h"
#include "resourcemgr.h"
#include "portable.h"
#include "fileinfo.h"
#include "utf8.h"
#include "datetime.h"
#include "portable.h"
#include "outputlist.h"
#include "moduledef.h"
static QCString g_header;
static QCString g_footer;
static const SelectionMarkerInfo latexMarkerInfo = { '%', "%%BEGIN ",8 ,"%%END ",6, "",0 };
static QCString substituteLatexKeywords(const QCString &str, const QCString &title);
LatexCodeGenerator::LatexCodeGenerator(TextStream *t,const QCString &relPath,const QCString &sourceFileName)
: m_t(t), m_relPath(relPath), m_sourceFileName(sourceFileName)
{
}
LatexCodeGenerator::LatexCodeGenerator(TextStream *t) : m_t(t)
{
}
void LatexCodeGenerator::setRelativePath(const QCString &path)
{
m_relPath = path;
}
void LatexCodeGenerator::setSourceFileName(const QCString &name)
{
m_sourceFileName = name;
}
void LatexCodeGenerator::codify(const QCString &str)
{
if (!str.isEmpty())
{
const char *p=str.data();
char c = 0;
//char cs[5];
int tabSize = Config_getInt(TAB_SIZE);
static THREAD_LOCAL char *result = nullptr;
static THREAD_LOCAL int lresult = 0;
if (m_hide) // only update column count
{
m_col = updateColumnCount(p,m_col);
}
else // actually output content and keep track of m_col
{
while ((c=*p))
{
switch(c)
{
case 0x0c: p++; // remove ^L
break;
case ' ': if (m_col>=m_stripIndentAmount)
{
*m_t << (m_doxyCodeLineOpen ? "\\ " : " ");
}
m_col++;
p++;
break;
case '^': *m_t <<"\\string^";
m_col++;
p++;
break;
case '`': *m_t <<"\\`{}";
m_col++;
p++;
break;
case '\t': {
int spacesToNextTabStop = tabSize - (m_col%tabSize);
while (spacesToNextTabStop--)
{
if (m_col>=m_stripIndentAmount)
{
*m_t << (m_doxyCodeLineOpen ? "\\ " : " ");
}
m_col++;
}
p++;
}
break;
case '\n': *m_t << '\n';
m_col=0;
p++;
break;
default:
{
int i=0;
#undef COPYCHAR
// helper macro to copy a single utf8 character, dealing with multibyte chars.
#define COPYCHAR() do { \
int bytes = getUTF8CharNumBytes(c); \
if (lresult < (i + bytes + 1)) \
{ \
lresult += 512; \
result = static_cast<char *>(realloc(result, lresult)); \
} \
for (int j=0; j<bytes && *p; j++) \
{ \
result[i++]=*p++; \
} \
m_col++; \
} while(0)
// gather characters until we find whitespace or another special character
COPYCHAR();
while ((c=*p) &&
c!=0x0c && c!='\t' && c!='\n' && c!=' ' && c!='^'
)
{
COPYCHAR();
}
result[i]=0; // add terminator
filterLatexString(*m_t,result,
m_insideTabbing, // insideTabbing
true, // insidePre
false, // insideItem
m_usedTableLevel>0, // insideTable
false // keepSpaces
);
}
break;
}
}
}
}
}
void LatexCodeGenerator::stripCodeComments(bool b)
{
m_stripCodeComments = b;
}
void LatexCodeGenerator::startSpecialComment()
{
m_hide = m_stripCodeComments;
}
void LatexCodeGenerator::endSpecialComment()
{
m_hide = false;
}
void LatexCodeGenerator::setStripIndentAmount(size_t amount)
{
m_stripIndentAmount = amount;
}
void LatexCodeGenerator::writeCodeLink(CodeSymbolType,
const QCString &ref,const QCString &f,
const QCString &anchor,const QCString &name,
const QCString &)
{
if (m_hide) return;
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
bool usePDFLatex = Config_getBool(USE_PDFLATEX);
size_t l = name.length();
if (ref.isEmpty() && usePDFLatex && pdfHyperlinks)
{
*m_t << "\\mbox{\\hyperlink{";
if (!f.isEmpty()) *m_t << stripPath(f);
if (!f.isEmpty() && !anchor.isEmpty()) *m_t << "_";
if (!anchor.isEmpty()) *m_t << anchor;
*m_t << "}{";
codify(name);
*m_t << "}}";
}
else
{
codify(name);
}
m_col+=l;
}
void LatexCodeGenerator::writeLineNumber(const QCString &ref,const QCString &fileName,const QCString &anchor,int l,bool writeLineAnchor)
{
if (m_hide) return;
bool usePDFLatex = Config_getBool(USE_PDFLATEX);
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
if (!m_doxyCodeLineOpen)
{
*m_t << "\\DoxyCodeLine{";
m_doxyCodeLineOpen = TRUE;
}
if (Config_getBool(SOURCE_BROWSER))
{
QCString lineNumber;
lineNumber.sprintf("%05d",l);
QCString lineAnchor;
if (!m_sourceFileName.isEmpty())
{
lineAnchor.sprintf("_l%05d",l);
lineAnchor.prepend(stripExtensionGeneral(m_sourceFileName, ".tex"));
}
bool showTarget = usePDFLatex && pdfHyperlinks && !lineAnchor.isEmpty() && writeLineAnchor;
if (showTarget)
{
*m_t << "\\Hypertarget{" << stripPath(lineAnchor) << "}";
}
if (!fileName.isEmpty())
{
writeCodeLink(CodeSymbolType::Default,ref,fileName,anchor,lineNumber,QCString());
}
else
{
codify(lineNumber);
}
*m_t << "\\ ";
}
else
{
QCString lineNumber;
lineNumber.sprintf("%05d",l);
codify(lineNumber);
*m_t << "\\ ";
}
m_col=0;
}
void LatexCodeGenerator::startCodeLine(int)
{
if (m_hide) return;
m_col=0;
if (!m_doxyCodeLineOpen)
{
*m_t << "\\DoxyCodeLine{";
m_doxyCodeLineOpen = TRUE;
}
}
void LatexCodeGenerator::endCodeLine()
{
if (m_hide) return;
if (m_doxyCodeLineOpen)
{
*m_t << "}";
m_doxyCodeLineOpen = FALSE;
}
codify("\n");
}
void LatexCodeGenerator::startFontClass(const QCString &name)
{
if (m_hide) return;
*m_t << "\\textcolor{" << name << "}{";
}
void LatexCodeGenerator::endFontClass()
{
if (m_hide) return;
*m_t << "}";
}
void LatexCodeGenerator::startCodeFragment(const QCString &style)
{
*m_t << "\n\\begin{" << style << "}{" << m_usedTableLevel << "}\n";
}
void LatexCodeGenerator::endCodeFragment(const QCString &style)
{
//endCodeLine checks is there is still an open code line, if so closes it.
endCodeLine();
*m_t << "\\end{" << style << "}\n";
}
//-------------------------------
LatexGenerator::LatexGenerator()
: OutputGenerator(Config_getString(LATEX_OUTPUT))
, m_codeList(std::make_unique<OutputCodeList>())
{
m_codeGen = m_codeList->add<LatexCodeGenerator>(&m_t);
}
LatexGenerator::LatexGenerator(const LatexGenerator &og) : OutputGenerator(og.m_dir), OutputGenIntf()
{
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<LatexCodeGenerator>(OutputType::Latex);
m_codeGen->setTextStream(&m_t);
m_firstDescItem = og.m_firstDescItem;
m_disableLinks = og.m_disableLinks;
m_relPath = og.m_relPath;
m_indent = og.m_indent;
m_templateMemberItem = og.m_templateMemberItem;
m_hierarchyLevel = og.m_hierarchyLevel;
}
LatexGenerator &LatexGenerator::operator=(const LatexGenerator &og)
{
if (this!=&og)
{
m_dir = og.m_dir;
m_codeList = std::make_unique<OutputCodeList>(*og.m_codeList);
m_codeGen = m_codeList->get<LatexCodeGenerator>(OutputType::Latex);
m_codeGen->setTextStream(&m_t);
m_firstDescItem = og.m_firstDescItem;
m_disableLinks = og.m_disableLinks;
m_relPath = og.m_relPath;
m_indent = og.m_indent;
m_templateMemberItem = og.m_templateMemberItem;
m_hierarchyLevel = og.m_hierarchyLevel;
}
return *this;
}
LatexGenerator::~LatexGenerator() = default;
void LatexGenerator::addCodeGen(OutputCodeList &list)
{
list.add<LatexCodeGeneratorDefer>(m_codeGen);
}
static void writeLatexMakefile()
{
bool generateBib = !CitationManager::instance().isEmpty();
QCString fileName=Config_getString(LATEX_OUTPUT)+"/Makefile";
std::ofstream f = Portable::openOutputStream(fileName);
if (!f.is_open())
{
term("Could not open file %s for writing\n",qPrint(fileName));
}
TextStream t(&f);
// inserted by KONNO Akihisa <konno@researchers.jp> 2002-03-05
QCString latex_command = theTranslator->latexCommandName().quoted();
QCString mkidx_command = Config_getString(MAKEINDEX_CMD_NAME).quoted();
QCString bibtex_command = "bibtex";
QCString manual_file = "refman";
const int latex_count = 8;
// end insertion by KONNO Akihisa <konno@researchers.jp> 2002-03-05
t << "LATEX_CMD?=" << latex_command << "\n"
<< "MKIDX_CMD?=" << mkidx_command << "\n"
<< "BIBTEX_CMD?=" << bibtex_command << "\n"
<< "LATEX_COUNT?=" << latex_count << "\n"
<< "MANUAL_FILE?=" << manual_file << "\n"
<< "\n";
if (!Config_getBool(USE_PDFLATEX)) // use plain old latex
{
t << "all: $(MANUAL_FILE).dvi\n"
<< "\n"
<< "ps: $(MANUAL_FILE).ps\n"
<< "\n"
<< "pdf: $(MANUAL_FILE).pdf\n"
<< "\n"
<< "ps_2on1: $(MANUAL_FILE).ps\n"
<< "\n"
<< "pdf_2on1: $(MANUAL_FILE).pdf\n"
<< "\n"
<< "$(MANUAL_FILE).ps: $(MANUAL_FILE).dvi\n"
<< "\tdvips -o $(MANUAL_FILE).ps $(MANUAL_FILE).dvi\n"
<< "\n";
t << "$(MANUAL_FILE).pdf: $(MANUAL_FILE).ps\n";
t << "\tps2pdf $(MANUAL_FILE).ps $(MANUAL_FILE).pdf\n\n";
t << "$(MANUAL_FILE).dvi: clean $(MANUAL_FILE).tex doxygen.sty\n"
<< "\techo \"Running latex...\"\n"
<< "\t$(LATEX_CMD) $(MANUAL_FILE).tex || \\\n"
<< "\tif [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\tfi\n"
<< "\techo \"Running makeindex...\"\n"
<< "\t$(MKIDX_CMD) $(MANUAL_FILE).idx\n";
if (generateBib)
{
t << "\techo \"Running bibtex...\"\n";
t << "\t$(BIBTEX_CMD) $(MANUAL_FILE)\n";
t << "\techo \"Rerunning latex....\"\n";
t << "\t$(LATEX_CMD) $(MANUAL_FILE).tex || \\\n"
<< "\tif [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\tfi\n";
}
t << "\techo \"Rerunning latex....\"\n"
<< "\t$(LATEX_CMD) $(MANUAL_FILE).tex\n"
<< "\tlatex_count=$(LATEX_COUNT) ; \\\n"
<< "\twhile grep -E -s 'Rerun (LaTeX|to get cross-references right|to get bibliographical references right)' $(MANUAL_FILE).log && [ $$latex_count -gt 0 ] ;\\\n"
<< "\t do \\\n"
<< "\t echo \"Rerunning latex....\" ;\\\n"
<< "\t $(LATEX_CMD) $(MANUAL_FILE).tex ; \\\n"
<< "\t $(LATEX_CMD) $(MANUAL_FILE).tex || \\\n"
<< "\t if [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\t fi; \\\n"
<< "\t latex_count=`expr $$latex_count - 1` ;\\\n"
<< "\t done\n"
<< "\t$(MKIDX_CMD) $(MANUAL_FILE).idx\n"
<< "\t$(LATEX_CMD) $(MANUAL_FILE).tex || \\\n"
<< "\tif [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\tfi\n"
<< "$(MANUAL_FILE).ps: $(MANUAL_FILE).ps\n"
<< "\tpsnup -2 $(MANUAL_FILE).ps >$(MANUAL_FILE).ps\n"
<< "\n"
<< "$(MANUAL_FILE).pdf: $(MANUAL_FILE).ps\n"
<< "\tps2pdf $(MANUAL_FILE).ps $(MANUAL_FILE).pdf\n";
}
else // use pdflatex for higher quality output
{
t << "all: $(MANUAL_FILE).pdf\n\n"
<< "pdf: $(MANUAL_FILE).pdf\n\n";
t << "$(MANUAL_FILE).pdf: clean $(MANUAL_FILE).tex\n";
t << "\t$(LATEX_CMD) $(MANUAL_FILE) || \\\n"
<< "\tif [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\tfi\n";
t << "\t$(MKIDX_CMD) $(MANUAL_FILE).idx\n";
if (generateBib)
{
t << "\t$(BIBTEX_CMD) $(MANUAL_FILE)\n";
t << "\t$(LATEX_CMD) $(MANUAL_FILE) || \\\n"
<< "\tif [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\tfi\n";
}
t << "\t$(LATEX_CMD) $(MANUAL_FILE) || \\\n"
<< "\tif [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\tfi\n"
<< "\tlatex_count=$(LATEX_COUNT) ; \\\n"
<< "\twhile grep -E -s 'Rerun (LaTeX|to get cross-references right|to get bibliographical references right)' $(MANUAL_FILE).log && [ $$latex_count -gt 0 ] ;\\\n"
<< "\t do \\\n"
<< "\t echo \"Rerunning latex....\" ;\\\n"
<< "\t $(LATEX_CMD) $(MANUAL_FILE) || \\\n"
<< "\t if [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\t fi; \\\n"
<< "\t latex_count=`expr $$latex_count - 1` ;\\\n"
<< "\t done\n"
<< "\t$(MKIDX_CMD) $(MANUAL_FILE).idx\n"
<< "\t$(LATEX_CMD) $(MANUAL_FILE) || \\\n"
<< "\tif [ $$? != 0 ] ; then \\\n"
<< "\t \\echo \"Please consult $(MANUAL_FILE).log to see the error messages\" ; \\\n"
<< "\t false; \\\n"
<< "\tfi\n";
}
t << "\n"
<< "clean:\n"
<< "\trm -f "
<< "*.ps *.dvi *.aux *.toc *.idx *.ind *.ilg *.log *.out *.brf *.blg *.bbl $(MANUAL_FILE).pdf\n";
}
static void writeMakeBat()
{
#if defined(_MSC_VER)
QCString dir=Config_getString(LATEX_OUTPUT);
QCString fileName=dir+"/make.bat";
QCString latex_command = theTranslator->latexCommandName().quoted();
QCString mkidx_command = Config_getString(MAKEINDEX_CMD_NAME).quoted();
QCString bibtex_command = "bibtex";
QCString manual_file = "refman";
const int latex_count = 8;
bool generateBib = !CitationManager::instance().isEmpty();
std::ofstream t = Portable::openOutputStream(fileName);
if (!t.is_open())
{
term("Could not open file %s for writing\n",qPrint(fileName));
}
t << "pushd %~dp0\r\n";
t << "if not %errorlevel% == 0 goto :end1\r\n";
t << "\r\n";
t << "set ORG_LATEX_CMD=%LATEX_CMD%\r\n";
t << "set ORG_MKIDX_CMD=%MKIDX_CMD%\r\n";
t << "set ORG_BIBTEX_CMD=%BIBTEX_CMD%\r\n";
t << "set ORG_LATEX_COUNT=%LATEX_COUNT%\r\n";
t << "set ORG_MANUAL_FILE=%MANUAL_FILE%\r\n";
t << "if \"X\"%LATEX_CMD% == \"X\" set LATEX_CMD=" << latex_command << "\r\n";
t << "if \"X\"%MKIDX_CMD% == \"X\" set MKIDX_CMD=" << mkidx_command << "\r\n";
t << "if \"X\"%BIBTEX_CMD% == \"X\" set BIBTEX_CMD=" << bibtex_command << "\r\n";
t << "if \"X\"%LATEX_COUNT% == \"X\" set LATEX_COUNT=" << latex_count << "\r\n";
t << "if \"X\"%MANUAL_FILE% == \"X\" set MANUAL_FILE=" << manual_file << "\r\n";
t << "\r\n";
t << "del /s /f *.ps *.dvi *.aux *.toc *.idx *.ind *.ilg *.log *.out *.brf *.blg *.bbl %MANUAL_FILE%.pdf\r\n\r\n";
t << "\r\n";
if (!Config_getBool(USE_PDFLATEX)) // use plain old latex
{
t << "%LATEX_CMD% %MANUAL_FILE%.tex\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
t << "echo ----\r\n";
t << "%MKIDX_CMD% %MANUAL_FILE%.idx\r\n";
if (generateBib)
{
t << "%BIBTEX_CMD% %MANUAL_FILE%\r\n";
t << "echo ----\r\n";
t << "\t%LATEX_CMD% %MANUAL_FILE%.tex\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
}
t << "setlocal enabledelayedexpansion\r\n";
t << "set count=%LAT#EX_COUNT%\r\n";
t << ":repeat\r\n";
t << "set content=X\r\n";
t << "for /F \"tokens=*\" %%T in ( 'findstr /C:\"Rerun LaTeX\" %MANUAL_FILE%.log' ) do set content=\"%%~T\"\r\n";
t << "if !content! == X for /F \"tokens=*\" %%T in ( 'findstr /C:\"Rerun to get cross-references right\" %MANUAL_FILE%.log' ) do set content=\"%%~T\"\r\n";
t << "if !content! == X for /F \"tokens=*\" %%T in ( 'findstr /C:\"Rerun to get bibliographical references right\" %MANUAL_FILE%.log' ) do set content=\"%%~T\"\r\n";
t << "if !content! == X goto :skip\r\n";
t << "set /a count-=1\r\n";
t << "if !count! EQU 0 goto :skip\r\n\r\n";
t << "echo ----\r\n";
t << "%LATEX_CMD% %MANUAL_FILE%.tex\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
t << "goto :repeat\r\n";
t << ":skip\r\n";
t << "endlocal\r\n";
t << "%MKIDX_CMD% %MANUAL_FILE%.idx\r\n";
t << "%LATEX_CMD% %MANUAL_FILE%.tex\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
t << "dvips -o %MANUAL_FILE%.ps %MANUAL_FILE%.dvi\r\n";
t << Portable::ghostScriptCommand();
t << " -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite "
"-sOutputFile=%MANUAL_FILE%.pdf -c save pop -f %MANUAL_FILE%.ps\r\n";
}
else // use pdflatex
{
t << "%LATEX_CMD% %MANUAL_FILE%\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
t << "echo ----\r\n";
t << "%MKIDX_CMD% %MANUAL_FILE%.idx\r\n";
if (generateBib)
{
t << "%BIBTEX_CMD% %MANUAL_FILE%\r\n";
t << "%LATEX_CMD% %MANUAL_FILE%\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
}
t << "echo ----\r\n";
t << "%LATEX_CMD% %MANUAL_FILE%\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
t << "\r\n";
t << "setlocal enabledelayedexpansion\r\n";
t << "set count=%LATEX_COUNT%\r\n";
t << ":repeat\r\n";
t << "set content=X\r\n";
t << "for /F \"tokens=*\" %%T in ( 'findstr /C:\"Rerun LaTeX\" %MANUAL_FILE%.log' ) do set content=\"%%~T\"\r\n";
t << "if !content! == X for /F \"tokens=*\" %%T in ( 'findstr /C:\"Rerun to get cross-references right\" %MANUAL_FILE%.log' ) do set content=\"%%~T\"\r\n";
t << "if !content! == X for /F \"tokens=*\" %%T in ( 'findstr /C:\"Rerun to get bibliographical references right\" %MANUAL_FILE%.log' ) do set content=\"%%~T\"\r\n";
t << "if !content! == X goto :skip\r\n";
t << "set /a count-=1\r\n";
t << "if !count! EQU 0 goto :skip\r\n\r\n";
t << "echo ----\r\n";
t << "%LATEX_CMD% %MANUAL_FILE%\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
t << "goto :repeat\r\n";
t << ":skip\r\n";
t << "endlocal\r\n";
t << "%MKIDX_CMD% %MANUAL_FILE%.idx\r\n";
t << "%LATEX_CMD% %MANUAL_FILE%\r\n";
t << "@if ERRORLEVEL 1 goto :error\r\n";
}
t<< "\r\n";
t << "goto :end\r\n";
t << ":error\r\n";
t << "@echo ===============\r\n";
t << "@echo Please consult %MANUAL_FILE%.log to see the error messages\r\n";
t << "@echo ===============\r\n";
t<< "\r\n";
t<< ":end\r\n";
t<< "@REM reset environment\r\n";
t<< "popd\r\n";
t<< "set LATEX_CMD=%ORG_LATEX_CMD%\r\n";
t<< "set ORG_LATEX_CMD=\r\n";
t<< "set MKIDX_CMD=%ORG_MKIDX_CMD%\r\n";
t<< "set ORG_MKIDX_CMD=\r\n";
t<< "set BIBTEX_CMD=%ORG_BIBTEX_CMD%\r\n";
t<< "set ORG_BIBTEX_CMD=\r\n";
t<< "set MANUAL_FILE=%ORG_MANUAL_FILE%\r\n";
t<< "set ORG_MANUAL_FILE=\r\n";
t<< "set LATEX_COUNT=%ORG_LATEX_COUNT%\r\n";
t<< "set ORG_LATEX_COUNT=\r\n";
t<< "\r\n";
t<< ":end1\r\n";
#endif
}
void LatexGenerator::init()
{
QCString dname = Config_getString(LATEX_OUTPUT);
Dir d(dname.str());
if (!d.exists() && !d.mkdir(dname.str()))
{
term("Could not create output directory %s\n",qPrint(dname));
}
if (!Config_getString(LATEX_HEADER).isEmpty())
{
g_header=fileToString(Config_getString(LATEX_HEADER));
//printf("g_header='%s'\n",qPrint(g_header));
QCString result = substituteLatexKeywords(g_header,QCString());
checkBlocks(result,Config_getString(LATEX_HEADER),latexMarkerInfo);
}
else
{
g_header = ResourceMgr::instance().getAsString("header.tex");
QCString result = substituteLatexKeywords(g_header,QCString());
checkBlocks(result,"<default header.tex>",latexMarkerInfo);
}
if (!Config_getString(LATEX_FOOTER).isEmpty())
{
g_footer=fileToString(Config_getString(LATEX_FOOTER));
//printf("g_footer='%s'\n",qPrint(g_footer));
QCString result = substituteLatexKeywords(g_footer,QCString());
checkBlocks(result,Config_getString(LATEX_FOOTER),latexMarkerInfo);
}
else
{
g_footer = ResourceMgr::instance().getAsString("footer.tex");
QCString result = substituteLatexKeywords(g_footer,QCString());
checkBlocks(result,"<default footer.tex>",latexMarkerInfo);
}
writeLatexMakefile();
writeMakeBat();
createSubDirs(d);
}
void LatexGenerator::cleanup()
{
QCString dname = Config_getString(LATEX_OUTPUT);
Dir d(dname.str());
clearSubDirs(d);
}
static void writeDefaultStyleSheet(TextStream &t)
{
t << ResourceMgr::instance().getAsString("doxygen.sty");
}
void LatexGenerator::writeHeaderFile(TextStream &t)
{
t << "% Latex header for doxygen " << getDoxygenVersion() << "\n";
t << ResourceMgr::instance().getAsString("header.tex");
}
void LatexGenerator::writeFooterFile(TextStream &t)
{
t << "% Latex footer for doxygen " << getDoxygenVersion() << "\n";
t << ResourceMgr::instance().getAsString("footer.tex");
}
void LatexGenerator::writeStyleSheetFile(TextStream &t)
{
t << "% stylesheet for doxygen " << getDoxygenVersion() << "\n";
writeDefaultStyleSheet(t);
}
void LatexGenerator::startFile(const QCString &name,const QCString &,const QCString &,int,int hierarchyLevel)
{
#if 0
setEncoding(Config_getString(LATEX_OUTPUT_ENCODING));
#endif
QCString fileName=name;
m_hierarchyLevel = hierarchyLevel;
m_relPath = relativePathToRoot(fileName);
if (!fileName.endsWith(".tex") && !fileName.endsWith(".sty")) fileName+=".tex";
startPlainFile(fileName);
m_codeGen->setRelativePath(m_relPath);
m_codeGen->setSourceFileName(stripPath(fileName));
}
void LatexGenerator::endFile()
{
endPlainFile();
m_codeGen->setSourceFileName("");
}
//void LatexGenerator::writeIndex()
//{
// startFile("refman.tex");
//}
void LatexGenerator::startProjectNumber()
{
m_t << "\\\\[1ex]\\large ";
}
static QCString extraLatexStyleSheet()
{
QCString result;
const StringVector &extraLatexStyles = Config_getList(LATEX_EXTRA_STYLESHEET);
for (const auto &fileName : extraLatexStyles)
{
if (!fileName.empty())
{
FileInfo fi(fileName);
if (fi.exists())
{
result += "\\usepackage{";
if (checkExtension(fi.fileName().c_str(), LATEX_STYLE_EXTENSION))
{
// strip the extension, it will be added by the usepackage in the tex conversion process
result += stripExtensionGeneral(fi.fileName().c_str(), LATEX_STYLE_EXTENSION);
}
else
{
result += fi.fileName();
}
result += "}\n";
}
}
}
return result;
}
static QCString makeIndex()
{
QCString result;
QCString latex_mkidx_command = Config_getString(LATEX_MAKEINDEX_CMD);
if (!latex_mkidx_command.isEmpty())
{
if (latex_mkidx_command[0] == '\\')
result += latex_mkidx_command;
else
result += "\\"+latex_mkidx_command;
}
else
{
result += "\\makeindex";
}
return result;
}
static QCString latex_batchmode()
{
switch (Config_getEnum(LATEX_BATCHMODE))
{
case LATEX_BATCHMODE_t::NO: return "";
case LATEX_BATCHMODE_t::YES: return "\\batchmode";
case LATEX_BATCHMODE_t::BATCH: return "\\batchmode";
case LATEX_BATCHMODE_t::NON_STOP: return "\\nonstopmode";
case LATEX_BATCHMODE_t::SCROLL: return "\\scrollmode";
case LATEX_BATCHMODE_t::ERROR_STOP: return "\\errorstopmode";
}
return "";
}
static QCString substituteLatexKeywords(const QCString &str,
const QCString &title)
{
bool compactLatex = Config_getBool(COMPACT_LATEX);
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
bool usePdfLatex = Config_getBool(USE_PDFLATEX);
QCString paperType = Config_getEnumAsString(PAPER_TYPE);
QCString style = Config_getString(LATEX_BIB_STYLE);
if (style.isEmpty())
{
style="plainnat";
}
TextStream tg;
QCString generatedBy;
auto timeStamp = Config_getEnum(TIMESTAMP);
switch (timeStamp)
{
case TIMESTAMP_t::YES:
case TIMESTAMP_t::DATETIME:
generatedBy = theTranslator->trGeneratedAt(dateToString(DateTimeType::DateTime),
Config_getString(PROJECT_NAME));
break;
case TIMESTAMP_t::DATE:
generatedBy = theTranslator->trGeneratedAt(dateToString(DateTimeType::Date),
Config_getString(PROJECT_NAME));
break;
case TIMESTAMP_t::NO:
generatedBy = theTranslator->trGeneratedBy();
break;
}
filterLatexString(tg, generatedBy,
false, // insideTabbing
false, // insidePre
false, // insideItem
false, // insideTable
false // keepSpaces
);
generatedBy = tg.str();
QCString latexFontenc = theTranslator->latexFontenc();
QCString latexEmojiDirectory = Config_getString(LATEX_EMOJI_DIRECTORY);
if (latexEmojiDirectory.isEmpty()) latexEmojiDirectory = ".";
latexEmojiDirectory = substitute(latexEmojiDirectory,"\\","/");
TextStream tg1;
writeExtraLatexPackages(tg1);
QCString extraLatexPackages = tg1.str();
TextStream tg2;
writeLatexSpecialFormulaChars(tg2);
QCString latexSpecialFormulaChars = tg2.str();
QCString formulaMacrofile = Config_getString(FORMULA_MACROFILE);
QCString stripMacroFile;
if (!formulaMacrofile.isEmpty())
{
FileInfo fi(formulaMacrofile.str());
formulaMacrofile=fi.absFilePath();
stripMacroFile = fi.fileName();
copyFile(formulaMacrofile,Config_getString(LATEX_OUTPUT) + "/" + stripMacroFile);
}
QCString projectNumber = Config_getString(PROJECT_NUMBER);
// first substitute generic keywords
QCString result = substituteKeywords(str,title,
convertToLaTeX(Config_getString(PROJECT_NAME),false),
convertToLaTeX(projectNumber,false),
convertToLaTeX(Config_getString(PROJECT_BRIEF),false));
// additional LaTeX only keywords
result = substituteKeywords(result,
{
// keyword value getter
{ "$latexdocumentpre", [&]() { return theTranslator->latexDocumentPre(); } },
{ "$latexdocumentpost", [&]() { return theTranslator->latexDocumentPost(); } },
{ "$generatedby", [&]() { return generatedBy; } },
{ "$latexbibstyle", [&]() { return style; } },
{ "$latexcitereference", [&]() { return theTranslator->trCiteReferences(); } },
{ "$latexbibfiles", [&]() { return CitationManager::instance().latexBibFiles(); } },
{ "$papertype", [&]() { return paperType+"paper"; } },
{ "$extralatexstylesheet", [&]() { return extraLatexStyleSheet(); } },
{ "$languagesupport", [&]() { return theTranslator->latexLanguageSupportCommand(); } },
{ "$latexfontenc", [&]() { return latexFontenc; } },
{ "$latexfont", [&]() { return theTranslator->latexFont(); } },
{ "$latexemojidirectory", [&]() { return latexEmojiDirectory; } },
{ "$makeindex", [&]() { return makeIndex(); } },
{ "$extralatexpackages", [&]() { return extraLatexPackages; } },
{ "$latexspecialformulachars", [&]() { return latexSpecialFormulaChars; } },
{ "$formulamacrofile", [&]() { return stripMacroFile; } },
{ "$latex_batchmode", [&]() { return latex_batchmode(); } }
});
// remove conditional blocks
result = selectBlocks(result,
{
// marker is enabled
{ "CITATIONS_PRESENT", !CitationManager::instance().isEmpty() },
{ "COMPACT_LATEX", compactLatex },
{ "PDF_HYPERLINKS", pdfHyperlinks },
{ "USE_PDFLATEX", usePdfLatex },
{ "TIMESTAMP", timeStamp!=TIMESTAMP_t::NO },
{ "LATEX_FONTENC", !latexFontenc.isEmpty() },
{ "FORMULA_MACROFILE", !formulaMacrofile.isEmpty() },
{ "PROJECT_NUMBER", !projectNumber.isEmpty() }
},latexMarkerInfo);
result = removeEmptyLines(result);
return result;
}
void LatexGenerator::startIndexSection(IndexSection is)
{
bool compactLatex = Config_getBool(COMPACT_LATEX);
switch (is)
{
case IndexSection::isTitlePageStart:
m_t << substituteLatexKeywords(g_header,convertToLaTeX(Config_getString(PROJECT_NAME),m_codeGen->insideTabbing()));
break;
case IndexSection::isTitlePageAuthor:
break;
case IndexSection::isMainPage:
break;
case IndexSection::isModuleIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Module Index}\n"
break;
case IndexSection::isTopicIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Topic Index}\n"
break;
case IndexSection::isDirIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Directory Index}\n"
break;
case IndexSection::isNamespaceIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Namespace Index}\n"
break;
case IndexSection::isConceptIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Concept Index}\n"
break;
case IndexSection::isClassHierarchyIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Hierarchical Index}\n"
break;
case IndexSection::isCompoundIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Annotated Compound Index}\n"
break;
case IndexSection::isFileIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Annotated File Index}\n"
break;
case IndexSection::isPageIndex:
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Annotated Page Index}\n"
break;
case IndexSection::isTopicDocumentation:
{
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (!gd->isReference())
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Topic Documentation}\n";
break;
}
}
}
break;
case IndexSection::isModuleDocumentation:
{
for (const auto &mod : ModuleManager::instance().modules())
{
if (!mod->isReference() && mod->isPrimaryInterface())
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Topic Documentation}\n";
break;
}
}
}
break;
case IndexSection::isDirDocumentation:
{
for (const auto &dd : *Doxygen::dirLinkedMap)
{
if (dd->isLinkableInProject())
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Dir Documentation}\n";
break;
}
}
}
break;
case IndexSection::isNamespaceDocumentation:
{
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject() && !nd->isAlias())
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; // Namespace Documentation}\n":
break;
}
}
}
break;
case IndexSection::isConceptDocumentation:
{
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject() && !cd->isAlias())
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; // Concept Documentation}\n":
break;
}
}
}
break;
case IndexSection::isClassDocumentation:
{
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkableInProject() &&
cd->templateMaster()==nullptr &&
!cd->isEmbeddedInOuterScope() &&
!cd->isAlias()
)
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Compound Documentation}\n";
break;
}
}
}
break;
case IndexSection::isFileDocumentation:
{
bool isFirst=TRUE;
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->isLinkableInProject() || fd->generateSourceFile())
{
if (isFirst)
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //File Documentation}\n";
isFirst=FALSE;
break;
}
}
}
}
}
break;
case IndexSection::isExampleDocumentation:
{
if (compactLatex) m_t << "\\doxysection"; else m_t << "\\chapter";
m_t << "{"; //Example Documentation}\n";
}
break;
case IndexSection::isPageDocumentation:
break;
case IndexSection::isPageDocumentation2:
break;
case IndexSection::isEndIndex:
break;
}
}
void LatexGenerator::endIndexSection(IndexSection is)
{
switch (is)
{
case IndexSection::isTitlePageStart:
break;
case IndexSection::isTitlePageAuthor:
break;
case IndexSection::isMainPage:
{
if (Doxygen::mainPage)
{
writePageLink(Doxygen::mainPage->getOutputFileBase(), FALSE);
}
}
break;
case IndexSection::isModuleIndex:
m_t << "}\n\\input{modules}\n";
break;
case IndexSection::isTopicIndex:
m_t << "}\n\\input{topics}\n";
break;
case IndexSection::isDirIndex:
m_t << "}\n\\input{dirs}\n";
break;
case IndexSection::isNamespaceIndex:
m_t << "}\n\\input{namespaces}\n";
break;
case IndexSection::isConceptIndex:
m_t << "}\n\\input{concepts}\n";
break;
case IndexSection::isClassHierarchyIndex:
m_t << "}\n\\input{hierarchy}\n";
break;
case IndexSection::isCompoundIndex:
m_t << "}\n\\input{annotated}\n";
break;
case IndexSection::isFileIndex:
m_t << "}\n\\input{files}\n";
break;
case IndexSection::isPageIndex:
m_t << "}\n\\input{pages}\n";
break;
case IndexSection::isTopicDocumentation:
{
m_t << "}\n";
for (const auto &gd : *Doxygen::groupLinkedMap)
{
if (!gd->isReference() && !gd->isASubGroup())
{
writePageLink(gd->getOutputFileBase(), FALSE);
}
}
}
break;
case IndexSection::isModuleDocumentation:
{
m_t << "}\n";
for (const auto &mod : ModuleManager::instance().modules())
{
if (!mod->isReference() && mod->isPrimaryInterface())
{
writePageLink(mod->getOutputFileBase(), FALSE);
}
}
}
break;
case IndexSection::isDirDocumentation:
{
bool found=FALSE;
for (const auto &dd : *Doxygen::dirLinkedMap)
{
if (dd->isLinkableInProject())
{
if (!found)
{
m_t << "}\n";
found = TRUE;
}
m_t << "\\input{" << dd->getOutputFileBase() << "}\n";
}
}
}
break;
case IndexSection::isNamespaceDocumentation:
{
bool found=FALSE;
for (const auto &nd : *Doxygen::namespaceLinkedMap)
{
if (nd->isLinkableInProject() && !nd->isAlias())
{
if (!found)
{
m_t << "}\n";
found=true;
}
m_t << "\\input{" << nd->getOutputFileBase() << "}\n";
}
}
}
break;
case IndexSection::isConceptDocumentation:
{
bool found=FALSE;
for (const auto &cd : *Doxygen::conceptLinkedMap)
{
if (cd->isLinkableInProject() && !cd->isAlias())
{
if (!found)
{
m_t << "}\n";
found=true;
}
m_t << "\\input{" << cd->getOutputFileBase() << "}\n";
}
}
}
break;
case IndexSection::isClassDocumentation:
{
bool found=FALSE;
for (const auto &cd : *Doxygen::classLinkedMap)
{
if (cd->isLinkableInProject() &&
cd->templateMaster()==nullptr &&
!cd->isEmbeddedInOuterScope() &&
!cd->isAlias()
)
{
if (!found)
{
m_t << "}\n"; // end doxysection or chapter title
found=TRUE;
}
m_t << "\\input{" << cd->getOutputFileBase() << "}\n";
}
}
}
break;
case IndexSection::isFileDocumentation:
{
bool isFirst=TRUE;
for (const auto &fn : *Doxygen::inputNameLinkedMap)
{
for (const auto &fd : *fn)
{
if (fd->isLinkableInProject())
{
if (isFirst)
{
m_t << "}\n"; // end doxysection or chapter title
}
isFirst=FALSE;
m_t << "\\input{" << fd->getOutputFileBase() << "}\n";
}
if (fd->generateSourceFile())
{
if (isFirst)
{
m_t << "}\n"; // end doxysection or chapter title
}
isFirst=FALSE;
m_t << "\\input{" << fd->getSourceFileBase() << "}\n";
}
}
}
}
break;
case IndexSection::isExampleDocumentation:
{
m_t << "}\n";
for (const auto &pd : *Doxygen::exampleLinkedMap)
{
m_t << "\\input{" << pd->getOutputFileBase() << "}\n";
}
}
break;
case IndexSection::isPageDocumentation:
{
for (const auto &pd : *Doxygen::pageLinkedMap)
{
if (!pd->getGroupDef() && !pd->isReference() && !pd->hasParentPage()
&& pd->name() != "citelist" && Doxygen::mainPage.get() != pd.get())
{
writePageLink(pd->getOutputFileBase(), FALSE);
}
}
}
break;
case IndexSection::isPageDocumentation2:
break;
case IndexSection::isEndIndex:
m_t << substituteLatexKeywords(g_footer,convertToLaTeX(Config_getString(PROJECT_NAME),m_codeGen->insideTabbing()));
break;
}
}
void LatexGenerator::writePageLink(const QCString &name, bool /*first*/)
{
//bool &compactLatex = Config_getBool(COMPACT_LATEX);
// next is remove for bug615957
//if (compactLatex || first) m_t << "\\input" ; else m_t << "\\include";
m_t << "\\input" ;
m_t << "{" << name << "}\n";
}
void LatexGenerator::writeStyleInfo(int part)
{
if (part > 0)
return;
startPlainFile("doxygen.sty");
writeDefaultStyleSheet(m_t);
endPlainFile();
// workaround for the problem caused by change in LaTeX in version 2019
// in the unmaintained tabu package
startPlainFile("tabu_doxygen.sty");
m_t << ResourceMgr::instance().getAsString("tabu_doxygen.sty");
endPlainFile();
startPlainFile("longtable_doxygen.sty");
m_t << ResourceMgr::instance().getAsString("longtable_doxygen.sty");
endPlainFile();
/// an extension of the etoc package is required that is only available in the
/// newer version. Providing the updated version to be used with older versions
/// of LaTeX
startPlainFile("etoc_doxygen.sty");
m_t << ResourceMgr::instance().getAsString("etoc_doxygen.sty");
endPlainFile();
}
void LatexGenerator::startParagraph(const QCString &)
{
m_t << "\n" << "\n";
}
void LatexGenerator::endParagraph()
{
m_t << "\n" << "\n";
}
void LatexGenerator::writeString(const QCString &text)
{
m_t << text;
}
void LatexGenerator::startIndexItem(const QCString &ref,const QCString &fn)
{
m_t << "\\item ";
if (ref.isEmpty() && !fn.isEmpty())
{
m_t << "\\contentsline{section}{";
}
}
void LatexGenerator::endIndexItem(const QCString &ref,const QCString &fn)
{
if (ref.isEmpty() && !fn.isEmpty())
{
m_t << "}{\\pageref{" << stripPath(fn) << "}}{}\n";
}
}
void LatexGenerator::writeStartAnnoItem(const QCString &,const QCString &,
const QCString &path,const QCString &name)
{
m_t << "\\item\\contentsline{section}\\textbf{ ";
if (!path.isEmpty()) docify(path);
docify(name);
m_t << "} ";
}
void LatexGenerator::startIndexKey()
{
m_t << "\\item\\contentsline{section}{";
}
void LatexGenerator::endIndexKey()
{
}
void LatexGenerator::startIndexValue(bool hasBrief)
{
m_t << " ";
if (hasBrief) m_t << "\\\\*";
}
void LatexGenerator::endIndexValue(const QCString &name,bool /*hasBrief*/)
{
//if (hasBrief) m_t << ")";
m_t << "}{\\pageref{" << stripPath(name) << "}}{}\n";
}
//void LatexGenerator::writeClassLink(const QCString &,const QCString &,
// const QCString &,const QCString &name)
//{
// m_t << "\\textbf{ ";
// docify(name);
// m_t << "}";
//}
void LatexGenerator::startTextLink(const QCString &f,const QCString &anchor)
{
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
if (!m_disableLinks && pdfHyperlinks)
{
m_t << "\\mbox{\\hyperlink{";
if (!f.isEmpty()) m_t << stripPath(f);
if (!anchor.isEmpty()) m_t << "_" << anchor;
m_t << "}{";
}
else
{
m_t << "\\textbf{ ";
}
}
void LatexGenerator::endTextLink()
{
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
if (!m_disableLinks && pdfHyperlinks)
{
m_t << "}";
}
m_t << "}";
}
static QCString objectLinkToString(const QCString &ref, const QCString &f,
const QCString &anchor, const QCString &text,
bool insideTabbing,bool disableLinks)
{
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
QCString result;
if (!disableLinks && ref.isEmpty() && pdfHyperlinks)
{
result += "\\mbox{\\hyperlink{";
if (!f.isEmpty()) result += stripPath(f);
if (!f.isEmpty() && !anchor.isEmpty()) result += "_";
if (!anchor.isEmpty()) result += anchor;
result += "}{";
result += convertToLaTeX(text,insideTabbing);
result += "}}";
}
else
{
result += "\\textbf{ ";
result += convertToLaTeX(text,insideTabbing);
result += "}";
}
return result;
}
static void processEntity(TextStream &t, bool pdfHyperlinks, const char *strForm, const char *strRepl)
{
if (pdfHyperlinks)
{
t << "\\texorpdfstring{";
}
t << strForm;
if (pdfHyperlinks)
{
t << "}{" << strRepl << "}";
}
}
void LatexGenerator::writeObjectLink(const QCString &ref, const QCString &f,
const QCString &anchor, const QCString &text)
{
m_t << objectLinkToString(ref,f,anchor,text,m_codeGen->insideTabbing(),m_disableLinks);
}
void LatexGenerator::startPageRef()
{
m_t << " \\doxyref{}{";
}
void LatexGenerator::endPageRef(const QCString &clname, const QCString &anchor)
{
m_t << "}{";
if (!clname.isEmpty()) m_t << clname;
if (!anchor.isEmpty()) m_t << "_" << anchor;
m_t << "}";
}
void LatexGenerator::startTitleHead(const QCString &fileName)
{
int hierarchyLevel = m_hierarchyLevel;
if (Config_getBool(COMPACT_LATEX))
{
++hierarchyLevel;
}
if (hierarchyLevel < 0)
m_t << "\\chapter{";
else
m_t << "\\doxy" << QCString("sub").repeat(hierarchyLevel) << "section{";
}
void LatexGenerator::endTitleHead(const QCString &fileName,const QCString &name)
{
m_t << "}\n";
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
bool usePDFLatex = Config_getBool(USE_PDFLATEX);
if (usePDFLatex && pdfHyperlinks && !fileName.isEmpty())
{
m_t << "\\hypertarget{" << stripPath(fileName) << "}{}";
}
QCString fn = stripPath(fileName);
if (!fn.isEmpty())
{
m_t << "\\label{" << fn << "}";
}
if (!name.isEmpty())
{
m_t << "\\index{";
m_t << latexEscapeLabelName(name);
m_t << "@{";
m_t << latexEscapeIndexChars(name);
m_t << "}}\n";
}
}
void LatexGenerator::startTitle()
{
if (Config_getBool(COMPACT_LATEX))
{
m_t << "\\doxysubsection{";
}
else
{
m_t << "\\doxysection{";
}
}
void LatexGenerator::startGroupHeader(int extraIndentLevel)
{
if (Config_getBool(COMPACT_LATEX))
{
extraIndentLevel++;
}
if (extraIndentLevel>=3)
{
m_t << "\\doxysubparagraph*{";
}
else if (extraIndentLevel==2)
{
m_t << "\\doxyparagraph{";
}
else
{
extraIndentLevel += m_hierarchyLevel + 1;
m_t << "\\doxy" << QCString("sub").repeat(extraIndentLevel) << "section{";
}
m_disableLinks=TRUE;
}
void LatexGenerator::endGroupHeader(int)
{
m_disableLinks=FALSE;
m_t << "}\n";
}
void LatexGenerator::startMemberHeader(const QCString &,int)
{
int l = m_hierarchyLevel + 1;
if (Config_getBool(COMPACT_LATEX))
{
++l;
}
m_t << "\\doxysub" << QCString("sub").repeat(l) << "section*{";
m_disableLinks=TRUE;
}
void LatexGenerator::endMemberHeader()
{
m_disableLinks=FALSE;
m_t << "}\n";
}
void LatexGenerator::startMemberDoc(const QCString &clname,
const QCString &memname,
const QCString &,
const QCString &title,
int memCount,
int memTotal,
bool showInline)
{
if (!memname.isEmpty() && memname[0]!='@')
{
m_t << "\\index{";
if (!clname.isEmpty())
{
m_t << latexEscapeLabelName(clname);
m_t << "@{";
m_t << latexEscapeIndexChars(clname);
m_t << "}!";
}
m_t << latexEscapeLabelName(memname);
m_t << "@{";
m_t << latexEscapeIndexChars(memname);
m_t << "}}\n";
m_t << "\\index{";
m_t << latexEscapeLabelName(memname);
m_t << "@{";
m_t << latexEscapeIndexChars(memname);
m_t << "}";
if (!clname.isEmpty())
{
m_t << "!";
m_t << latexEscapeLabelName(clname);
m_t << "@{";
m_t << latexEscapeIndexChars(clname);
m_t << "}";
}
m_t << "}\n";
}
bool compactLatex = Config_getBool(COMPACT_LATEX);
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
if (showInline)
{
m_t << "\\doxysubparagraph";
}
else if (compactLatex)
{
m_t << "\\doxyparagraph";
}
else
{
m_t << "\\doxy" << QCString("sub").repeat(m_hierarchyLevel + 2) << "section";
}
m_t << "{";
if (pdfHyperlinks)
{
m_t << "\\texorpdfstring{";
}
m_t << latexEscapeIndexChars(title);
if (pdfHyperlinks)
{
m_t << "}{" << latexEscapePDFString(title) << "}";
}
if (memTotal>1)
{
m_t << "\\hspace{0.1cm}{\\footnotesize\\ttfamily [" << memCount << "/" << memTotal << "]}";
}
m_t << "}";
m_t << "\n{\\footnotesize\\ttfamily ";
//m_disableLinks=TRUE;
}
void LatexGenerator::endMemberDoc(bool)
{
m_disableLinks=FALSE;
m_t << "}\n\n";
//if (Config_getBool(COMPACT_LATEX)) m_t << "\\hfill";
}
void LatexGenerator::startDoxyAnchor(const QCString &fName,const QCString &,
const QCString &anchor, const QCString &,
const QCString &)
{
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
bool usePDFLatex = Config_getBool(USE_PDFLATEX);
if (m_insideTableEnv) m_t << "\\mbox{"; // see issue #6093
if (usePDFLatex && pdfHyperlinks)
{
m_t << "\\Hypertarget{";
if (!fName.isEmpty()) m_t << stripPath(fName);
if (!anchor.isEmpty()) m_t << "_" << anchor;
m_t << "}";
}
}
void LatexGenerator::endDoxyAnchor(const QCString &/* fName */,const QCString &/* anchor */)
{
}
void LatexGenerator::addLabel(const QCString &fName, const QCString &anchor)
{
m_t << "\\label{";
if (!fName.isEmpty()) m_t << stripPath(fName);
if (!anchor.isEmpty()) m_t << "_" << anchor;
if (m_insideTableEnv) m_t << "}";
m_t << "} \n";
}
void LatexGenerator::writeAnchor(const QCString &fName,const QCString &name)
{
//printf("LatexGenerator::writeAnchor(%s,%s)\n",fName,name);
m_t << "\\label{" << stripPath(name) << "}\n";
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
bool usePDFLatex = Config_getBool(USE_PDFLATEX);
if (usePDFLatex && pdfHyperlinks)
{
if (!fName.isEmpty())
{
m_t << "\\Hypertarget{" << stripPath(fName) << "_" << stripPath(name) << "}\n";
}
else
{
m_t << "\\Hypertarget{" << stripPath(name) << "}\n";
}
}
}
//void LatexGenerator::writeLatexLabel(const QCString &clName,const QCString &anchor)
//{
// writeDoxyAnchor(0,clName,anchor,0);
//}
void LatexGenerator::addIndexItem(const QCString &s1,const QCString &s2)
{
if (!s1.isEmpty())
{
m_t << "\\index{";
m_t << latexEscapeLabelName(s1);
m_t << "@{";
m_t << latexEscapeIndexChars(s1);
m_t << "}";
if (!s2.isEmpty())
{
m_t << "!";
m_t << latexEscapeLabelName(s2);
m_t << "@{";
m_t << latexEscapeIndexChars(s2);
m_t << "}";
}
m_t << "}";
}
}
void LatexGenerator::startSection(const QCString &lab,const QCString &,SectionType type)
{
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
bool usePDFLatex = Config_getBool(USE_PDFLATEX);
if (usePDFLatex && pdfHyperlinks)
{
m_t << "\\hypertarget{" << stripPath(lab) << "}{}";
}
m_t << "\\";
if (Config_getBool(COMPACT_LATEX))
{
switch(type.level())
{
case SectionType::Page: m_t << "doxysubsection"; break;
case SectionType::Section: m_t << "doxysubsubsection"; break;
case SectionType::Subsection: m_t << "doxysubsubsubsection"; break;
case SectionType::Subsubsection: m_t << "doxysubsubsubsubsection"; break;
case SectionType::Paragraph: m_t << "doxysubsubsubsubsubsection"; break;
case SectionType::Subparagraph: m_t << "doxysubsubsubsubsubsubsection"; break;
case SectionType::Subsubparagraph: m_t << "doxysubsubsubsubsubsubsection"; break;
default: ASSERT(0); break;
}
m_t << "{";
}
else
{
switch(type.level())
{
case SectionType::Page: m_t << "doxysection"; break;
case SectionType::Section: m_t << "doxysubsection"; break;
case SectionType::Subsection: m_t << "doxysubsubsection"; break;
case SectionType::Subsubsection: m_t << "doxysubsubsubsection"; break;
case SectionType::Paragraph: m_t << "doxysubsubsubsubsection"; break;
case SectionType::Subparagraph: m_t << "doxysubsubsubsubsubsection"; break;
case SectionType::Subsubparagraph: m_t << "doxysubsubsubsubsubsubsection"; break;
default: ASSERT(0); break;
}
m_t << "{";
}
}
void LatexGenerator::endSection(const QCString &lab,SectionType)
{
m_t << "}\\label{" << lab << "}\n";
}
void LatexGenerator::docify(const QCString &str)
{
filterLatexString(m_t,str,
m_codeGen->insideTabbing(), // insideTabbing
false, // insidePre
false, // insideItem
m_codeGen->usedTableLevel()>0, // insideTable
false // keepSpaces
);
}
void LatexGenerator::writeChar(char c)
{
char cs[2];
cs[0]=c;
cs[1]=0;
docify(cs);
}
void LatexGenerator::startClassDiagram()
{
//if (Config_getBool(COMPACT_LATEX)) m_t << "\\doxysubsubsection"; else m_t << "\\doxysubsection";
//m_t << "{";
}
void LatexGenerator::endClassDiagram(const ClassDiagram &d,
const QCString &fileName,const QCString &)
{
d.writeFigure(m_t,dir(),fileName);
}
void LatexGenerator::startAnonTypeScope(int indent)
{
if (indent==0)
{
m_t << "\\begin{tabbing}\n";
m_t << "xx\\=xx\\=xx\\=xx\\=xx\\=xx\\=xx\\=xx\\=xx\\=\\kill\n";
m_codeGen->setInsideTabbing(true);
}
m_indent=indent;
}
void LatexGenerator::endAnonTypeScope(int indent)
{
if (indent==0)
{
m_t << "\n" << "\\end{tabbing}";
m_codeGen->setInsideTabbing(false);
}
m_indent=indent;
}
void LatexGenerator::startMemberTemplateParams()
{
if (m_templateMemberItem)
{
m_t << "{\\footnotesize ";
}
}
void LatexGenerator::endMemberTemplateParams(const QCString &,const QCString &)
{
if (m_templateMemberItem)
{
m_t << "}\\\\";
}
}
void LatexGenerator::startMemberItem(const QCString &,MemberItemType type,const QCString &)
{
//printf("LatexGenerator::startMemberItem(%d)\n",annType);
if (!m_codeGen->insideTabbing())
{
m_t << "\\item \n";
m_templateMemberItem = (type == MemberItemType::Templated);
}
}
void LatexGenerator::endMemberItem(MemberItemType)
{
if (m_codeGen->insideTabbing())
{
m_t << "\\\\";
}
m_templateMemberItem = FALSE;
m_t << "\n";
}
void LatexGenerator::startMemberDescription(const QCString &,const QCString &,bool)
{
if (!m_codeGen->insideTabbing())
{
m_t << "\\begin{DoxyCompactList}\\small\\item\\em ";
}
else
{
for (int i=0;i<m_indent+2;i++) m_t << "\\>";
m_t << "{\\em ";
}
}
void LatexGenerator::endMemberDescription()
{
if (!m_codeGen->insideTabbing())
{
//m_t << "\\item\\end{DoxyCompactList}";
m_t << "\\end{DoxyCompactList}";
}
else
{
m_t << "}\\\\\n";
}
}
void LatexGenerator::writeNonBreakableSpace(int)
{
//printf("writeNonBreakableSpace()\n");
if (m_codeGen->insideTabbing())
{
m_t << "\\>";
}
else
{
m_t << "~";
}
}
// ----------------------------------------------
// nesting of functions below:
// startDescTable()
// - startDescTableRow()
// - startDescTableTitle()
// - endDescTableTitle()
// - startDescTableData()
// - endDescTableData()
// - endDescTableRow()
// - startDescTableRow()
// - ...
// - endDescTableRow()
// endDescTable()
void LatexGenerator::startDescTable(const QCString &title,const bool hasInits)
{
m_codeGen->incUsedTableLevel();
m_t << "\\begin{DoxyEnumFields}[" << (hasInits?3:2) << "]{" << title << "}\n";
}
void LatexGenerator::endDescTable()
{
m_codeGen->decUsedTableLevel();
m_t << "\\end{DoxyEnumFields}\n";
}
void LatexGenerator::startDescTableRow()
{
// this is needed to prevent the \hypertarget, \label, and \index commands from messing up
// the row height (based on http://tex.stackexchange.com/a/186102)
m_t << "\\raisebox{\\heightof{T}}[0pt][0pt]{";
}
void LatexGenerator::endDescTableRow()
{
}
void LatexGenerator::startDescTableTitle()
{
m_t << "}";
}
void LatexGenerator::endDescTableTitle()
{
}
void LatexGenerator::startDescTableInit()
{
m_t << "&";
}
void LatexGenerator::endDescTableInit()
{
}
void LatexGenerator::startDescTableData()
{
m_t << "&";
}
void LatexGenerator::endDescTableData()
{
m_t << "\\\\\n\\hline\n\n";
}
void LatexGenerator::lastIndexPage()
{
}
void LatexGenerator::startMemberList()
{
if (!m_codeGen->insideTabbing())
{
m_t << "\\begin{DoxyCompactItemize}\n";
}
}
void LatexGenerator::endMemberList()
{
//printf("LatexGenerator::endMemberList(%d)\n",m_codeGen->InsideTabbing());
if (!m_codeGen->insideTabbing())
{
m_t << "\\end{DoxyCompactItemize}\n";
}
}
void LatexGenerator::startMemberGroupHeader(bool hasHeader)
{
if (hasHeader) m_t << "\\begin{Indent}";
m_t << "\\textbf{ ";
// changed back to rev 756 due to bug 660501
//if (Config_getBool(COMPACT_LATEX))
//{
// m_t << "\\doxysubparagraph*{";
//}
//else
//{
// m_t << "\\doxyparagraph*{";
//}
}
void LatexGenerator::endMemberGroupHeader()
{
// changed back to rev 756 due to bug 660501
m_t << "}\\par\n";
//m_t << "}\n";
}
void LatexGenerator::startMemberGroupDocs()
{
m_t << "{\\em ";
}
void LatexGenerator::endMemberGroupDocs()
{
m_t << "}";
}
void LatexGenerator::startMemberGroup()
{
}
void LatexGenerator::endMemberGroup(bool hasHeader)
{
if (hasHeader)m_t << "\\end{Indent}";
m_t << "\n";
}
void LatexGenerator::startDotGraph()
{
m_t << "\n" << "\n";
}
void LatexGenerator::endDotGraph(DotClassGraph &g)
{
g.writeGraph(m_t,GraphOutputFormat::EPS,EmbeddedOutputFormat::LaTeX,dir(),fileName(),m_relPath);
}
void LatexGenerator::startInclDepGraph()
{
}
void LatexGenerator::endInclDepGraph(DotInclDepGraph &g)
{
g.writeGraph(m_t,GraphOutputFormat::EPS,EmbeddedOutputFormat::LaTeX,dir(),fileName(),m_relPath);
}
void LatexGenerator::startGroupCollaboration()
{
}
void LatexGenerator::endGroupCollaboration(DotGroupCollaboration &g)
{
g.writeGraph(m_t,GraphOutputFormat::EPS,EmbeddedOutputFormat::LaTeX,dir(),fileName(),m_relPath);
}
void LatexGenerator::startCallGraph()
{
}
void LatexGenerator::endCallGraph(DotCallGraph &g)
{
g.writeGraph(m_t,GraphOutputFormat::EPS,EmbeddedOutputFormat::LaTeX,dir(),fileName(),m_relPath);
}
void LatexGenerator::startDirDepGraph()
{
}
void LatexGenerator::endDirDepGraph(DotDirDeps &g)
{
g.writeGraph(m_t,GraphOutputFormat::EPS,EmbeddedOutputFormat::LaTeX,dir(),fileName(),m_relPath);
}
void LatexGenerator::startExamples()
{
m_t << "\\begin{Desc}\n\\item[";
docify(theTranslator->trExamples());
m_t << "]";
}
void LatexGenerator::endExamples()
{
m_t << "\\end{Desc}\n";
}
void LatexGenerator::startParameterList(bool openBracket)
{
/* start of ParameterType ParameterName list */
if (openBracket) m_t << "(";
m_t << "\\begin{DoxyParamCaption}";
}
void LatexGenerator::endParameterList()
{
}
void LatexGenerator::startParameterType(bool first,const QCString &key)
{
m_t << "\\item[{";
if (!first && !key.isEmpty()) docify(key);
}
void LatexGenerator::endParameterType()
{
m_t << "}]";
}
void LatexGenerator::startParameterName(bool /*oneArgOnly*/)
{
m_t << "{";
}
void LatexGenerator::endParameterName()
{
m_t << "}";
}
void LatexGenerator::startParameterExtra()
{
m_t << "{";
}
void LatexGenerator::endParameterExtra(bool last,bool /*emptyList*/,bool closeBracket)
{
m_t << "}";
if (last)
{
m_t << "\\end{DoxyParamCaption}";
if (closeBracket) m_t << ")";
}
}
void LatexGenerator::exceptionEntry(const QCString &prefix,bool closeBracket)
{
if (!prefix.isEmpty())
{
m_t << " " << prefix << "(";
}
else if (closeBracket)
{
m_t << ")";
}
m_t << " ";
}
void LatexGenerator::writeDoc(const IDocNodeAST *ast,const Definition *ctx,const MemberDef *,int)
{
const DocNodeAST *astImpl = dynamic_cast<const DocNodeAST*>(ast);
if (astImpl)
{
LatexDocVisitor visitor(m_t,*m_codeList,*m_codeGen,
ctx?ctx->getDefFileExtension():QCString(""),
m_hierarchyLevel);
std::visit(visitor,astImpl->root);
}
}
void LatexGenerator::startConstraintList(const QCString &header)
{
m_t << "\\begin{Desc}\n\\item[";
docify(header);
m_t << "]";
m_t << "\\begin{description}\n";
}
void LatexGenerator::startConstraintParam()
{
m_t << "\\item[{\\em ";
}
void LatexGenerator::endConstraintParam()
{
}
void LatexGenerator::startConstraintType()
{
m_t << "} : {\\em ";
}
void LatexGenerator::endConstraintType()
{
m_t << "}]";
}
void LatexGenerator::startConstraintDocs()
{
}
void LatexGenerator::endConstraintDocs()
{
}
void LatexGenerator::endConstraintList()
{
m_t << "\\end{description}\n";
m_t << "\\end{Desc}\n";
}
void LatexGenerator::startInlineHeader()
{
if (Config_getBool(COMPACT_LATEX))
{
m_t << "\\doxyparagraph*{";
}
else
{
m_t << "\\doxy" << QCString("sub").repeat(m_hierarchyLevel + 1) << "section*{";
}
}
void LatexGenerator::endInlineHeader()
{
m_t << "}\n";
}
void LatexGenerator::lineBreak(const QCString &)
{
if (m_codeGen->insideTabbing())
{
m_t << "\\\\\n";
}
else
{
m_t << "\\newline\n";
}
}
void LatexGenerator::startMemberDocSimple(bool isEnum)
{
m_codeGen->incUsedTableLevel();
if (isEnum)
{
m_t << "\\begin{DoxyEnumFields}{";
docify(theTranslator->trEnumerationValues());
}
else
{
m_t << "\\begin{DoxyFields}{";
docify(theTranslator->trCompoundMembers());
}
m_t << "}\n";
m_insideTableEnv=true;
}
void LatexGenerator::endMemberDocSimple(bool isEnum)
{
m_insideTableEnv=false;
m_codeGen->decUsedTableLevel();
if (isEnum)
{
m_t << "\\end{DoxyEnumFields}\n";
}
else
{
m_t << "\\end{DoxyFields}\n";
}
}
void LatexGenerator::startInlineMemberType()
{
m_codeGen->setInsideTabbing(true); // to prevent \+ from causing unwanted breaks
}
void LatexGenerator::endInlineMemberType()
{
m_t << "&\n";
m_codeGen->setInsideTabbing(false);
}
void LatexGenerator::startInlineMemberName()
{
m_codeGen->setInsideTabbing(true); // to prevent \+ from causing unwanted breaks
}
void LatexGenerator::endInlineMemberName()
{
m_t << "&\n";
m_codeGen->setInsideTabbing(false);
}
void LatexGenerator::startInlineMemberDoc()
{
}
void LatexGenerator::endInlineMemberDoc()
{
m_t << "\\\\\n\\hline\n\n";
}
void LatexGenerator::startLabels()
{
m_t << "\\hspace{0.3cm}";
}
void LatexGenerator::writeLabel(const QCString &l,bool isLast)
{
m_t << "{\\ttfamily [" << l << "]}";
if (!isLast) m_t << ", ";
}
void LatexGenerator::endLabels()
{
}
void LatexGenerator::writeInheritedSectionTitle(
const QCString &/*id*/,const QCString &ref,
const QCString &file, const QCString &anchor,
const QCString &title, const QCString &name)
{
if (Config_getBool(COMPACT_LATEX))
{
m_t << "\\doxyparagraph*{";
}
else
{
m_t << "\\doxy" << QCString("sub").repeat(m_hierarchyLevel + 1) << "section*{";
}
m_t << theTranslator->trInheritedFrom(convertToLaTeX(title,m_codeGen->insideTabbing()),
objectLinkToString(ref, file, anchor, name, m_codeGen->insideTabbing(), m_disableLinks));
m_t << "}\n";
}
void LatexGenerator::writeLocalToc(const SectionRefs &,const LocalToc &localToc)
{
if (localToc.isLatexEnabled())
{
int maxLevel = localToc.latexLevel() + m_hierarchyLevel;
m_t << "\\etocsetnexttocdepth{" << maxLevel << "}\n";
m_t << "\\localtableofcontents\n";
}
}
//--------------------------------------------------------------------------------------------------
void writeExtraLatexPackages(TextStream &t)
{
// User-specified packages
const StringVector &extraPackages = Config_getList(EXTRA_PACKAGES);
if (!extraPackages.empty())
{
t << "% Packages requested by user\n";
for (const auto &pkgName : extraPackages)
{
if ((pkgName[0] == '[') || (pkgName[0] == '{'))
t << "\\usepackage" << pkgName.c_str() << "\n";
else
t << "\\usepackage{" << pkgName.c_str() << "}\n";
}
t << "\n";
}
}
void writeLatexSpecialFormulaChars(TextStream &t)
{
unsigned char minus[4]; // Superscript minus
unsigned char sup2[3]; // Superscript two
unsigned char sup3[3];
minus[0]= 0xE2;
minus[1]= 0x81;
minus[2]= 0xBB;
minus[3]= 0;
sup2[0]= 0xC2;
sup2[1]= 0xB2;
sup2[2]= 0;
sup3[0]= 0xC2;
sup3[1]= 0xB3;
sup3[2]= 0;
t << "\\ifPDFTeX\n";
t << "\\usepackage{newunicodechar}\n";
// taken from the newunicodechar package and removed the warning message
// actually forcing to redefine the unicode character
t << " \\makeatletter\n"
" \\def\\doxynewunicodechar#1#2{%\n"
" \\@tempswafalse\n"
" \\edef\\nuc@tempa{\\detokenize{#1}}%\n"
" \\if\\relax\\nuc@tempa\\relax\n"
" \\nuc@emptyargerr\n"
" \\else\n"
" \\edef\\@tempb{\\expandafter\\@car\\nuc@tempa\\@nil}%\n"
" \\nuc@check\n"
" \\if@tempswa\n"
" \\@namedef{u8:\\nuc@tempa}{#2}%\n"
" \\fi\n"
" \\fi\n"
" }\n"
" \\makeatother\n";
t << " \\doxynewunicodechar{" << minus << "}{${}^{-}$}% Superscript minus\n"
" \\doxynewunicodechar{" << sup2 << "}{${}^{2}$}% Superscript two\n"
" \\doxynewunicodechar{" << sup3 << "}{${}^{3}$}% Superscript three\n"
"\n";
t << "\\fi\n";
}
void filterLatexString(TextStream &t,const QCString &str,
bool insideTabbing,bool insidePre,bool insideItem,bool insideTable,bool keepSpaces, const bool retainNewline)
{
if (str.isEmpty()) return;
bool pdfHyperlinks = Config_getBool(PDF_HYPERLINKS);
//printf("filterLatexString(%s) insideTabbing=%d\n",qPrint(str),insideTabbing);
const char *p = str.data();
const char *q = nullptr;
unsigned char pc='\0';
while (*p)
{
unsigned char c=static_cast<unsigned char>(*p++);
if (insidePre)
{
switch(c)
{
case 0xef: // handle U+FFFD i.e. "Replacement character" caused by octal: 357 277 275 / hexadecimal 0xef 0xbf 0xbd
// the LaTeX command \ucr has been defined in doxygen.sty
if (static_cast<unsigned char>(*(p)) == 0xbf && static_cast<unsigned char>(*(p+1)) == 0xbd)
{
t << "{\\ucr}";
p += 2;
}
else
t << static_cast<char>(c);
break;
case '\\': t << "\\(\\backslash\\)"; break;
case '{': t << "\\{"; break;
case '}': t << "\\}"; break;
case '_': t << "\\_"; break;
case '&': t << "\\&"; break;
case '%': t << "\\%"; break;
case '#': t << "\\#"; break;
case '$': t << "\\$"; break;
case '"': t << "\"{}"; break;
case '-': t << "-\\/"; break;
case '^': insideTable ? t << "\\string^" : t << static_cast<char>(c); break;
case '~': t << "\\string~"; break;
case '\n': if (retainNewline) t << "\\newline"; else t << ' ';
break;
case ' ': if (keepSpaces) t << "~"; else t << ' ';
break;
default:
if (c<32) t << ' '; // non printable control character
else t << static_cast<char>(c);
break;
}
}
else
{
switch(c)
{
case 0xef: // handle U+FFFD i.e. "Replacement character" caused by octal: 357 277 275 / hexadecimal 0xef 0xbf 0xbd
// the LaTeX command \ucr has been defined in doxygen.sty
if (static_cast<unsigned char>(*(p)) == 0xbf && static_cast<unsigned char>(*(p+1)) == 0xbd)
{
t << "{\\ucr}";
p += 2;
}
else
t << static_cast<char>(c);
break;
case '#': t << "\\#"; break;
case '$': t << "\\$"; break;
case '%': t << "\\%"; break;
case '^': processEntity(t,pdfHyperlinks,"$^\\wedge$","\\string^"); break;
case '&': {
// possibility to have a special symbol
q = p;
int cnt = 2; // we have to count & and ; as well
while ((*q >= 'a' && *q <= 'z') || (*q >= 'A' && *q <= 'Z') || (*q >= '0' && *q <= '9'))
{
cnt++;
q++;
}
if (*q == ';')
{
--p; // we need & as well
HtmlEntityMapper::SymType res = HtmlEntityMapper::instance().name2sym(QCString(p).left(cnt));
if (res == HtmlEntityMapper::Sym_Unknown)
{
p++;
t << "\\&";
}
else
{
t << HtmlEntityMapper::instance().latex(res);
q++;
p = q;
}
}
else
{
t << "\\&";
}
}
break;
case '*': processEntity(t,pdfHyperlinks,"$\\ast$","*"); break;
case '_': if (!insideTabbing) t << "\\+";
t << "\\_";
if (!insideTabbing) t << "\\+";
break;
case '{': t << "\\{"; break;
case '}': t << "\\}"; break;
case '<': t << "$<$"; break;
case '>': t << "$>$"; break;
case '|': processEntity(t,pdfHyperlinks,"$\\vert$","|"); break;
case '~': processEntity(t,pdfHyperlinks,"$\\sim$","\\string~"); break;
case '[': if (Config_getBool(PDF_HYPERLINKS) || insideItem)
t << "\\mbox{[}";
else
t << "[";
break;
case ']': if (pc=='[') t << "$\\,$";
if (Config_getBool(PDF_HYPERLINKS) || insideItem)
t << "\\mbox{]}";
else
t << "]";
break;
case '-': t << "-\\/";
break;
case '\\': t << "\\textbackslash{}";
break;
case '"': t << "\"{}";
break;
case '`': t << "\\`{}";
break;
case '\'': t << "\\textquotesingle{}";
break;
case '\n': if (retainNewline) t << "\\newline"; else t << ' ';
break;
case ' ': if (keepSpaces) { if (insideTabbing) t << "\\>"; else t << '~'; } else t << ' ';
break;
default:
//if (!insideTabbing && forceBreaks && c!=' ' && *p!=' ')
if (!insideTabbing &&
((c>='A' && c<='Z' && pc!=' ' && !(pc>='A' && pc <= 'Z') && pc!='\0' && *p) || (c==':' && pc!=':') || (pc=='.' && isId(c)))
)
{
t << "\\+";
}
if (c<32)
{
t << ' '; // non-printable control character
}
else
{
t << static_cast<char>(c);
}
}
}
pc = c;
}
}
QCString convertToLaTeX(const QCString &s,bool insideTabbing,bool keepSpaces)
{
TextStream t;
filterLatexString(t,s,insideTabbing,false,false,false,keepSpaces);
return t.str();
}
QCString latexEscapeLabelName(const QCString &s)
{
//printf("latexEscapeLabelName(%s)\n",qPrint(s));
if (s.isEmpty()) return s;
QCString tmp(s.length(), QCString::ExplicitSize);
TextStream t;
const char *p=s.data();
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '|': t << "\\texttt{\"|}"; break;
case '!': t << "\"!"; break;
case '@': t << "\"@"; break;
case '%': t << "\\%"; break;
case '{': t << "\\lcurly{}"; break;
case '}': t << "\\rcurly{}"; break;
case '~': t << "````~"; break; // to get it a bit better in index together with other special characters
// NOTE: adding a case here, means adding it to while below as well!
default:
{
int i=0;
// collect as long string as possible, before handing it to docify
tmp[i++]=c;
while ((c=*p) && c!='@' && c!='[' && c!=']' && c!='!' && c!='{' && c!='}' && c!='|')
{
tmp[i++]=c;
p++;
}
tmp[i]=0;
filterLatexString(t,tmp,
true, // insideTabbing
false, // insidePre
false, // insideItem
false, // insideTable
false // keepSpaces
);
}
break;
}
}
return t.str();
}
QCString latexEscapeIndexChars(const QCString &s)
{
//printf("latexEscapeIndexChars(%s)\n",qPrint(s));
if (s.isEmpty()) return s;
QCString tmp(s.length(), QCString::ExplicitSize);
TextStream t;
const char *p=s.data();
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '!': t << "\"!"; break;
case '"': t << "\"\""; break;
case '@': t << "\"@"; break;
case '|': t << "\\texttt{\"|}"; break;
case '[': t << "["; break;
case ']': t << "]"; break;
case '{': t << "\\lcurly{}"; break;
case '}': t << "\\rcurly{}"; break;
// NOTE: adding a case here, means adding it to while below as well!
default:
{
int i=0;
// collect as long string as possible, before handing it to docify
tmp[i++]=c;
while ((c=*p) && c!='"' && c!='@' && c!='[' && c!=']' && c!='!' && c!='{' && c!='}' && c!='|')
{
tmp[i++]=c;
p++;
}
tmp[i]=0;
filterLatexString(t,tmp,
true, // insideTabbing
false, // insidePre
false, // insideItem
false, // insideTable
false // keepSpaces
);
}
break;
}
}
return t.str();
}
QCString latexEscapePDFString(const QCString &s)
{
if (s.isEmpty()) return s;
TextStream t;
const char *p=s.data();
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '\\': t << "\\textbackslash{}"; break;
case '{': t << "\\{"; break;
case '}': t << "\\}"; break;
case '_': t << "\\_"; break;
case '%': t << "\\%"; break;
case '&': t << "\\&"; break;
case '#': t << "\\#"; break;
case '$': t << "\\$"; break;
case '^': t << "\\string^"; break;
case '~': t << "\\string~"; break;
default:
t << c;
break;
}
}
return t.str();
}
QCString latexFilterURL(const QCString &s)
{
constexpr auto hex = "0123456789ABCDEF";
if (s.isEmpty()) return s;
TextStream t;
const char *p=s.data();
char c = 0;
while ((c=*p++))
{
switch (c)
{
case '#': t << "\\#"; break;
case '%': t << "\\%"; break;
case '\\': t << "\\\\"; break;
default:
if (c<0)
{
unsigned char id = static_cast<unsigned char>(c);
t << "\\%" << hex[id>>4] << hex[id&0xF];
}
else
{
t << c;
}
break;
}
}
return t.str();
}
| 77,778
|
C++
|
.cpp
| 2,481
| 25.19871
| 169
| 0.546937
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,438
|
aliases.cpp
|
doxygen_doxygen/src/aliases.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 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.
*
*/
#include <unordered_map>
#include <cassert>
#include "message.h"
#include "aliases.h"
#include "containers.h"
#include "config.h"
#include "regex.h"
#include "textstream.h"
#include "util.h"
#include "debug.h"
#include "stringutil.h"
//-----------------------------------------------------------
struct AliasInfo
{
AliasInfo(const std::string &val,const std::string &sep=std::string())
: value(val), separator(sep) {}
std::string value;
std::string separator;
};
using AliasOverloads = std::unordered_map<int,AliasInfo>; // key = parameter count
using AliasInfoMap = std::unordered_map<std::string,AliasOverloads>; // key = alias name (with parameter part)
//-----------------------------------------------------------
static std::string expandAliasRec(StringUnorderedSet &aliasesProcessed,
std::string_view s,bool allowRecursion=FALSE);
static int countAliasArguments(std::string_view args, std::string_view sep);
static std::string extractAliasArgs(std::string_view args);
static std::string expandAlias(std::string_view aliasName,std::string_view aliasValue);
//-----------------------------------------------------------
static AliasInfoMap g_aliasInfoMap;
//-----------------------------------------------------------
static void addValidAliasToMap(std::string_view alias)
{
bool valid = true;
std::string aliasName;
std::string aliasValue;
int numParams = 0;
std::string separator;
static std::string_view separators = "!#$%&,.?|;:'+=~`/";
auto isValidSeparator = [](char c) -> bool { return separators.find(c)!=std::string::npos; };
static const reg::Ex re1(R"(^\a[\w-]*\s*=)");
static const reg::Ex re2(R"(^\a[\w-]*{[^}]*}\s*=)");
if (reg::search(std::string{alias},re1) || reg::search(std::string{alias},re2)) // valid name= or name{...}= part
{
size_t i=alias.find('=');
assert(i!=std::string::npos); // based on re1 and re2 there is always a =
std::string name{ stripWhiteSpace(alias.substr(0,i)) };
aliasValue = alias.substr(i+1);
//printf("Alias: found name='%s' value='%s'\n",qPrint(name),qPrint(aliasValue));
size_t l = name.length();
size_t j = name.find('{');
if (j!=std::string::npos) // alias with parameters
{
if (name[l-1]=='}')
{
separator=",";
size_t k=j+1;
while (k<l-1 && isdigit(name[k])) k++;
numParams = atoi(name.substr(j+1,k-j-1).c_str());
if (numParams>0)
{
if (k<l-1) // we have a separator
{
size_t m=k;
while (m<l && isValidSeparator(name[m])) m++;
if (m<l-1)
{
err("Invalid alias '%s': invalid separator character '%c' (code %d), allowed characters: %s. Check your config file.\n",qPrint(alias),name[m],name[m],qPrint(std::string{separators}));
valid=false;
}
else
{
separator=name.substr(k,l-k-1);
}
}
if (valid) // valid alias with parameters
{
aliasName = name.substr(0,j);
Debug::print(Debug::Alias,0,"Alias definition: name='%s' #param='%d' separator='%s' value='%s'\n",
qPrint(aliasName),numParams,qPrint(separator),qPrint(aliasValue));
}
}
else
{
err("Invalid alias '%s': missing number of parameters. Check your config file.\n",qPrint(std::string{alias}));
valid=false;
}
}
else
{
err("Invalid alias '%s': missing closing bracket. Check your config file.\n",qPrint(std::string{alias}));
valid=false;
}
}
else // valid alias without parameters
{
aliasName = name;
numParams = 0;
Debug::print(Debug::Alias,0,"Alias definition: name='%s' value='%s'\n",qPrint(aliasName),qPrint(aliasValue));
}
}
else
{
err("Invalid alias '%s': invalid 'name=' or 'name{...}=' part. Check you config file.\n",qPrint(std::string{alias}));
valid=false;
}
if (valid) // alias definition passed all checks, so store it.
{
auto it = g_aliasInfoMap.find(aliasName);
if (it==g_aliasInfoMap.end()) // insert new alias
{
AliasOverloads overloads { { numParams, AliasInfo(aliasValue, separator) } };
g_aliasInfoMap.emplace(aliasName,overloads);
}
else // replace exiting alias with new definition
{
auto it2 = it->second.find(numParams);
if (it2==it->second.end()) // new alias overload for the given number of parameters
{
it->second.emplace(numParams, AliasInfo(aliasValue,separator));
}
else // replace alias with new definition
{
it2->second = AliasInfo(aliasValue,separator);
}
}
}
}
//----------------------------------------------------------------------------
static std::string escapeAlias(std::string_view value)
{
std::string newValue = substituteStringView(value,"^^ ","@ilinebr ");
newValue = substituteStringView(newValue,"^^","@ilinebr ");
//printf("escapeAlias('%s')='%s'\n",qPrint(std::string{value}),qPrint(newValue));
return newValue;
}
//----------------------------------------------------------------------------
void readAliases()
{
// add aliases to a dictionary
const StringVector &aliasList = Config_getList(ALIASES);
for (const auto &al : aliasList)
{
addValidAliasToMap(al);
}
for (auto &[name,overloads] : g_aliasInfoMap)
{
for (auto &[numParams,aliasInfo] : overloads)
{
aliasInfo.value = expandAlias(name+":"+std::to_string(numParams),aliasInfo.value);
}
}
for (auto &[name,overloads] : g_aliasInfoMap)
{
for (auto &[numParams,aliasInfo] : overloads)
{
aliasInfo.value = escapeAlias(aliasInfo.value);
}
}
}
//--------------------------------------------------------------------------------------
struct Marker
{
Marker(size_t p, size_t n,size_t s) : pos(p), number(n), size(s) {}
size_t pos; // position in the string
size_t number; // argument number
size_t size; // size of the marker
};
/** For a string \a s that starts with a command name, returns the character
* offset within that string representing the first character after the
* command. For an alias with argument, this is the offset to the
* character just after the argument list.
*
* Examples:
* - s=="a b" returns 1
* - s=="a{2,3} b" returns 6
* = s=="#" returns 0
*/
static size_t findEndOfCommand(std::string_view s)
{
char c=' ';
size_t i=0;
if (!s.empty())
{
while (i<s.length() && (c=s[i]) && isId(c)) i++;
if (c=='{') i+=extractAliasArgs(s.substr(i)).length()+2; // +2 for '{' and '}'
}
return i;
}
/** Replaces the markers in an alias definition \a aliasValue
* with the corresponding values found in the comma separated argument
* list \a argList and the returns the result after recursive alias expansion.
*/
static std::string replaceAliasArguments(StringUnorderedSet &aliasesProcessed,
std::string_view aliasValue,std::string_view argList,
std::string_view sep)
{
//printf("----- replaceAliasArguments(val=[%s],args=[%s],sep=[%s])\n",qPrint(aliasValue),qPrint(argList),qPrint(sep));
// first make a list of arguments from the comma separated argument list
StringViewVector args;
size_t l=argList.length();
size_t p=0;
for (size_t i=0;i<l;i++)
{
char c = argList[i];
if (!sep.empty() &&
c==sep[0] && // start with separator character
(i==0 || argList[i-1]!='\\') && // is not escaped
argList.substr(i,sep.length())==sep) // whole separator matches
{
args.push_back(argList.substr(p,i-p));
p = i+sep.length(); // start of next argument
i = p-1; // compensate with -1 for loop iterator
}
else if (c=='@' || c=='\\') // command
{
// check if this is the start of another aliased command (see bug704172)
i+=findEndOfCommand(argList.substr(i+1));
}
}
if (l>p) args.push_back(argList.substr(p));
//printf("found %zu arguments\n",args.size());
// next we look for the positions of the markers and add them to a list
std::vector<Marker> markerList;
l = aliasValue.length();
char pc = '\0';
bool insideMarkerId = false;
size_t markerStart = 0;
auto isDigit = [](char c) { return c>='0' && c<='9'; };
for (size_t i=0;i<=l;i++)
{
char c = i<l ? aliasValue[i] : '\0';
if (insideMarkerId && !isDigit(c)) // found end of a markerId
{
insideMarkerId = false;
size_t markerLen = i-markerStart;
markerList.emplace_back(markerStart-1,
static_cast<size_t>(std::stoi(std::string{aliasValue.substr(markerStart,markerLen)})),
markerLen+1);
}
if (c=='\\' && (pc=='@' || pc=='\\')) // found escaped backslash
{
// skip
pc = '\0';
}
else
{
if (isDigit(c) && pc=='\\') // found start of a markerId
{
insideMarkerId=true;
markerStart=i;
}
pc = c;
}
}
// then we replace the markers with the corresponding arguments in one pass
std::string result;
p = 0;
for (const Marker &m : markerList)
{
result+=aliasValue.substr(p,m.pos-p);
//printf("part before marker: '%s'\n",qPrint(aliasValue.substr(p,m.pos-p)));
if (m.number>0 && m.number<=args.size()) // valid number
{
result+=expandAliasRec(aliasesProcessed,args[m.number-1],true);
//printf("marker index=%zu pos=%zu number=%zu size=%zu replacement %s\n",i,m.pos,m.number,m.size,
// qPrint(args[m.number-1]));
}
p=m.pos+m.size; // continue after the marker
}
result+=aliasValue.substr(p); // append remainder
//printf("string after replacement of markers: '%s'\n",qPrint(result));
// expand the result again
substituteInplace(result,"\\{","{");
substituteInplace(result,"\\}","}");
substituteInplace(result,std::string{"\\"}+std::string{sep},sep);
result = expandAliasRec(aliasesProcessed,result);
//printf("final string '%s'\n",qPrint(result));
return result;
}
static std::string escapeSeparators(const std::string &s, const std::string &sep)
{
if (s.empty() || sep.empty()) return s;
std::string result;
result.reserve(s.length()+10);
size_t i, p=0, l=sep.length();
while ((i=s.find(sep,p))!=std::string::npos)
{
result += s.substr(p,i-p);
if (i>0 && s[i-1]!='\\') // escape the separator
{
result += '\\';
}
result += s.substr(i,l);
p = i+l;
}
result += s.substr(p);
//printf("escapeSeparators(%s,sep='%s')=%s\n",qPrint(s),qPrint(sep),qPrint(result));
return result;
}
static std::string expandAliasRec(StringUnorderedSet &aliasesProcessed,std::string_view s,bool allowRecursion)
{
std::string result;
static const reg::Ex re(R"([\\@](\a[\w-]*))");
std::string str{s};
reg::Match match;
size_t p = 0;
while (reg::search(str,match,re,p))
{
size_t i = match.position();
size_t l = match.length();
if (i>p) result+=s.substr(p,i-p);
std::string args = extractAliasArgs(s.substr(i+l));
bool hasArgs = !args.empty(); // found directly after command
size_t argsLen = args.length();
std::string cmd = match[1].str();
int selectedNumArgs = -1;
//printf("looking for alias '%s' with params '%s'\n",qPrint(cmd),qPrint(args));
auto it = g_aliasInfoMap.find(cmd);
if (it == g_aliasInfoMap.end())
{
// if command has a - then also try part in without it
size_t minusPos = cmd.find('-');
if (minusPos!=std::string::npos)
{
it = g_aliasInfoMap.find(cmd.substr(0,minusPos));
if (it!=g_aliasInfoMap.end()) // found part before - as alias
{
cmd = cmd.substr(0,minusPos);
args = "";
hasArgs = false;
argsLen = 0;
l = cmd.length()+1; // +1 for the minus sign
}
}
}
if (it != g_aliasInfoMap.end()) // cmd is an alias
{
//printf("found an alias, hasArgs=%d\n",hasArgs);
if (hasArgs)
{
// Find the an alias that matches the number of arguments.
// If there are multiple candidates, take the one that matches the most parameters
for (const auto &[numParams,aliasInfo] : it->second)
{
int numArgs = countAliasArguments(args,aliasInfo.separator);
if (numParams==numArgs && numArgs>selectedNumArgs)
{
selectedNumArgs = numArgs;
}
}
if (selectedNumArgs==-1) // no match found, check if there is an alias with one argument
{
auto it2 = it->second.find(1);
if (it2 != it->second.end())
{
args = escapeSeparators(args,it2->second.separator); // escape separator so that everything is seen as one argument
selectedNumArgs = 1;
}
}
}
else
{
selectedNumArgs = 0;
}
}
else
{
//printf("Alias %s not found\n",qPrint(cmd));
}
//printf("Found command s='%s' cmd='%s' numArgs=%d args='%s'\n", qPrint(s),qPrint(cmd),selectedNumArgs,qPrint(args));
std::string qualifiedName = cmd+":"+std::to_string(selectedNumArgs);
if ((allowRecursion || aliasesProcessed.find(qualifiedName)==aliasesProcessed.end()) &&
it!=g_aliasInfoMap.end() && selectedNumArgs!=-1 &&
it->second.find(selectedNumArgs)!=it->second.end()) // expand the alias
{
const auto &aliasInfo = it->second.find(selectedNumArgs)->second;
//printf("is an alias with separator='%s' selectedNumArgs=%d hasArgs=%d!\n",qPrint(aliasInfo.separator),selectedNumArgs,hasArgs);
if (!allowRecursion) aliasesProcessed.insert(qualifiedName);
std::string val = aliasInfo.value;
if (hasArgs)
{
//printf("before replaceAliasArguments(val='%s')\n",qPrint(val));
val = replaceAliasArguments(aliasesProcessed,val,args,aliasInfo.separator);
//printf("after replaceAliasArguments sep='%s' val='%s' args='%s'\n",
// qPrint(aliasInfo.separator),qPrint(val),qPrint(args));
}
result += expandAliasRec(aliasesProcessed,val);
if (!allowRecursion) aliasesProcessed.erase(qualifiedName);
p = i+l;
if (hasArgs) p += argsLen+2;
}
else // command is not an alias
{
//printf("not an alias!\n");
result += match.str();
p = i+l;
}
}
result += s.substr(p);
//printf("expandAliases \"%s\"->\"%s\"\n",qPrint(s),qPrint(result));
return result;
}
static int countAliasArguments(std::string_view args, std::string_view sep)
{
int count = 1;
size_t l = args.length();
for (size_t i=0;i<l;i++)
{
char c = args[i];
if (!sep.empty() &&
c==sep[0] && // start with separator character
(i==0 || args[i-1]!='\\') && // is not escaped
args.substr(i,sep.length())==sep) // whole separator matches
{
count++;
}
else if (c=='@' || c=='\\')
{
// check if this is the start of another aliased command (see bug704172)
i += findEndOfCommand(args.substr(i+1));
}
}
//printf("countAliasArguments(%s,sep=%s)=%d\n",qPrint(args),qPrint(sep),count);
return count;
}
static std::string extractAliasArgs(std::string_view args)
{
int bc = 0;
char prevChar = 0;
if (!args.empty() && args[0]=='{') // alias has argument
{
for (size_t i=0;i<args.length();i++)
{
char c = args[i];
if (prevChar!='\\') // not escaped
{
if (c=='{') bc++;
if (c=='}') bc--;
prevChar=c;
}
else
{
prevChar=0;
}
if (bc==0)
{
//printf("extractAliasArgs('%s')->'%s'\n",qPrint(args),qPrint(args.substr(1,i-1)));
return std::string{args.substr(1,i-1)};
}
}
}
return std::string{};
}
std::string resolveAliasCmd(std::string_view aliasCmd)
{
StringUnorderedSet aliasesProcessed;
//printf("Expanding: '%s'\n",qPrint(aliasCmd));
std::string result = expandAliasRec(aliasesProcessed,aliasCmd);
//printf("Expanding result: '%s'->'%s'\n",qPrint(aliasCmd),qPrint(result));
Debug::print(Debug::Alias,0,"Resolving alias: cmd='%s' result='%s'\n",qPrint(std::string{aliasCmd}),qPrint(result));
return result;
}
static std::string expandAlias(std::string_view aliasName,std::string_view aliasValue)
{
std::string result;
StringUnorderedSet aliasesProcessed;
// avoid expanding this command recursively
aliasesProcessed.insert(std::string{aliasName});
// expand embedded commands
//printf("Expanding: '%s'->'%s'\n",qPrint(aliasName),qPrint(aliasValue));
result = expandAliasRec(aliasesProcessed,aliasValue);
//printf("Expanding result: '%s'->'%s'\n",qPrint(aliasName),qPrint(result));
Debug::print(Debug::Alias,0,"Expanding alias: input='%s' result='%s'\n",qPrint(std::string{aliasValue}),qPrint(result));
return result;
}
bool isAliasCmd(std::string_view aliasCmd)
{
return g_aliasInfoMap.find(std::string{aliasCmd}) != g_aliasInfoMap.end();
}
| 17,852
|
C++
|
.cpp
| 493
| 30.841785
| 197
| 0.598637
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,439
|
dotcallgraph.cpp
|
doxygen_doxygen/src/dotcallgraph.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2020 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.
*
*/
#include "dotcallgraph.h"
#include "dotnode.h"
#include "memberlist.h"
#include "config.h"
#include "util.h"
static QCString getUniqueId(const MemberDef *md)
{
const MemberDef *def = md->memberDefinition();
if (def==nullptr) def = md;
QCString result = def->getReference()+"$"+
def->getOutputFileBase()+"#"+
def->anchor();
return result;
}
void DotCallGraph::buildGraph(DotNode *n,const MemberDef *md,int distance)
{
auto refs = m_inverse ? md->getReferencedByMembers() : md->getReferencesMembers();
for (const auto &rmd : refs)
{
if (rmd->isCallable())
{
QCString uniqueId = getUniqueId(rmd);
auto it = m_usedNodes.find(uniqueId.str());
if (it!=m_usedNodes.end()) // file is already a node in the graph
{
DotNode *bn = it->second;
n->addChild(bn,EdgeInfo::Blue,EdgeInfo::Solid);
bn->addParent(n);
bn->setDistance(distance);
}
else
{
QCString name;
if (Config_getBool(HIDE_SCOPE_NAMES))
{
name = rmd->getOuterScope()==m_scope ?
rmd->name() : rmd->qualifiedName();
}
else
{
name = rmd->qualifiedName();
}
QCString tooltip = rmd->briefDescriptionAsTooltip();
DotNode *bn = new DotNode(
this,
linkToText(rmd->getLanguage(),name,FALSE),
tooltip,
uniqueId,
0 //distance
);
n->addChild(bn,EdgeInfo::Blue,EdgeInfo::Solid);
bn->addParent(n);
bn->setDistance(distance);
m_usedNodes.emplace(uniqueId.str(),bn);
buildGraph(bn,rmd,distance+1);
}
}
}
}
void DotCallGraph::determineVisibleNodes(DotNodeDeque &queue, int &maxNodes)
{
while (!queue.empty() && maxNodes>0)
{
DotNode *n = queue.front();
queue.pop_front();
if (!n->isVisible() && n->distance()<=Config_getInt(MAX_DOT_GRAPH_DEPTH)) // not yet processed
{
n->markAsVisible();
maxNodes--;
// add direct children
for (const auto &dn : n->children())
{
queue.push_back(dn);
}
}
}
}
void DotCallGraph::determineTruncatedNodes(DotNodeDeque &queue)
{
while (!queue.empty())
{
DotNode *n = queue.front();
queue.pop_front();
if (n->isVisible() && n->isTruncated()==DotNode::Unknown)
{
bool truncated = FALSE;
for (const auto &dn : n->children())
{
if (!dn->isVisible())
truncated = TRUE;
else
queue.push_back(dn);
}
n->markAsTruncated(truncated);
}
}
}
DotCallGraph::DotCallGraph(const MemberDef *md,bool inverse)
{
m_inverse = inverse;
m_diskName = md->getOutputFileBase()+"_"+md->anchor();
m_scope = md->getOuterScope();
QCString uniqueId = getUniqueId(md);
QCString name;
if (Config_getBool(HIDE_SCOPE_NAMES))
{
name = md->name();
}
else
{
name = md->qualifiedName();
}
QCString tooltip = md->briefDescriptionAsTooltip();
m_startNode = new DotNode(this,
linkToText(md->getLanguage(),name,FALSE),
tooltip,
uniqueId,
TRUE // root node
);
m_startNode->setDistance(0);
m_usedNodes.emplace(uniqueId.str(),m_startNode);
buildGraph(m_startNode,md,1);
int maxNodes = Config_getInt(DOT_GRAPH_MAX_NODES);
DotNodeDeque openNodeQueue;
openNodeQueue.push_back(m_startNode);
determineVisibleNodes(openNodeQueue,maxNodes);
openNodeQueue.clear();
openNodeQueue.push_back(m_startNode);
determineTruncatedNodes(openNodeQueue);
}
DotCallGraph::~DotCallGraph()
{
DotNode::deleteNodes(m_startNode);
}
QCString DotCallGraph::getBaseName() const
{
return m_diskName + (m_inverse ? "_icgraph" : "_cgraph");
}
void DotCallGraph::computeTheGraph()
{
computeGraph(
m_startNode,
GraphType::CallGraph,
m_graphFormat,
m_inverse ? "RL" : "LR",
FALSE,
m_inverse,
m_startNode->label(),
m_theGraph);
}
QCString DotCallGraph::getMapLabel() const
{
return m_baseName;
}
QCString DotCallGraph::writeGraph(
TextStream &out,
GraphOutputFormat graphFormat,
EmbeddedOutputFormat textFormat,
const QCString &path,
const QCString &fileName,
const QCString &relPath,bool generateImageMap,
int graphId)
{
m_doNotAddImageToIndex = textFormat!=EmbeddedOutputFormat::Html;
return DotGraph::writeGraph(out, graphFormat, textFormat, path, fileName, relPath, generateImageMap, graphId);
}
bool DotCallGraph::isTrivial() const
{
return m_startNode->children().empty();
}
bool DotCallGraph::isTooBig() const
{
return numNodes()>=Config_getInt(DOT_GRAPH_MAX_NODES);
}
int DotCallGraph::numNodes() const
{
return static_cast<int>(m_startNode->children().size());
}
bool DotCallGraph::isTrivial(const MemberDef *md,bool inverse)
{
auto refs = inverse ? md->getReferencedByMembers() : md->getReferencesMembers();
for (const auto &rmd : refs)
{
if (rmd->isCallable())
{
return FALSE;
}
}
return TRUE;
}
| 5,667
|
C++
|
.cpp
| 204
| 23.20098
| 112
| 0.655337
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,440
|
language.cpp
|
doxygen_doxygen/src/language.cpp
|
/******************************************************************************
*
*
*
* Copyright (C) 1997-2015 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.
*
*/
#include "types.h"
#include "message.h"
#include "config.h"
#include "util.h"
#include "language.h"
#include "translator.h"
#include "translator_en.h"
#include "translator_adapter.h"
#include "translator_nl.h"
#include "translator_am.h"
#include "translator_sv.h"
#include "translator_cz.h"
#include "translator_fr.h"
#include "translator_id.h"
#include "translator_it.h"
#include "translator_de.h"
#include "translator_jp.h"
#include "translator_je.h"
#include "translator_es.h"
#include "translator_eo.h"
#include "translator_fi.h"
#include "translator_ru.h"
#include "translator_hr.h"
#include "translator_pl.h"
#include "translator_pt.h"
#include "translator_hi.h"
#include "translator_hu.h"
#include "translator_ke.h"
#include "translator_kr.h"
#include "translator_ro.h"
#include "translator_si.h"
#include "translator_cn.h"
#include "translator_tw.h"
#include "translator_no.h"
#include "translator_br.h"
#include "translator_dk.h"
#include "translator_sk.h"
#include "translator_ua.h"
#include "translator_gr.h"
#include "translator_sr.h"
#include "translator_ca.h"
#include "translator_lt.h"
#include "translator_lv.h"
#include "translator_za.h"
#include "translator_ar.h"
#include "translator_fa.h"
#include "translator_mk.h"
#include "translator_sc.h"
#include "translator_vi.h"
#include "translator_tr.h"
#include "translator_bg.h"
#include "configimpl.h"
Translator *theTranslator=nullptr;
void setTranslator(OUTPUT_LANGUAGE_t langName)
{
switch (langName)
{
case OUTPUT_LANGUAGE_t::English: theTranslator = new TranslatorEnglish; break;
case OUTPUT_LANGUAGE_t::Afrikaans: theTranslator = new TranslatorAfrikaans; break;
case OUTPUT_LANGUAGE_t::Arabic: theTranslator = new TranslatorArabic; break;
case OUTPUT_LANGUAGE_t::Armenian: theTranslator = new TranslatorArmenian; break;
case OUTPUT_LANGUAGE_t::Brazilian: theTranslator = new TranslatorBrazilian; break;
case OUTPUT_LANGUAGE_t::Bulgarian: theTranslator = new TranslatorBulgarian; break;
case OUTPUT_LANGUAGE_t::Catalan: theTranslator = new TranslatorCatalan; break;
case OUTPUT_LANGUAGE_t::Chinese: theTranslator = new TranslatorChinese; break;
case OUTPUT_LANGUAGE_t::Chinese_Traditional: theTranslator = new TranslatorChinesetraditional; break;
case OUTPUT_LANGUAGE_t::Croatian: theTranslator = new TranslatorCroatian; break;
case OUTPUT_LANGUAGE_t::Czech: theTranslator = new TranslatorCzech; break;
case OUTPUT_LANGUAGE_t::Danish: theTranslator = new TranslatorDanish; break;
case OUTPUT_LANGUAGE_t::Dutch: theTranslator = new TranslatorDutch; break;
case OUTPUT_LANGUAGE_t::Esperanto: theTranslator = new TranslatorEsperanto; break;
case OUTPUT_LANGUAGE_t::Farsi: theTranslator = new TranslatorPersian; break;
case OUTPUT_LANGUAGE_t::Finnish: theTranslator = new TranslatorFinnish; break;
case OUTPUT_LANGUAGE_t::French: theTranslator = new TranslatorFrench; break;
case OUTPUT_LANGUAGE_t::German: theTranslator = new TranslatorGerman; break;
case OUTPUT_LANGUAGE_t::Greek: theTranslator = new TranslatorGreek; break;
case OUTPUT_LANGUAGE_t::Hindi: theTranslator = new TranslatorHindi; break;
case OUTPUT_LANGUAGE_t::Hungarian: theTranslator = new TranslatorHungarian; break;
case OUTPUT_LANGUAGE_t::Indonesian: theTranslator = new TranslatorIndonesian; break;
case OUTPUT_LANGUAGE_t::Italian: theTranslator = new TranslatorItalian; break;
case OUTPUT_LANGUAGE_t::Japanese: theTranslator = new TranslatorJapanese; break;
case OUTPUT_LANGUAGE_t::Japanese_en: theTranslator = new TranslatorJapaneseEn; break;
case OUTPUT_LANGUAGE_t::Korean: theTranslator = new TranslatorKorean; break;
case OUTPUT_LANGUAGE_t::Korean_en: theTranslator = new TranslatorKoreanEn; break;
case OUTPUT_LANGUAGE_t::Latvian: theTranslator = new TranslatorLatvian; break;
case OUTPUT_LANGUAGE_t::Lithuanian: theTranslator = new TranslatorLithuanian; break;
case OUTPUT_LANGUAGE_t::Macedonian: theTranslator = new TranslatorMacedonian; break;
case OUTPUT_LANGUAGE_t::Norwegian: theTranslator = new TranslatorNorwegian; break;
case OUTPUT_LANGUAGE_t::Persian: theTranslator = new TranslatorPersian; break;
case OUTPUT_LANGUAGE_t::Polish: theTranslator = new TranslatorPolish; break;
case OUTPUT_LANGUAGE_t::Portuguese: theTranslator = new TranslatorPortuguese; break;
case OUTPUT_LANGUAGE_t::Romanian: theTranslator = new TranslatorRomanian; break;
case OUTPUT_LANGUAGE_t::Russian: theTranslator = new TranslatorRussian; break;
case OUTPUT_LANGUAGE_t::Serbian: theTranslator = new TranslatorSerbian; break;
case OUTPUT_LANGUAGE_t::Serbian_Cyrillic: theTranslator = new TranslatorSerbianCyrillic; break;
case OUTPUT_LANGUAGE_t::Slovak: theTranslator = new TranslatorSlovak; break;
case OUTPUT_LANGUAGE_t::Slovene: theTranslator = new TranslatorSlovene; break;
case OUTPUT_LANGUAGE_t::Spanish: theTranslator = new TranslatorSpanish; break;
case OUTPUT_LANGUAGE_t::Swedish: theTranslator = new TranslatorSwedish; break;
case OUTPUT_LANGUAGE_t::Turkish: theTranslator = new TranslatorTurkish; break;
case OUTPUT_LANGUAGE_t::Ukrainian: theTranslator = new TranslatorUkrainian; break;
case OUTPUT_LANGUAGE_t::Vietnamese: theTranslator = new TranslatorVietnamese; break;
}
QCString msg = theTranslator->updateNeededMessage();
if (!msg.isEmpty()) ConfigImpl::config_warn("%s", qPrint(msg));
}
| 6,585
|
C++
|
.cpp
| 122
| 51.262295
| 105
| 0.708469
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,441
|
tooltip.cpp
|
doxygen_doxygen/src/tooltip.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2020 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.
*
*/
#include <map>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <mutex>
#include "tooltip.h"
#include "definition.h"
#include "outputlist.h"
#include "util.h"
#include "filedef.h"
#include "doxygen.h"
#include "config.h"
static std::mutex g_tooltipsFileMutex;
static std::mutex g_tooltipsTipMutex;
static std::unordered_map<int, std::unordered_set<std::string> > g_tooltipsWrittenPerFile;
class TooltipManager::Private
{
public:
std::map<std::string,const Definition*> tooltipInfo;
};
TooltipManager::TooltipManager() : p(std::make_unique<Private>())
{
}
TooltipManager::~TooltipManager()
{
}
static QCString escapeId(const QCString &s)
{
QCString res=s;
for (size_t i=0;i<res.length();i++) if (!isId(res[i])) res[i]='_';
return res;
}
void TooltipManager::addTooltip(const Definition *d)
{
bool sourceTooltips = Config_getBool(SOURCE_TOOLTIPS);
if (!sourceTooltips) return;
QCString id = d->getOutputFileBase();
int i=id.findRev('/');
if (i!=-1)
{
id = id.right(id.length()-i-1); // strip path (for CREATE_SUBDIRS=YES)
}
// In case an extension is present translate this extension to something understood by the tooltip handler
// otherwise extend t with a translated htmlFileExtension.
QCString currentExtension = getFileNameExtension(id);
if (currentExtension.isEmpty())
{
id += escapeId(Doxygen::htmlFileExtension);
}
else
{
id = stripExtensionGeneral(id,currentExtension) + escapeId(currentExtension);
}
QCString anc = d->anchor();
if (!anc.isEmpty())
{
id+="_"+anc;
}
id = "a" + id;
p->tooltipInfo.emplace(id.str(),d);
//printf("%p: addTooltip(%s)\n",this,id.data());
}
void TooltipManager::writeTooltips(OutputCodeList &ol)
{
std::unordered_map<int, std::unordered_set<std::string> >::iterator it;
// critical section
{
std::lock_guard<std::mutex> lock(g_tooltipsFileMutex);
int id = ol.id();
it = g_tooltipsWrittenPerFile.find(id);
if (it==g_tooltipsWrittenPerFile.end()) // new file
{
it = g_tooltipsWrittenPerFile.emplace(id,std::unordered_set<std::string>()).first;
}
}
for (const auto &[name,d] : p->tooltipInfo)
{
bool written = false;
// critical section
{
std::lock_guard<std::mutex> lock(g_tooltipsTipMutex);
written = it->second.find(name)!=it->second.end();
if (!written) // only write tooltips once
{
it->second.insert(name); // remember we wrote this tooltip for the given file id
}
}
if (!written)
{
//printf("%p: writeTooltips(%s) ol=%d\n",this,name.c_str(),ol.id());
DocLinkInfo docInfo;
docInfo.name = d->qualifiedName();
docInfo.ref = d->getReference();
docInfo.url = d->getOutputFileBase();
docInfo.anchor = d->anchor();
SourceLinkInfo defInfo;
if (d->getBodyDef() && d->getStartBodyLine()!=-1)
{
defInfo.file = d->getBodyDef()->name();
defInfo.line = d->getStartBodyLine();
defInfo.url = d->getSourceFileBase();
defInfo.anchor = d->getSourceAnchor();
}
SourceLinkInfo declInfo; // TODO: fill in...
QCString decl;
if (d->definitionType()==Definition::TypeMember)
{
const MemberDef *md = toMemberDef(d);
if (!md->isAnonymous())
{
decl = md->declaration();
}
}
ol.writeTooltip(name.c_str(), // id
docInfo, // symName
decl, // decl
d->briefDescriptionAsTooltip(), // desc
defInfo,
declInfo
);
}
}
}
| 4,422
|
C++
|
.cpp
| 138
| 27.833333
| 108
| 0.630975
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
28,442
|
moduledef.cpp
|
doxygen_doxygen/src/moduledef.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2023 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.
*
*/
#include "moduledef.h"
#include "definitionimpl.h"
#include "entry.h"
#include "memberdef.h"
#include "classlist.h"
#include "namespacedef.h"
#include "conceptdef.h"
#include "config.h"
#include "outputlist.h"
#include "language.h"
#include "util.h"
#include "groupdef.h"
#include "message.h"
#include "membergroup.h"
#include "classdef.h"
#include "textstream.h"
#include "trace.h"
class ModuleDefImpl;
struct HeaderInfo
{
HeaderInfo(const QCString &fn,const QCString &name,bool sys)
: fileName(fn), headerName(name), isSystem(sys) {}
QCString fileName; // file containing the import
QCString headerName; // name of the imported header
bool isSystem; // <...> => true, "..." => false
};
using HeaderInfoVector = std::vector<HeaderInfo>;
class ModuleDefImpl : public DefinitionMixin<ModuleDef>
{
public:
ModuleDefImpl(const QCString &fileName,int startLine,int startColom,
const QCString &name, Type type, const QCString &partitionName)
: DefinitionMixin<ModuleDef>(fileName,startLine,startColom,name,nullptr,nullptr,true),
m_type(type), m_partitionName(partitionName) {}
// --- Definition
DefType definitionType() const override { return TypeModule; }
CodeSymbolType codeSymbolType() const override { return CodeSymbolType::Module; }
QCString displayName(bool=TRUE) const override { return name(); }
QCString getOutputFileBase() const override;
QCString anchor() const override { return ""; }
bool isLinkableInProject() const override { return isLinkable() && !isHidden() && !isReference(); }
bool isLinkable() const override { return hasDocumentation(); }
QCString qualifiedName() const override;
void writeSummaryLinks(OutputList &ol) const override;
// --- ModuleDef
Type moduleType() const override { return m_type; }
QCString partitionName() const override { return m_partitionName; }
void writeDocumentation(OutputList &ol) override;
bool isPrimaryInterface() const override { return m_type==Type::Interface && m_partitionName.isEmpty(); }
MemberList *getMemberList(MemberListType lt) const override;
const MemberLists &getMemberLists() const override { return m_memberLists; }
const MemberGroupList &getMemberGroups() const override { return m_memberGroups; }
const ClassLinkedRefMap &getClasses() const override { return m_classes; }
const ConceptLinkedRefMap &getConcepts() const override { return m_concepts; }
int countVisibleMembers() const override;
FileDef *getFileDef() const override { return m_fileDef; }
const ImportInfoMap &getImports() const override { return m_imports; }
const ImportInfoMap &getExports() const override { return m_exportedModules; }
const ModuleMap &partitions() const override { return m_partitions; }
void writeTagFile(TextStream &t) const override;
FileList getUsedFiles() const override;
void writeExports(OutputList &ol,const QCString &title);
void writeClassDeclarations(OutputList &ol,const QCString &title);
void writeConcepts(OutputList &ol,const QCString &title);
void writeFiles(OutputList &ol,const QCString &title);
void startMemberDeclarations(OutputList &ol);
void endMemberDeclarations(OutputList &ol);
void startMemberDocumentation(OutputList &ol);
void endMemberDocumentation(OutputList &ol);
void writeDetailedDescription(OutputList &ol,const QCString &title);
void writeBriefDescription(OutputList &ol);
void writeMemberGroups(OutputList &ol);
void writeMemberDeclarations(OutputList &ol,MemberListType lt,const QCString &title);
void writeMemberDocumentation(OutputList &ol,MemberListType lt,const QCString &title);
void writeAuthorSection(OutputList &ol);
void writeDeclarationLink(OutputList &ol,bool &found,const QCString &header,bool localNames) const;
void addHeader(int line,const QCString &headerName,bool isSystem);
void addImport(int line,const QCString &moduleName,const QCString &partitionName,bool isExported);
void addClassToModule(const Entry *root,ClassDef *cd);
void addConceptToModule(const Entry *root,ConceptDef *cd);
void addMemberToModule(const Entry *root,MemberDef *md);
void addPartition(ModuleDefImpl *mod);
void addContributingModule(ModuleDefImpl *mod);
void setPrimaryInterface(const ModuleDef *mod);
void setFileDef(FileDef *fd);
void addMemberToList(MemberListType lt,MemberDef *md);
void addExportedModule(const QCString &moduleName,const ImportInfo &info);
void addListReferences();
void addMembersToMemberGroup();
void distributeMemberGroupDocumentation();
void findSectionsInDocumentation();
void sortMemberLists();
//ModuleMap &partitions() { return m_partitions; }
void mergeSymbolsFrom(ModuleDefImpl *other);
bool hasDetailedDescription() const;
void countMembers();
private:
Type m_type;
QCString m_partitionName;
ImportInfoMap m_imports;
ImportInfoMap m_exportedModules;
ClassLinkedRefMap m_classes;
ConceptLinkedRefMap m_concepts;
MemberLists m_memberLists;
ModuleMap m_partitions;
ModuleList m_contributing;
MemberGroupList m_memberGroups;
const ModuleDef *m_primaryInterface = nullptr;
FileDef *m_fileDef = nullptr; // file holding this module
};
QCString ModuleDefImpl::getOutputFileBase() const
{
return convertNameToFile("module_" + name());
}
QCString ModuleDefImpl::qualifiedName() const
{
QCString result=name();
if (!m_partitionName.isEmpty())
{
result+=":"+m_partitionName;
}
return result;
}
void ModuleDefImpl::addPartition(ModuleDefImpl *mod)
{
std::string qName = mod->qualifiedName().str();
if (m_partitions.find(qName)==m_partitions.end())
{
m_partitions.emplace(qName,mod);
}
}
void ModuleDefImpl::addContributingModule(ModuleDefImpl *mod)
{
if (std::find(m_contributing.begin(),m_contributing.end(),mod)==m_contributing.end())
{
m_contributing.push_back(mod);
}
}
void ModuleDefImpl::setPrimaryInterface(const ModuleDef *mod)
{
m_primaryInterface = mod;
}
void ModuleDefImpl::setFileDef(FileDef *fd)
{
m_fileDef = fd;
}
void ModuleDefImpl::addHeader(int line,const QCString &headerName,bool isSystem)
{
AUTO_TRACE("name={}:line={},header={},isSystem={}",name(),line,headerName,isSystem);
}
void ModuleDefImpl::addImport(int line,const QCString &moduleName,const QCString &partitionName,bool isExported)
{
AUTO_TRACE("name={}:line={},module={},partition={}",name(),line,moduleName,partitionName);
m_imports[getDefFileName().str()+":"+std::to_string(line)].push_back(ImportInfo(this,moduleName,line,partitionName,isExported));
}
void ModuleDefImpl::addExportedModule(const QCString &moduleName,const ImportInfo &info)
{
AUTO_TRACE("name={}:moduleName={},import={}",name(),moduleName,info.importName);
m_exportedModules[moduleName.str()].push_back(info);
}
void ModuleDefImpl::addClassToModule(const Entry *root,ClassDef *cd)
{
QCString className = cd->qualifiedName();
AUTO_TRACE("{}:{} class {} of module {} exported={}",
root->fileName,root->startLine, className, name(), root->exported);
bool isExported = m_classes.find(className)!=nullptr;
if (root->exported && !isExported)
{
m_classes.add(className,cd);
}
auto cdm = toClassDefMutable(cd);
if (cdm && root->exported && !cd->isExported())
{
cdm->setExported(true);
}
}
void ModuleDefImpl::addConceptToModule(const Entry *root,ConceptDef *cd)
{
QCString conceptName = cd->qualifiedName();
AUTO_TRACE("{}:{} concept {} of module {} exported={}",
root->fileName,root->startLine,
cd->qualifiedName(),name(),
root->exported);
bool isExported = m_classes.find(conceptName)!=nullptr;
if (root->exported && !isExported)
{
m_concepts.add(conceptName,cd);
}
auto cdm = toConceptDefMutable(cd);
if (cdm && root->exported && !cd->isExported())
{
cdm->setExported(true);
}
}
MemberList *ModuleDefImpl::getMemberList(MemberListType lt) const
{
for (auto &ml : m_memberLists)
{
if (ml->listType()==lt)
{
return ml.get();
}
}
return nullptr;
}
void ModuleDefImpl::addMemberToList(MemberListType lt,MemberDef *md)
{
bool sortBriefDocs = Config_getBool(SORT_BRIEF_DOCS);
bool sortMemberDocs = Config_getBool(SORT_MEMBER_DOCS);
auto &ml = m_memberLists.get(lt,MemberListContainer::Module);
ml->setNeedsSorting(
(ml->listType().isDeclaration() && sortBriefDocs) ||
(ml->listType().isDocumentation() && sortMemberDocs));
ml->push_back(md);
if (ml->listType().isDeclaration())
{
MemberDefMutable *mdm = toMemberDefMutable(md);
if (mdm)
{
mdm->setSectionList(this,ml.get());
}
}
}
void ModuleDefImpl::addMemberToModule(const Entry *root,MemberDef *md)
{
AUTO_TRACE("{}:{} member {} of module {} exported={}",
qPrint(root->fileName),root->startLine,
qPrint(md->qualifiedName()),qPrint(name()),
root->exported);
MemberList *allMemberList = getMemberList(MemberListType::AllMembersList());
if (allMemberList==nullptr)
{
m_memberLists.emplace_back(std::make_unique<MemberList>(MemberListType::AllMembersList(),MemberListContainer::Module));
allMemberList = m_memberLists.back().get();
}
if (allMemberList->contains(md))
{
return;
}
allMemberList->push_back(md);
switch (md->memberType())
{
case MemberType::Variable:
addMemberToList(MemberListType::DecVarMembers(),md);
break;
case MemberType::Function:
addMemberToList(MemberListType::DecFuncMembers(),md);
break;
case MemberType::Typedef:
addMemberToList(MemberListType::DecTypedefMembers(),md);
break;
case MemberType::Enumeration:
addMemberToList(MemberListType::DecEnumMembers(),md);
break;
default:
break;
}
auto mdm = toMemberDefMutable(md);
if (mdm && root->exported && !md->isExported())
{
mdm->setExported(true);
}
}
void ModuleDefImpl::mergeSymbolsFrom(ModuleDefImpl *other)
{
AUTO_TRACE("{} merging symbols of {} ({}:{})",
name(),other->qualifiedName(),other->getDefFileName(),other->getDefLine());
for (const auto &cd : other->getClasses())
{
m_classes.add(cd->qualifiedName(),cd);
}
for (const auto &cd : other->getConcepts())
{
m_concepts.add(cd->qualifiedName(),cd);
}
auto mergeMemberList = [this,other](MemberListType lt)
{
const auto srcMl = other->getMemberList(lt);
if (srcMl)
{
auto &dstMl = m_memberLists.get(lt,srcMl->container());
for (const auto &md : *srcMl)
{
dstMl->push_back(md);
}
}
};
mergeMemberList(MemberListType::DecVarMembers());
mergeMemberList(MemberListType::DecFuncMembers());
mergeMemberList(MemberListType::DecTypedefMembers());
mergeMemberList(MemberListType::DecEnumMembers());
}
void ModuleDefImpl::writeDocumentation(OutputList &ol)
{
if (isReference()) return;
ol.pushGeneratorState();
AUTO_TRACE("%s file=%s",name(),getDefFileName());
SrcLangExt lang = getLanguage();
QCString pageTitle = theTranslator->trModuleReference(displayName());
startFile(ol,getOutputFileBase(),name(),pageTitle,HighlightedItem::ModuleVisible,false,QCString(),0);
// ---- title part
ol.startHeaderSection();
writeSummaryLinks(ol);
ol.startTitleHead(getOutputFileBase());
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.parseText(pageTitle);
ol.popGeneratorState();
addGroupListToTitle(ol,this);
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.endTitleHead(getOutputFileBase(),pageTitle);
ol.popGeneratorState();
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Man);
ol.endTitleHead(getOutputFileBase(),name());
ol.writeString(" - ");
ol.parseText(pageTitle);
ol.popGeneratorState();
ol.endHeaderSection();
ol.startContents();
//---------------------------------------- start flexible part -------------------------------
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Module))
{
const LayoutDocEntrySection *ls = dynamic_cast<const LayoutDocEntrySection*>(lde.get());
switch (lde->kind())
{
case LayoutDocEntry::BriefDesc:
writeBriefDescription(ol);
break;
case LayoutDocEntry::MemberDeclStart:
startMemberDeclarations(ol);
break;
case LayoutDocEntry::ModuleClasses:
if (ls) writeClassDeclarations(ol,ls->title(lang));
break;
case LayoutDocEntry::ModuleConcepts:
if (ls) writeConcepts(ol,ls->title(lang));
break;
case LayoutDocEntry::ModuleExports:
if (ls) writeExports(ol,ls->title(lang));
break;
case LayoutDocEntry::ModuleUsedFiles:
if (ls) writeFiles(ol,ls->title(lang));
break;
case LayoutDocEntry::MemberGroups:
writeMemberGroups(ol);
break;
case LayoutDocEntry::MemberDecl:
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd) writeMemberDeclarations(ol,lmd->type,lmd->title(lang));
}
break;
case LayoutDocEntry::MemberDeclEnd:
endMemberDeclarations(ol);
break;
case LayoutDocEntry::DetailedDesc:
if (ls) writeDetailedDescription(ol,ls->title(lang));
break;
case LayoutDocEntry::MemberDefStart:
startMemberDocumentation(ol);
break;
case LayoutDocEntry::MemberDef:
{
const LayoutDocEntryMemberDef *lmd = dynamic_cast<const LayoutDocEntryMemberDef*>(lde.get());
if (lmd) writeMemberDocumentation(ol,lmd->type,lmd->title(lang));
}
break;
case LayoutDocEntry::MemberDefEnd:
endMemberDocumentation(ol);
break;
case LayoutDocEntry::AuthorSection:
writeAuthorSection(ol);
break;
case LayoutDocEntry::ClassIncludes:
case LayoutDocEntry::ClassInheritanceGraph:
case LayoutDocEntry::ClassNestedClasses:
case LayoutDocEntry::ClassCollaborationGraph:
case LayoutDocEntry::ClassAllMembersLink:
case LayoutDocEntry::ClassUsedFiles:
case LayoutDocEntry::ClassInlineClasses:
case LayoutDocEntry::FileClasses:
case LayoutDocEntry::FileConcepts:
case LayoutDocEntry::FileInterfaces:
case LayoutDocEntry::FileStructs:
case LayoutDocEntry::FileExceptions:
case LayoutDocEntry::FileNamespaces:
case LayoutDocEntry::FileConstantGroups:
case LayoutDocEntry::FileIncludes:
case LayoutDocEntry::FileIncludeGraph:
case LayoutDocEntry::FileIncludedByGraph:
case LayoutDocEntry::FileInlineClasses:
case LayoutDocEntry::FileSourceLink:
case LayoutDocEntry::NamespaceNestedNamespaces:
case LayoutDocEntry::NamespaceNestedConstantGroups:
case LayoutDocEntry::NamespaceClasses:
case LayoutDocEntry::NamespaceConcepts:
case LayoutDocEntry::NamespaceInterfaces:
case LayoutDocEntry::NamespaceStructs:
case LayoutDocEntry::NamespaceExceptions:
case LayoutDocEntry::NamespaceInlineClasses:
case LayoutDocEntry::ConceptDefinition:
case LayoutDocEntry::GroupClasses:
case LayoutDocEntry::GroupConcepts:
case LayoutDocEntry::GroupModules:
case LayoutDocEntry::GroupInlineClasses:
case LayoutDocEntry::GroupNamespaces:
case LayoutDocEntry::GroupDirs:
case LayoutDocEntry::GroupNestedGroups:
case LayoutDocEntry::GroupFiles:
case LayoutDocEntry::GroupGraph:
case LayoutDocEntry::GroupPageDocs:
case LayoutDocEntry::DirSubDirs:
case LayoutDocEntry::DirFiles:
case LayoutDocEntry::DirGraph:
err("Internal inconsistency: member %d should not be part of "
"LayoutDocManager::Module entry list\n",lde->kind());
break;
}
}
//---------------------------------------- end flexible part -------------------------------
endFile(ol);
ol.popGeneratorState();
}
void ModuleDefImpl::writeClassDeclarations(OutputList &ol,const QCString &title)
{
m_classes.writeDeclaration(ol,nullptr,title,FALSE);
}
void ModuleDefImpl::writeConcepts(OutputList &ol,const QCString &title)
{
m_concepts.writeDeclaration(ol,title,FALSE);
}
void ModuleDefImpl::startMemberDeclarations(OutputList &ol)
{
ol.startMemberSections();
}
void ModuleDefImpl::endMemberDeclarations(OutputList &ol)
{
ol.endMemberSections();
}
void ModuleDefImpl::startMemberDocumentation(OutputList &ol)
{
if (Config_getBool(SEPARATE_MEMBER_PAGES))
{
ol.disable(OutputType::Html);
Doxygen::suppressDocWarnings = TRUE;
}
}
void ModuleDefImpl::endMemberDocumentation(OutputList &ol)
{
if (Config_getBool(SEPARATE_MEMBER_PAGES))
{
ol.enable(OutputType::Html);
Doxygen::suppressDocWarnings = FALSE;
}
}
void ModuleDefImpl::writeDetailedDescription(OutputList &ol,const QCString &title)
{
if (hasDetailedDescription())
{
ol.pushGeneratorState();
ol.disable(OutputType::Html);
ol.writeRuler();
ol.popGeneratorState();
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
ol.writeAnchor(QCString(),"details");
ol.popGeneratorState();
ol.startGroupHeader();
ol.parseText(title);
ol.endGroupHeader();
ol.startTextBlock();
if (!briefDescription().isEmpty() && Config_getBool(REPEAT_BRIEF))
{
ol.generateDoc(briefFile(),briefLine(),this,nullptr,briefDescription(),FALSE,FALSE,
QCString(),FALSE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
}
if (!briefDescription().isEmpty() && Config_getBool(REPEAT_BRIEF) &&
!documentation().isEmpty())
{
ol.pushGeneratorState();
ol.disable(OutputType::Man);
ol.disable(OutputType::RTF);
ol.enableAll();
ol.disableAllBut(OutputType::Man);
ol.enable(OutputType::Latex);
ol.writeString("\n\n");
ol.popGeneratorState();
}
if (!documentation().isEmpty())
{
ol.generateDoc(docFile(),docLine(),this,nullptr,documentation()+"\n",TRUE,FALSE,
QCString(),FALSE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
}
ol.endTextBlock();
}
}
void ModuleDefImpl::writeBriefDescription(OutputList &ol)
{
if (hasBriefDescription())
{
auto parser { createDocParser() };
auto ast { validatingParseDoc(*parser.get(),
briefFile(),briefLine(),this,nullptr,
briefDescription(),TRUE,FALSE,
QCString(),TRUE,FALSE,Config_getBool(MARKDOWN_SUPPORT)) };
if (!ast->isEmpty())
{
ol.startParagraph();
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Man);
ol.writeString(" - ");
ol.popGeneratorState();
ol.writeDoc(ast.get(),this,nullptr);
ol.pushGeneratorState();
ol.disable(OutputType::RTF);
ol.writeString(" \n");
ol.enable(OutputType::RTF);
if (hasDetailedDescription())
{
ol.disableAllBut(OutputType::Html);
ol.startTextLink(QCString(),"details");
ol.parseText(theTranslator->trMore());
ol.endTextLink();
}
ol.popGeneratorState();
ol.endParagraph();
}
}
ol.writeSynopsis();
}
void ModuleDefImpl::writeMemberGroups(OutputList &ol)
{
for (const auto &mg : m_memberGroups)
{
mg->writeDeclarations(ol,nullptr,nullptr,nullptr,nullptr,this);
}
}
void ModuleDefImpl::writeMemberDeclarations(OutputList &ol,MemberListType lt,const QCString &title)
{
MemberList * ml = getMemberList(lt);
if (ml) ml->writeDeclarations(ol,nullptr,nullptr,nullptr,nullptr,this,title,QCString());
}
void ModuleDefImpl::writeMemberDocumentation(OutputList &ol,MemberListType lt,const QCString &title)
{
MemberList * ml = getMemberList(lt);
if (ml) ml->writeDocumentation(ol,name(),this,title);
}
void ModuleDefImpl::writeAuthorSection(OutputList &ol)
{
// write Author section (Man only)
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Man);
ol.startGroupHeader();
ol.parseText(theTranslator->trAuthor(TRUE,TRUE));
ol.endGroupHeader();
ol.parseText(theTranslator->trGeneratedAutomatically(Config_getString(PROJECT_NAME)));
ol.popGeneratorState();
}
bool ModuleDefImpl::hasDetailedDescription() const
{
bool repeatBrief = Config_getBool(REPEAT_BRIEF);
return (!briefDescription().isEmpty() && repeatBrief) || !documentation().isEmpty();
}
void ModuleDefImpl::countMembers()
{
for (auto &ml : m_memberLists)
{
ml->countDecMembers();
ml->countDocMembers();
}
for (const auto &mg : m_memberGroups)
{
mg->countDecMembers();
mg->countDocMembers();
}
}
void ModuleDefImpl::addListReferences()
{
const RefItemVector &xrefItems = xrefListItems();
addRefItem(xrefItems,
qualifiedName(),
getLanguage()==SrcLangExt::Fortran ?
theTranslator->trModule(TRUE,TRUE) :
theTranslator->trNamespace(TRUE,TRUE),
getOutputFileBase(),displayName(),
QCString(),
this
);
for (const auto &mg : m_memberGroups)
{
mg->addListReferences(this);
}
for (auto &ml : m_memberLists)
{
if (ml->listType().isDocumentation())
{
ml->addListReferences(this);
}
}
}
void ModuleDefImpl::addMembersToMemberGroup()
{
for (auto &ml : m_memberLists)
{
if (ml->listType().isDeclaration())
{
::addMembersToMemberGroup(ml.get(),&m_memberGroups,this);
}
}
// add members inside sections to their groups
for (const auto &mg : m_memberGroups)
{
if (mg->allMembersInSameSection() && Config_getBool(SUBGROUPING))
{
//printf("----> addToDeclarationSection(%s)\n",qPrint(mg->header()));
mg->addToDeclarationSection();
}
}
}
void ModuleDefImpl::distributeMemberGroupDocumentation()
{
for (const auto &mg : m_memberGroups)
{
mg->distributeMemberGroupDocumentation();
}
}
void ModuleDefImpl::findSectionsInDocumentation()
{
docFindSections(briefDescription(),this,docFile());
docFindSections(documentation(),this,docFile());
docFindSections(inbodyDocumentation(),this,docFile());
for (const auto &mg : m_memberGroups)
{
mg->findSectionsInDocumentation(this);
}
for (auto &ml : m_memberLists)
{
if (ml->listType().isDeclaration())
{
ml->findSectionsInDocumentation(this);
}
}
}
void ModuleDefImpl::sortMemberLists()
{
for (auto &ml : m_memberLists)
{
if (ml->needsSorting()) { ml->sort(); ml->setNeedsSorting(FALSE); }
}
if (Config_getBool(SORT_BRIEF_DOCS))
{
auto classComp = [](const ClassLinkedRefMap::Ptr &c1,const ClassLinkedRefMap::Ptr &c2)
{
return Config_getBool(SORT_BY_SCOPE_NAME) ?
qstricmp_sort(c1->name(), c2->name())<0 :
qstricmp_sort(c1->className(), c2->className())<0;
};
std::stable_sort(m_classes.begin(), m_classes.end(), classComp);
auto conceptComp = [](const ConceptLinkedRefMap::Ptr &c1,const ConceptLinkedRefMap::Ptr &c2)
{
return Config_getBool(SORT_BY_SCOPE_NAME) ?
qstricmp_sort(c1->qualifiedName(), c2->qualifiedName())<0 :
qstricmp_sort(c1->name(), c2->name())<0;
};
std::stable_sort(m_concepts.begin(), m_concepts.end(), conceptComp);
}
static auto contrComp = [](const ModuleDef *m1, const ModuleDef *m2)
{
FileDef *f1 = m1->getFileDef();
FileDef *f2 = m2->getFileDef();
QCString fn1 = f1 ? f1->name() : m1->name();
QCString fn2 = f2 ? f2->name() : m2->name();
static auto typeRank = [](const ModuleDef *m) -> int
{
if (m->moduleType()==ModuleDef::Type::Interface)
{
if (m->partitionName().isEmpty()) return 0; // primary interface unit
return 1; // partition interface unit
}
else
{
if (!m->partitionName().isEmpty()) return 2; // partition implementation unit
return 3; // implementation unit
}
};
auto tr1 = typeRank(m1);
auto tr2 = typeRank(m2);
int diff = qstricmp_sort(fn1,fn2);
return tr1<tr2 || (tr1==tr2 && diff<0);
};
std::stable_sort(m_contributing.begin(), m_contributing.end(), contrComp);
}
void ModuleDefImpl::writeSummaryLinks(OutputList &ol) const
{
ol.pushGeneratorState();
ol.disableAllBut(OutputType::Html);
bool first=TRUE;
SrcLangExt lang=getLanguage();
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Module))
{
const LayoutDocEntrySection *ls = dynamic_cast<const LayoutDocEntrySection*>(lde.get());
if (lde->kind()==LayoutDocEntry::ModuleClasses && m_classes.declVisible() && ls)
{
QCString label = "classes";
ol.writeSummaryLink(QCString(),label,ls->title(lang),first);
first=FALSE;
}
else if (lde->kind()==LayoutDocEntry::ModuleConcepts && m_concepts.declVisible() && ls)
{
QCString label = "concepts";
ol.writeSummaryLink(QCString(),label,ls->title(lang),first);
first=FALSE;
}
else if (lde->kind()==LayoutDocEntry::ModuleUsedFiles && ls)
{
QCString label = "files";
ol.writeSummaryLink(QCString(),label,ls->title(lang),first);
first=FALSE;
}
else if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
MemberList * ml = getMemberList(lmd->type);
if (ml && ml->declVisible())
{
ol.writeSummaryLink(QCString(),ml->listType().toLabel(),lmd->title(lang),first);
first=FALSE;
}
}
}
}
if (!first)
{
ol.writeString(" </div>\n");
}
ol.popGeneratorState();
}
void ModuleDefImpl::writeDeclarationLink(OutputList &ol,bool &found,const QCString &header,bool localNames) const
{
if (isLinkable())
{
if (!found) // first module
{
ol.startMemberHeader("modules");
if (!header.isEmpty())
{
ol.parseText(header);
}
else
{
theTranslator->trModule(true,false);
}
ol.endMemberHeader();
ol.startMemberList();
found=TRUE;
}
ol.startMemberDeclaration();
ol.startMemberItem(anchor(),OutputGenerator::MemberItemType::Normal);
ol.writeString("module ");
QCString cname = displayName(!localNames);
ol.insertMemberAlign();
if (isLinkable())
{
ol.writeObjectLink(getReference(),
getOutputFileBase(),
anchor(),
cname
);
}
else
{
ol.startBold();
ol.docify(cname);
ol.endBold();
}
ol.endMemberItem(OutputGenerator::MemberItemType::Normal);
// add the brief description if available
if (!briefDescription().isEmpty() && Config_getBool(BRIEF_MEMBER_DESC))
{
auto parser { createDocParser() };
auto ast { validatingParseDoc(
*parser.get(),briefFile(),briefLine(),this,nullptr,
briefDescription(),FALSE,FALSE,
QCString(),TRUE,FALSE,Config_getBool(MARKDOWN_SUPPORT)) };
if (!ast->isEmpty())
{
ol.startMemberDescription(anchor());
ol.writeDoc(ast.get(),this,nullptr);
ol.endMemberDescription();
}
}
ol.endMemberDeclaration(anchor(),QCString());
}
}
void ModuleDefImpl::writeExports(OutputList &ol,const QCString &title)
{
AUTO_TRACE("name={} count={}",name(),m_exportedModules.size());
if (!m_exportedModules.empty())
{
ol.startMemberHeader("exports");
ol.parseText(title);
ol.endMemberHeader();
ol.startMemberList();
for (const auto &[moduleName,importInfoList] : m_exportedModules)
{
for (const auto &importInfo : importInfoList)
{
ModuleDef *mod = ModuleManager::instance().getPrimaryInterface(importInfo.importName);
ol.startMemberDeclaration();
ol.startMemberItem(importInfo.importName,OutputGenerator::MemberItemType::Normal);
ol.docify(theTranslator->trModule(FALSE,TRUE)+" ");
ol.insertMemberAlign();
if (mod && mod->isLinkable())
{
ol.writeObjectLink(mod->getReference(),mod->getOutputFileBase(),QCString(),mod->displayName());
}
else
{
ol.startBold();
ol.docify(importInfo.importName);
ol.endBold();
}
ol.endMemberItem(OutputGenerator::MemberItemType::Normal);
if (mod && !mod->briefDescription().isEmpty() && Config_getBool(BRIEF_MEMBER_DESC))
{
ol.startMemberDescription(mod->getOutputFileBase());
ol.generateDoc(briefFile(),briefLine(),mod,nullptr,mod->briefDescription(),FALSE,FALSE,
QCString(),TRUE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
ol.endMemberDescription();
}
ol.endMemberDeclaration(QCString(),QCString());
}
}
ol.endMemberList();
}
}
void ModuleDefImpl::writeFiles(OutputList &ol,const QCString &title)
{
AUTO_TRACE("{} count={}",name(),m_contributing.size());
if (!m_contributing.empty())
{
ol.startMemberHeader("files");
ol.parseText(title);
ol.endMemberHeader();
ol.startMemberList();
for (const auto &mod : m_contributing)
{
FileDef *fd = mod->getFileDef();
if (fd)
{
ol.startMemberDeclaration();
ol.startMemberItem(fd->anchor(),OutputGenerator::MemberItemType::Normal);
ol.docify(theTranslator->trFile(FALSE,TRUE)+" ");
ol.insertMemberAlign();
QCString path=fd->getPath();
if (Config_getBool(FULL_PATH_NAMES))
{
ol.docify(stripFromPath(path));
}
if (fd->isLinkable())
{
ol.writeObjectLink(fd->getReference(),fd->getOutputFileBase(),QCString(),fd->displayName());
}
else
{
ol.startBold();
ol.docify(fd->displayName());
ol.endBold();
}
ol.endMemberItem(OutputGenerator::MemberItemType::Normal);
if (!fd->briefDescription().isEmpty() && Config_getBool(BRIEF_MEMBER_DESC))
{
ol.startMemberDescription(fd->getOutputFileBase());
ol.generateDoc(briefFile(),briefLine(),fd,nullptr,fd->briefDescription(),FALSE,FALSE,
QCString(),TRUE,FALSE,Config_getBool(MARKDOWN_SUPPORT));
ol.endMemberDescription();
}
ol.endMemberDeclaration(QCString(),QCString());
}
}
ol.endMemberList();
}
}
FileList ModuleDefImpl::getUsedFiles() const
{
FileList result;
for (const auto &mod : m_contributing)
{
FileDef *fd = mod->getFileDef();
if (fd) result.push_back(fd);
}
return result;
}
int ModuleDefImpl::countVisibleMembers() const
{
int count=0;
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Module))
{
if (lde->kind()==LayoutDocEntry::MemberDecl)
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
MemberList *ml = getMemberList(lmd->type);
if (ml)
{
for (const auto &md : *ml)
{
if (md->visibleInIndex())
{
count++;
}
}
}
}
}
else if (lde->kind()==LayoutDocEntry::ModuleClasses)
{
for (const auto &cd : getClasses())
{
if (cd->isLinkableInProject())
{
count++;
}
}
}
else if (lde->kind()==LayoutDocEntry::ModuleConcepts)
{
for (const auto &cd : getConcepts())
{
if (cd->isLinkableInProject())
{
count++;
}
}
}
}
return count;
}
void ModuleDefImpl::writeTagFile(TextStream &tagFile) const
{
if (!isPrimaryInterface() || !isLinkableInProject()) return;
tagFile << " <compound kind=\"module\">\n";
tagFile << " <name>" << convertToXML(name()) << "</name>\n";
const FileDef *fd = getFileDef();
QCString fn = fd ? fd->getOutputFileBase() : getOutputFileBase();
addHtmlExtensionIfMissing(fn);
tagFile << " <filename>" << convertToXML(fn) << "</filename>\n";
#if 0 // at the moment we do not export the members of a module to a tag file.
// We let the project using a tag file directly link to the implementation of the
// symbols (which have the same scope).
//
// When we support linking to a module's interface instead we need to
// export the module's members as well. Then we probably need a way to
// disambiguate/prioritize a link to a module over a link to the implementation,
// for instance by hiding non-exported symbols from the tag file.
for (const auto &lde : LayoutDocManager::instance().docEntries(LayoutDocManager::Group))
{
switch (lde->kind())
{
case LayoutDocEntry::ModuleExports:
{
for (const auto &[modName,importInfo] : m_exportedModules)
{
tagFile << " <export>" << convertToXML(importInfo.importName) << "</export>\n";
}
}
break;
case LayoutDocEntry::ModuleClasses:
{
for (const auto &cd : m_classes)
{
if (cd->isLinkableInProject())
{
tagFile << " <class kind=\"" << cd->compoundTypeString()
<< "\">" << convertToXML(cd->name()) << "</class>\n";
}
}
}
break;
case LayoutDocEntry::ModuleConcepts:
{
for (const auto &cd : m_concepts)
{
if (cd->isLinkableInProject())
{
tagFile << " <concept>" << convertToXML(cd->name())
<< "</concept>\n";
}
}
}
break;
case LayoutDocEntry::ModuleUsedFiles:
{
for (const auto &usedFd : getUsedFiles())
{
if (usedFd->isLinkableInProject())
{
tagFile << " <file>" << convertToXML(usedFd->name()) << "</file>\n";
}
}
}
break;
case LayoutDocEntry::MemberDecl:
{
const LayoutDocEntryMemberDecl *lmd = dynamic_cast<const LayoutDocEntryMemberDecl*>(lde.get());
if (lmd)
{
MemberList * ml = getMemberList(lmd->type);
if (ml)
{
ml->writeTagFile(tagFile,true);
}
}
}
break;
default:
break;
}
}
#endif
QCString idStr = id();
if (!idStr.isEmpty())
{
tagFile << " <clangid>" << convertToXML(idStr) << "</clangid>\n";
}
writeDocAnchorsToTagFile(tagFile);
tagFile << " </compound>\n";
}
//------------------------------------------------------------------------------------------------------------
ModuleDef *toModuleDef(Definition *d)
{
if (d==nullptr) return nullptr;
return (typeid(*d)==typeid(ModuleDefImpl)) ? static_cast<ModuleDef*>(d) : nullptr;
}
const ModuleDef *toModuleDef(const Definition *d)
{
if (d==nullptr) return nullptr;
return (typeid(*d)==typeid(ModuleDefImpl)) ? static_cast<const ModuleDef*>(d) : nullptr;
}
static inline ModuleDefImpl *toModuleDefImpl(ModuleDef *m)
{ return static_cast<ModuleDefImpl*>(m); }
//static inline const ModuleDefImpl *toModuleDefImpl(const ModuleDef *m)
//{ return static_cast<const ModuleDefImpl*>(m); }
static inline ModuleDefImpl *toModuleDefImpl(const std::unique_ptr<ModuleDef> &m)
{ return static_cast<ModuleDefImpl*>(m.get()); }
//------------------------------------------------------------------------------------
bool ModuleLinkedRefMap::declVisible() const
{
bool hideUndocClasses = Config_getBool(HIDE_UNDOC_CLASSES);
for (const auto &mod : *this)
{
bool isLink = mod->isLinkable();
if (isLink || !hideUndocClasses)
{
return true;
}
}
return false;
}
void ModuleLinkedRefMap::writeDeclaration(OutputList &ol,const QCString &header,bool localNames) const
{
bool found=FALSE;
for (const auto &mod : *this)
{
toModuleDefImpl(mod)->writeDeclarationLink(ol,found,header,localNames);
}
if (found) ol.endMemberList();
}
//------------------------------------------------------------------------------------------------------------
struct ModuleManager::Private
{
ModuleLinkedMap moduleFileMap; // file->module mapping
std::unordered_map<std::string,ModuleList> moduleNameMap; // name->module mapping
ImportInfoMap externalImports;
HeaderInfoVector headers;
std::mutex mutex;
};
ModuleManager &ModuleManager::instance()
{
static ModuleManager m;
return m;
}
ModuleManager::ModuleManager() : p(std::make_unique<Private>())
{
}
void ModuleManager::createModuleDef(const QCString &fileName,int line,int column,bool exported,
const QCString &moduleName,const QCString &partitionName)
{
AUTO_TRACE("{}:{}: Found module name='{}' partition='{}' exported='{}'",
fileName,line,moduleName,partitionName,exported);
std::lock_guard lock(p->mutex);
ModuleDef::Type mt = exported ? ModuleDef::Type::Interface : ModuleDef::Type::Implementation;
std::unique_ptr<ModuleDef> modDef = std::make_unique<ModuleDefImpl>(fileName,line,column,moduleName,mt,partitionName);
auto mod = p->moduleFileMap.add(fileName,std::move(modDef));
auto it = p->moduleNameMap.find(moduleName.str());
if (it == p->moduleNameMap.end())
{
ModuleList ml;
ml.push_back(mod);
p->moduleNameMap.emplace(moduleName.str(),ml);
}
else
{
it->second.push_back(mod);
}
}
void ModuleManager::clear()
{
std::lock_guard lock(p->mutex);
p->headers.clear();
p->externalImports.clear();
p->moduleNameMap.clear();
p->moduleFileMap.clear();
}
void ModuleManager::addHeader(const QCString &moduleFile,int line,const QCString &headerName,bool isSystem)
{
AUTO_TRACE("{}:{} headerName={} isSystem={}",moduleFile,line,headerName,isSystem);
std::lock_guard lock(p->mutex);
auto mod = p->moduleFileMap.find(moduleFile);
if (mod)
{
toModuleDefImpl(mod)->addHeader(line,headerName,isSystem);
}
else
{
AUTO_TRACE_ADD("imported header '{}' found in file '{}' that is not a module",headerName,moduleFile);
}
p->headers.emplace_back(moduleFile,headerName,isSystem);
}
void ModuleManager::addImport(const QCString &moduleFile,int line,const QCString &importName,
bool isExported,const QCString &partitionName)
{
AUTO_TRACE("{}:{} importName={},isExported={},partitionName={}",
moduleFile,line,importName,isExported,partitionName);
std::lock_guard lock(p->mutex);
auto mod = p->moduleFileMap.find(moduleFile);
if (mod) // import inside a module
{
AUTO_TRACE_ADD("in module");
toModuleDefImpl(mod)->addImport(line,importName.isEmpty()?mod->name():importName,partitionName,isExported);
}
else // import outside of a module
{
AUTO_TRACE_ADD("outside module");
p->externalImports[moduleFile.str()].emplace_back(nullptr,importName,line,partitionName);
}
}
void ModuleManager::addClassToModule(const Entry *root,ClassDef *cd)
{
std::lock_guard lock(p->mutex);
auto mod = p->moduleFileMap.find(root->fileName);
if (mod)
{
toModuleDefImpl(mod)->addClassToModule(root,cd);
auto cdm = toClassDefMutable(cd);
if (cdm) cdm->setModuleDef(mod);
}
}
void ModuleManager::addConceptToModule(const Entry *root,ConceptDef *cd)
{
std::lock_guard lock(p->mutex);
auto mod = p->moduleFileMap.find(root->fileName);
if (mod)
{
toModuleDefImpl(mod)->addConceptToModule(root,cd);
auto cdm = toConceptDefMutable(cd);
if (cdm) cdm->setModuleDef(mod);
}
}
void ModuleManager::addMemberToModule(const Entry *root,MemberDef *md)
{
std::lock_guard lock(p->mutex);
auto mod = p->moduleFileMap.find(root->fileName);
if (mod && root->exported)
{
toModuleDefImpl(mod)->addMemberToModule(root,md);
auto mdm = toMemberDefMutable(md);
if (mdm) mdm->setModuleDef(mod);
}
}
void ModuleManager::addTagInfo(const QCString &fileName,const QCString &tagFile,const QCString &clangId)
{
std::lock_guard lock(p->mutex);
auto mod = p->moduleFileMap.find(fileName);
if (mod)
{
ModuleDefImpl *modi = toModuleDefImpl(mod);
modi->setReference(tagFile);
modi->setId(clangId);
}
}
void ModuleManager::resolvePartitionsRecursively(ModuleDef *intfMod, ModuleDef *mod)
{
AUTO_TRACE();
for (auto &[partitionFileName,importInfoList] : mod->getImports()) // foreach import
{
for (auto &importInfo : importInfoList)
{
AUTO_TRACE_ADD("partitionFileName={} importName={} partitionName={}",
partitionFileName,importInfo.importName,importInfo.partitionName);
if (importInfo.importName==intfMod->name() && !importInfo.partitionName.isEmpty() &&
importInfo.exported) // that is an exported partition of this module
{
auto it = p->moduleNameMap.find(importInfo.importName.str());
if (it != p->moduleNameMap.end())
{
for (auto importedMod : it->second)
{
if (importedMod->qualifiedName()==importInfo.importName+":"+importInfo.partitionName)
{
AUTO_TRACE_ADD("Interface module {} exports partition {}:{}",
mod->name(),importedMod->name(),importedMod->partitionName());
toModuleDefImpl(intfMod)->addPartition(toModuleDefImpl(importedMod));
toModuleDefImpl(importedMod)->setPrimaryInterface(intfMod);
for (const auto &[partitionFileName_,partitionImportInfoList] : importedMod->getImports())
{
for (const auto &partitionImportInfo : partitionImportInfoList)
{
if (partitionImportInfo.exported && intfMod->name()!=partitionImportInfo.importName)
{
toModuleDefImpl(intfMod)->addExportedModule(partitionImportInfo.importName,partitionImportInfo);
}
}
}
resolvePartitionsRecursively(intfMod,importedMod);
}
}
}
}
}
}
}
void ModuleManager::resolvePartitions()
{
AUTO_TRACE();
for (auto &mod : p->moduleFileMap) // foreach module
{
if (mod->moduleType()==ModuleDef::Type::Interface && mod->partitionName().isEmpty())
{ // that is a primary interface
resolvePartitionsRecursively(mod.get(),mod.get());
}
// copy exported imports to m_exportedModules
for (const auto &[fileName,importInfoList] : mod->getImports())
{
for (const auto &importInfo : importInfoList)
{
if (importInfo.exported && mod->name()!=importInfo.importName)
{
toModuleDefImpl(mod)->addExportedModule(importInfo.importName,importInfo);
}
}
}
// also link the ModuleDef and FileDef together
bool ambig = false;
FileDef *fd = findFileDef(Doxygen::inputNameLinkedMap,mod->getDefFileName(),ambig);
if (fd)
{
fd->setModuleDef(mod.get());
toModuleDefImpl(mod)->setFileDef(fd);
}
}
}
void ModuleManager::resolveImports()
{
AUTO_TRACE();
for (auto &mod : p->moduleFileMap)
{
FileDef *fd = mod->getFileDef();
if (fd)
{
for (const auto &[fileName,importInfoList] : mod->getImports())
{
for (const auto &importInfo : importInfoList)
{
ModuleDef *importedModule = getPrimaryInterface(importInfo.importName);
const FileDef *importedFd = importedModule ? importedModule->getFileDef() : nullptr;
AUTO_TRACE_ADD("module: addIncludeDependency {}->{}:{} fd={}",
mod->qualifiedName(), importInfo.qualifiedName(), importInfo.line, fd?fd->absFilePath():"");
fd->addIncludeDependency(importedFd,importInfo.qualifiedName(),IncludeKind::ImportModule);
}
}
}
}
for (const auto &[fileName,importInfoList] : p->externalImports)
{
for (const auto &importInfo : importInfoList)
{
bool ambig = false;
FileDef *fd = findFileDef(Doxygen::inputNameLinkedMap,QCString(fileName),ambig);
AUTO_TRACE_ADD("externalImport name={} fd={}",fileName,(void*)fd);
if (fd)
{
ModuleDef *mod = getPrimaryInterface(importInfo.importName);
FileDef *importedFd = mod ? mod->getFileDef() : nullptr;
fd->addIncludeDependency(importedFd,importInfo.importName,IncludeKind::ImportModule);
if (importedFd)
{
importedFd->addIncludedByDependency(fd,stripFromPath(QCString(fileName)),IncludeKind::ImportModule);
}
}
}
}
for (const auto &headerInfo : p->headers)
{
bool ambig = false;
FileDef *fd = findFileDef(Doxygen::inputNameLinkedMap,headerInfo.fileName,ambig);
AUTO_TRACE_ADD("header name={} fd={}",headerInfo.fileName,(void*)fd);
if (fd)
{
QCString resolvedHeader = determineAbsoluteIncludeName(headerInfo.fileName,headerInfo.headerName);
FileDef *importFd = findFileDef(Doxygen::inputNameLinkedMap,resolvedHeader,ambig);
fd->addIncludeDependency(importFd, headerInfo.headerName,
headerInfo.isSystem ? IncludeKind::ImportSystem : IncludeKind::ImportLocal);
if (importFd)
{
importFd->addIncludedByDependency(fd,headerInfo.fileName,IncludeKind::ImportModule);
}
}
}
}
void ModuleManager::collectExportedSymbolsRecursively(ModuleDef *intfMod, ModuleDef *partitionMod)
{
AUTO_TRACE("{}: collecting symbols for partition {}",intfMod->qualifiedName(),partitionMod->qualifiedName());
auto intfModImpl = toModuleDefImpl(intfMod);
auto partitionModImpl = toModuleDefImpl(partitionMod);
intfModImpl->mergeSymbolsFrom(partitionModImpl);
}
void ModuleManager::collectExportedSymbols()
{
AUTO_TRACE();
for (auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface()) // that is a primary interface
{
for (auto &[partitionName,partitionMod] : mod->partitions())
{
collectExportedSymbolsRecursively(mod.get(),partitionMod);
}
// collect all files that contribute to this module (e.g. implementation/partition modules)
auto it = p->moduleNameMap.find(mod->name().str());
if (it != p->moduleNameMap.end())
{
for (auto contributingMod : it->second)
{
AUTO_TRACE_ADD(" adding contributing module {} to interface module {} type={} partition={} isPrimaryIntf={}",
contributingMod->qualifiedName(),
mod->name(),
contributingMod->moduleType()==ModuleDef::Type::Interface ? "Interface" : "Implementation",
contributingMod->partitionName(),
contributingMod->isPrimaryInterface());
toModuleDefImpl(mod)->addContributingModule(toModuleDefImpl(contributingMod));
}
}
}
}
}
void ModuleManager::countMembers()
{
for (auto &mod : p->moduleFileMap) // foreach module
{
toModuleDefImpl(mod)->countMembers();
}
}
void ModuleManager::writeDocumentation(OutputList &ol)
{
for (auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface())
{
mod->writeDocumentation(ol);
}
}
}
int ModuleManager::numDocumentedModules() const
{
int count=0;
for (const auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface()) count++;
}
return count;
}
const ModuleLinkedMap &ModuleManager::modules() const
{
return p->moduleFileMap;
}
void ModuleManager::addDocs(const Entry *root)
{
AUTO_TRACE("file={} module={}",root->fileName,root->name);
if (root->doc.isEmpty() && root->brief.isEmpty()) return;
if (root->name.find(':')!=-1)
{
warn(root->fileName,root->startLine,"Ignoring documentation for module partition %s. Please place documentation at the primary module name",
qPrint(root->name));
}
else
{
auto it = p->moduleNameMap.find(root->name.str());
if (it != p->moduleNameMap.end())
{
ModuleDef *mod = getPrimaryInterface(root->name);
if (mod)
{
mod->setDocumentation(root->doc,root->docFile,root->docLine);
mod->setBriefDescription(root->brief,root->briefFile,root->briefLine);
mod->setId(root->id);
mod->setHidden(root->hidden);
mod->setBodySegment(root->startLine,root->bodyLine,root->endBodyLine);
mod->setRefItems(root->sli);
//mod->addSectionsToDefinition(root->anchors);
addModuleToGroups(root,mod);
}
else
{
warn(root->fileName,root->startLine,"Found documentation for module %s but it has no primary interface unit.",qPrint(root->name));
}
}
else
{
warn(root->fileName,root->startLine,"Found documentation for unknown module %s.",qPrint(root->name));
}
}
}
ModuleDef *ModuleManager::getPrimaryInterface(const QCString &moduleName) const
{
auto it = p->moduleNameMap.find(moduleName.str());
if (it != p->moduleNameMap.end())
{
for (const auto &mod : it->second)
{
if (mod->isPrimaryInterface())
{
return mod;
}
}
}
return nullptr;
}
void ModuleManager::addListReferences()
{
for (const auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface()) toModuleDefImpl(mod)->addListReferences();
}
}
void ModuleManager::addMembersToMemberGroup()
{
for (const auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface()) toModuleDefImpl(mod)->addMembersToMemberGroup();
}
}
void ModuleManager::distributeMemberGroupDocumentation()
{
for (const auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface()) toModuleDefImpl(mod)->distributeMemberGroupDocumentation();
}
}
void ModuleManager::findSectionsInDocumentation()
{
for (auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface()) toModuleDefImpl(mod)->findSectionsInDocumentation();
}
}
void ModuleManager::sortMemberLists()
{
for (auto &mod : p->moduleFileMap) // foreach module
{
if (mod->isPrimaryInterface()) toModuleDefImpl(mod)->sortMemberLists();
}
}
| 51,003
|
C++
|
.cpp
| 1,492
| 28.822386
| 144
| 0.668657
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
28,443
|
regex.cpp
|
doxygen_doxygen/src/regex.cpp
|
/******************************************************************************
*
* Copyright (C) 1997-2021 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.
*
*/
#include "regex.h"
#include <cstdint>
#include <vector>
#include <cctype>
#include <cassert>
#include <algorithm>
#define ENABLE_DEBUG 0
#if ENABLE_DEBUG
#define DBG(fmt,...) do { fprintf(stderr,fmt,__VA_ARGS__); } while(0)
#else
#define DBG(fmt,...) do {} while(0)
#endif
namespace reg
{
static inline bool isspace(char c)
{
return c==' ' || c=='\t' || c=='\n' || c=='\r';
}
static inline bool isalpha(char c)
{
return static_cast<unsigned char>(c)>=128 || (c>='a' && c<='z') || (c>='A' && c<='Z');
}
static inline bool isdigit(char c)
{
return c>='0' && c<='9';
}
static inline bool isalnum(char c)
{
return isalpha(c) || isdigit(c);
}
/** Class representing a token in the compiled regular expression token stream.
* A token has a kind and an optional value whose meaning depends on the kind.
* It is also possible to store a (from,to) character range in a token.
*/
class PToken
{
public:
/** The kind of token.
*
* Ranges per bit mask:
* - `0x00FF` from part of a range, except for `0x0000` which is the End marker
* - `0x1FFF` built-in ranges
* - `0x2FFF` user defined ranges
* - `0x4FFF` special operations
* - `0x8000` literal character
*/
enum class Kind : uint16_t
{
End = 0x0000,
WhiteSpace = 0x1001, // \s range [ \t\r\n]
Digit = 0x1002, // \d range [0-9]
Alpha = 0x1003, // \a range [a-z_A-Z\x80-\xFF]
AlphaNum = 0x1004, // \w range [a-Z_A-Z0-9\x80-\xFF]
CharClass = 0x2001, // []
NegCharClass = 0x2002, // [^]
BeginOfLine = 0x4001, // ^
EndOfLine = 0x4002, // $
BeginOfWord = 0x4003, // \<
EndOfWord = 0x4004, // \>
BeginCapture = 0x4005, // (
EndCapture = 0x4006, // )
Any = 0x4007, // .
Star = 0x4008, // *
Optional = 0x4009, // ?
Character = 0x8000 // c
};
/** returns a string representation of the tokens kind (useful for debugging). */
const char *kindStr() const
{
if ((m_rep>>16)>=0x1000 || m_rep==0)
{
switch(static_cast<Kind>((m_rep>>16)))
{
case Kind::End: return "End";
case Kind::Alpha: return "Alpha";
case Kind::AlphaNum: return "AlphaNum";
case Kind::WhiteSpace: return "WhiteSpace";
case Kind::Digit: return "Digit";
case Kind::CharClass: return "CharClass";
case Kind::NegCharClass: return "NegCharClass";
case Kind::Character: return "Character";
case Kind::BeginOfLine: return "BeginOfLine";
case Kind::EndOfLine: return "EndOfLine";
case Kind::BeginOfWord: return "BeginOfWord";
case Kind::EndOfWord: return "EndOfWord";
case Kind::BeginCapture: return "BeginCapture";
case Kind::EndCapture: return "EndCapture";
case Kind::Any: return "Any";
case Kind::Star: return "Star";
case Kind::Optional: return "Optional";
}
}
else
{
return "Range";
}
}
/** Creates a token of kind 'End' */
PToken() : m_rep(0) {}
/** Creates a token of the given kind \a k */
explicit PToken(Kind k) : m_rep(static_cast<uint32_t>(k)<<16) {}
/** Create a token for an ASCII character */
PToken(char c) : m_rep((static_cast<uint32_t>(Kind::Character)<<16) |
static_cast<uint32_t>(c)) {}
/** Create a token for a byte of an UTF-8 character */
PToken(uint16_t v) : m_rep((static_cast<uint32_t>(Kind::Character)<<16) |
static_cast<uint32_t>(v)) {}
/** Create a token representing a range from one character \a from to another character \a to */
PToken(uint16_t from,uint16_t to) : m_rep(static_cast<uint32_t>(from)<<16 | to) {}
/** Sets the value for a token */
void setValue(uint16_t value) { m_rep = (m_rep & 0xFFFF0000) | value; }
/** Returns the kind of the token */
Kind kind() const { return static_cast<Kind>(m_rep>>16); }
/** Returns the 'from' part of the character range. Only valid if this token represents a range */
uint16_t from() const { return m_rep>>16; }
/** Returns the 'to' part of the character range. Only valid if this token represents a range */
uint16_t to() const { return m_rep & 0xFFFF; }
/** Returns the value for this token */
uint16_t value() const { return m_rep & 0xFFFF; }
/** Returns the value for this token as a ASCII character */
char asciiValue() const { return static_cast<char>(m_rep); }
/** Returns true iff this token represents a range of characters */
bool isRange() const { return m_rep!=0 && from()<=to(); }
/** Returns true iff this token is a positive or negative character class */
bool isCharClass() const { return kind()==Kind::CharClass || kind()==Kind::NegCharClass; }
private:
uint32_t m_rep;
};
/** Private members of a regular expression */
class Ex::Private
{
public:
/** Creates the private part */
Private(std::string_view pat) : pattern(pat)
{
data.reserve(100);
}
void compile();
#if ENABLE_DEBUG
void dump();
#endif
bool matchAt(size_t tokenPos,size_t tokenLen,std::string_view str,
Match &match,size_t pos,int level) const;
/** Flag indicating the expression was successfully compiled */
bool error = false;
/** The token stream representing the compiled regular expression. */
std::vector<PToken> data; // compiled pattern
/** The pattern string as passed by the user */
std::string pattern;
};
/** Compiles a regular expression passed as a string into a stream of tokens that can be used for
* efficient searching.
*/
void Ex::Private::compile()
{
error = false;
data.clear();
if (pattern.empty()) return;
const char *start = pattern.c_str();
const char *ps = start;
char c = 0;
int prevTokenPos=-1;
int tokenPos=0;
auto addToken = [&](PToken tok)
{
tokenPos++;
data.emplace_back(tok);
};
auto getNextCharacter = [&]() -> PToken
{
char cs=*ps;
PToken result = PToken(cs);
if (cs=='\\') // escaped character
{
ps++;
cs=*ps;
switch (cs)
{
case 'n': result = PToken('\n'); break;
case 'r': result = PToken('\r'); break;
case 't': result = PToken('\t'); break;
case 's': result = PToken(PToken::Kind::WhiteSpace); break;
case 'a': result = PToken(PToken::Kind::Alpha); break;
case 'w': result = PToken(PToken::Kind::AlphaNum); break;
case 'd': result = PToken(PToken::Kind::Digit); break;
case '<': result = PToken(PToken::Kind::BeginOfWord); break;
case '>': result = PToken(PToken::Kind::EndOfWord); break;
case 'x':
case 'X':
{
uint16_t v=0;
for (int i=0;i<2 && (cs=(*(ps+1)));i++) // 2 hex digits
{
int d = (cs>='a' && cs<='f') ? cs-'a'+10 :
(cs>='A' && cs<='F') ? cs-'A'+10 :
(cs>='0' && cs<='9') ? cs-'0' :
-1;
if (d>=0) { v<<=4; v|=d; ps++; } else break;
}
result = PToken(v);
}
break;
case '\0': ps--; break; // backslash at the end of the pattern
default:
result = PToken(cs);
break;
}
}
return result;
};
while ((c=*ps))
{
switch (c)
{
case '^': // beginning of line (if first character of the pattern)
prevTokenPos = tokenPos;
addToken(ps==start ? PToken(PToken::Kind::BeginOfLine) :
PToken(c));
break;
case '$': // end of the line (if last character of the pattern)
prevTokenPos = tokenPos;
addToken(*(ps+1)=='\0' ? PToken(PToken::Kind::EndOfLine) :
PToken(c));
break;
case '.': // any character
prevTokenPos = tokenPos;
addToken(PToken(PToken::Kind::Any));
break;
case '(': // begin of capture group
prevTokenPos = tokenPos;
addToken(PToken(PToken::Kind::BeginCapture));
break;
case ')': // end of capture group
prevTokenPos = tokenPos;
addToken(PToken(PToken::Kind::EndCapture));
break;
case '[': // character class
{
prevTokenPos = tokenPos;
ps++;
if (*ps==0) { error=true; return; }
bool esc = *ps=='\\';
PToken tok = getNextCharacter();
ps++;
if (!esc && tok.kind()==PToken::Kind::Character &&
tok.asciiValue()=='^') // negated character class
{
addToken(PToken(PToken::Kind::NegCharClass));
if (*ps==0) { error=true; return; }
tok = getNextCharacter();
ps++;
}
else
{
addToken(PToken(PToken::Kind::CharClass));
}
uint16_t numTokens=0;
while ((c=*ps))
{
if (c=='-' && *(ps+1)!=']' && *(ps+1)!=0) // range
{
getNextCharacter();
ps++;
PToken endTok = getNextCharacter();
ps++;
if (tok.value()>endTok.value())
{
addToken(PToken(endTok.value(),tok.value())); // swap start and end
}
else
{
addToken(PToken(tok.value(),endTok.value()));
}
numTokens++;
}
else // single char, from==to
{
if (tok.kind()==PToken::Kind::Character)
{
addToken(PToken(tok.value(),tok.value()));
}
else // special token, add as-is since from>to
{
addToken(tok);
}
numTokens++;
}
if (*ps==0) { error=true; return; } // expected at least a ]
esc = *ps=='\\';
tok = getNextCharacter();
if (!esc && tok.kind()==PToken::Kind::Character &&
tok.value()==static_cast<uint16_t>(']'))
{
break; // end of character class
}
if (*ps==0) { error=true; return; } // no ] found
ps++;
}
// set the value of either NegCharClass or CharClass
data[prevTokenPos].setValue(numTokens);
}
break;
case '*': // 0 or more
case '+': // 1 or more
case '?': // optional: 0 or 1
{
if (prevTokenPos==-1)
{
error=true;
return;
}
switch (data[prevTokenPos].kind())
{
case PToken::Kind::BeginOfLine: // $* or $+ or $?
case PToken::Kind::BeginOfWord: // \<* or \<+ or \<?
case PToken::Kind::EndOfWord: // \>* or \>+ or \>?
case PToken::Kind::Star: // ** or *+ or *?
case PToken::Kind::Optional: // ?* or ?+ or ??
error=true;
return;
default: // ok
break;
}
int ddiff = static_cast<int>(tokenPos-prevTokenPos);
if (*ps=='+') // convert <pat>+ -> <pat><pat>*
{
// turn a sequence of token [T1...Tn] followed by '+' into [T1..Tn T1..Tn T*]
// ddiff=n ^prevTokenPos
data.resize(data.size()+ddiff);
std::copy_n(data.begin()+prevTokenPos,ddiff,data.begin()+tokenPos);
prevTokenPos+=ddiff;
tokenPos+=ddiff;
}
if (data[prevTokenPos].kind()==PToken::Kind::EndCapture)
{
// find the beginning of the capture range
while (prevTokenPos>0 && data[prevTokenPos].kind()!=PToken::Kind::BeginCapture)
{
prevTokenPos--;
}
}
data.insert(data.begin()+prevTokenPos,
c=='?' ? PToken(PToken::Kind::Optional) : PToken(PToken::Kind::Star));
tokenPos++;
addToken(PToken(PToken::Kind::End));
// turn a sequence of tokens [T1 T2 T3] followed by 'T*' or into [T* T1 T2 T3 TEND]
// ^prevTokenPos
// same for 'T?'.
}
break;
default:
prevTokenPos = tokenPos;
addToken(getNextCharacter());
break;
}
ps++;
}
//addToken(PToken(PToken::Kind::End));
}
#if ENABLE_DEBUG
/** Dump the compiled token stream for this regular expression. For debugging purposes. */
void Ex::Private::dump()
{
size_t l = data.size();
size_t i =0;
DBG("==== compiled token stream for pattern '%s' ===\n",pattern.c_str());
while (i<l)
{
DBG("[%s:%04x]\n",data[i].kindStr(),data[i].value());
if (data[i].kind()==PToken::Kind::CharClass || data[i].kind()==PToken::Kind::NegCharClass)
{
uint16_t num = data[i].value();
while (num>0 && i<l)
{
i++;
if (data[i].isRange()) // from-to range
{
DBG("[%04x(%c)-%04x(%c)]\n",data[i].from(),data[i].from(),data[i].to(),data[i].to());
}
else // special character like \n or \s
{
DBG("[%s:%04x]\n",data[i].kindStr(),data[i].value());
}
num--;
}
}
i++;
}
}
#endif
/** Internal matching routine.
* @param tokenPos Offset into the token stream.
* @param tokenLen The length of the token stream.
* @param str The input string to match against.
* @param match The object used to store the matching results.
* @param pos The position in the input string to start with matching
* @param level Recursion level (used for debugging)
*/
bool Ex::Private::matchAt(size_t tokenPos,size_t tokenLen,std::string_view str,Match &match,const size_t pos,int level) const
{
DBG("%d:matchAt(tokenPos=%zu, str='%s', pos=%zu)\n",level,tokenPos,pos<str.length() ? str.substr(pos).c_str() : "",pos);
auto isStartIdChar = [](char c) { return isalpha(c) || c=='_'; };
auto isIdChar = [](char c) { return isalnum(c) || c=='_'; };
auto matchCharClass = [this,isStartIdChar,isIdChar](size_t tp,char c) -> bool
{
PToken tok = data[tp];
bool negate = tok.kind()==PToken::Kind::NegCharClass;
uint16_t numFields = tok.value();
bool found = false;
for (uint16_t i=0;i<numFields;i++)
{
tok = data[++tp];
// first check for built-in ranges
if ((tok.kind()==PToken::Kind::Alpha && isStartIdChar(c)) ||
(tok.kind()==PToken::Kind::AlphaNum && isIdChar(c)) ||
(tok.kind()==PToken::Kind::WhiteSpace && isspace(c)) ||
(tok.kind()==PToken::Kind::Digit && isdigit(c))
)
{
found=true;
break;
}
else // user specified range
{
uint16_t v = static_cast<uint16_t>(c);
if (tok.from()<=v && v<=tok.to())
{
found=true;
break;
}
}
}
DBG("matchCharClass(tp=%zu,c=%c (x%02x))=%d\n",tp,c,c,negate?!found:found);
return negate ? !found : found;
};
size_t index = pos;
enum SequenceType { Star, Optional, OptionalRange };
auto processSequence = [this,&tokenPos,&tokenLen,&index,&str,&matchCharClass,
&isStartIdChar,&isIdChar,&match,&level,&pos](SequenceType type) -> bool
{
size_t startIndex = index;
size_t len = str.length();
PToken tok = data[++tokenPos];
if (tok.kind()==PToken::Kind::Character) // 'x*' -> eat x's
{
char c_tok = tok.asciiValue();
while (index<len && str[index]==c_tok) { index++; if (type==Optional) break; }
tokenPos++;
}
else if (tok.isCharClass()) // '[a-f0-4]* -> eat matching characters
{
while (index<len && matchCharClass(tokenPos,str[index])) { index++; if (type==Optional) break; }
tokenPos+=tok.value()+1; // skip over character ranges + end token
}
else if (tok.kind()==PToken::Kind::Alpha) // '\a*' -> eat start id characters
{
while (index<len && isStartIdChar(str[index])) { index++; if (type==Optional) break; }
tokenPos++;
}
else if (tok.kind()==PToken::Kind::AlphaNum) // '\w*' -> eat id characters
{
while (index<len && isIdChar(str[index])) { index++; if (type==Optional) break; }
tokenPos++;
}
else if (tok.kind()==PToken::Kind::WhiteSpace) // '\s*' -> eat spaces
{
while (index<len && isspace(str[index])) { index++; if (type==Optional) break; }
tokenPos++;
}
else if (tok.kind()==PToken::Kind::Digit) // '\d*' -> eat digits
{
while (index<len && isdigit(str[index])) { index++; if (type==Optional) break; }
tokenPos++;
}
else if (tok.kind()==PToken::Kind::Any) // '.*' -> eat all
{
if (type==Optional) index++; else index = str.length();
tokenPos++;
}
else if (type==OptionalRange && tok.kind()==PToken::Kind::BeginCapture)
{
size_t tokenStart = ++tokenPos;
while (tokenPos<tokenLen && data[tokenPos].kind()!=PToken::Kind::EndCapture) { tokenPos++; }
Match rangeMatch;
rangeMatch.init(str);
bool found = matchAt(tokenStart,tokenPos,str,rangeMatch,index,level+1);
if (found)
{
index+=rangeMatch.length(); // (abc)? matches -> eat all
}
tokenPos++; // skip over EndCapture
}
tokenPos++; // skip over end marker
while (index>=startIndex)
{
// pattern 'x*xy' should match 'xy' and 'xxxxy'
bool found = matchAt(tokenPos,tokenLen,str,match,index,level+1);
if (found)
{
match.setMatch(pos,index-pos+match.length());
return true;
}
if (index==0) break;
index--;
}
return false;
};
while (tokenPos<tokenLen)
{
PToken tok = data[tokenPos];
DBG("loop tokenPos=%zu token=%s\n",tokenPos,tok.kindStr());
if (tok.kind()==PToken::Kind::Character) // match literal character
{
char c_tok = tok.asciiValue();
if (index>=str.length() || str[index]!=c_tok) return false; // end of string, or non matching char
index++,tokenPos++;
}
else if (tok.isCharClass())
{
if (index>=str.length() || !matchCharClass(tokenPos,str[index])) return false;
index++,tokenPos+=tok.value()+1; // skip over character ranges + end token
}
else
{
switch (tok.kind())
{
case PToken::Kind::Alpha:
if (index>=str.length() || !isStartIdChar(str[index])) return false;
index++;
break;
case PToken::Kind::AlphaNum:
if (index>=str.length() || !isIdChar(str[index])) return false;
index++;
break;
case PToken::Kind::WhiteSpace:
if (index>=str.length() || !isspace(str[index])) return false;
index++;
break;
case PToken::Kind::Digit:
if (index>=str.length() || !isdigit(str[index])) return false;
index++;
break;
case PToken::Kind::BeginOfLine:
if (index!=pos) return false;
break;
case PToken::Kind::EndOfLine:
if (index<str.length()) return false;
break;
case PToken::Kind::BeginOfWord:
DBG("BeginOfWord: index=%zu isIdChar(%c)=%d prev.isIdChar(%c)=%d\n",
index,str[index],isIdChar(str[index]),
index>0?str[index]-1:0,
index>0?isIdChar(str[index-1]):-1);
if (index>=str.length() ||
!isIdChar(str[index]) ||
(index>0 && isIdChar(str[index-1]))) return false;
break;
case PToken::Kind::EndOfWord:
DBG("EndOfWord: index=%zu pos=%zu idIdChar(%c)=%d prev.isIsChar(%c)=%d\n",
index,pos,str[index],isIdChar(str[index]),
index==0 ? 0 : str[index-1],
index==0 ? -1 : isIdChar(str[index-1]));
if (index<str.length() &&
(isIdChar(str[index]) || index==0 || !isIdChar(str[index-1]))) return false;
break;
case PToken::Kind::BeginCapture:
DBG("BeginCapture(%zu)\n",index);
match.startCapture(index);
break;
case PToken::Kind::EndCapture:
DBG("EndCapture(%zu)\n",index);
match.endCapture(index);
break;
case PToken::Kind::Any:
if (index>=str.length()) return false;
index++;
break;
case PToken::Kind::Star:
return processSequence(Star);
case PToken::Kind::Optional:
if (tokenPos<tokenLen-1 && data[tokenPos+1].kind()==PToken::Kind::BeginCapture)
{
return processSequence(OptionalRange); // (...)?
}
else
{
return processSequence(Optional); // x?
}
default:
return false;
}
tokenPos++;
}
}
match.setMatch(pos,index-pos);
return true;
}
static std::string wildcard2regex(std::string_view pattern)
{
std::string result="^"; // match start of input
result.reserve(pattern.length());
for (size_t i=0;i<pattern.length();i++)
{
char c=pattern[i];
switch(c)
{
case '*':
result+=".*";
break; // '*' => '.*'
case '?':
result+='.';
break; // '?' => '.'
case '.':
case '+':
case '\\':
case '$':
case '^':
case '(':
case ')':
result+='\\'; result+=c; // escape
break;
case '[':
if (i<pattern.length()-1 && pattern[i+1]=='^') // don't escape ^ after [
{
result+="[^";
i++;
}
else
{
result+=c;
}
break;
default: // just copy
result+=c;
break;
}
}
result+='$'; // match end of input
return result;
}
Ex::Ex(std::string_view pattern, Mode mode)
: p(std::make_unique<Private>(mode==Mode::RegEx ? pattern : wildcard2regex(pattern)))
{
p->compile();
#if ENABLE_DEBUG
p->dump();
assert(!p->error);
#endif
}
Ex::~Ex() = default;
bool Ex::match(std::string_view str,Match &match,size_t pos) const
{
bool found=false;
if (p->data.size()==0 || p->error) return found;
match.init(str);
PToken tok = p->data[0];
if (tok.kind()==PToken::Kind::BeginOfLine) // only test match at the given position
{
found = p->matchAt(0,p->data.size(),str,match,pos,0);
}
else
{
if (tok.kind()==PToken::Kind::Character) // search for the start character
{
size_t index = str.find(tok.asciiValue(),pos);
if (index==std::string::npos)
{
DBG("Ex::match(str='%s',pos=%zu)=false (no start char '%c')\n",str.c_str(),pos,tok.asciiValue());
return false;
}
DBG("pos=%zu str='%s' char='%c' index=%zu\n",index,str.c_str(),tok.asciiValue(),index);
pos=index;
}
while (pos<str.length()) // search for a match starting at pos
{
found = p->matchAt(0,p->data.size(),str,match,pos,0);
if (found) break;
pos++;
}
}
DBG("Ex::match(str='%s',pos=%zu)=%d\n",str.c_str(),pos,found);
return found;
}
bool Ex::isValid() const
{
return !p->pattern.empty() && !p->error;
}
//----------------------------------------------------------------------------------------
bool search(std::string_view str,Match &match,const Ex &re,size_t pos)
{
return re.match(str,match,pos);
}
bool search(std::string_view str,const Ex &re,size_t pos)
{
Match match;
return re.match(str,match,pos);
}
bool match(std::string_view str,Match &match,const Ex &re)
{
return re.match(str,match,0) && match.position()==0 && match.length()==str.length();
}
bool match(std::string_view str,const Ex &re)
{
Match match;
return re.match(str,match,0) && match.position()==0 && match.length()==str.length();
}
std::string replace(std::string_view str,const Ex &re,std::string_view replacement)
{
std::string result;
Match match;
size_t p=0;
while (re.match(str,match,p))
{
size_t i=match.position();
size_t l=match.length();
if (i>p) result+=str.substr(p,i-p);
result+=replacement;
p=i+l;
}
if (p<str.length()) result+=str.substr(p);
return result;
}
}
| 25,359
|
C++
|
.cpp
| 737
| 27.058345
| 125
| 0.538621
|
doxygen/doxygen
| 5,592
| 1,269
| 1,920
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.