dot.cpp 141 KB
Newer Older
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1 2
/*****************************************************************************
 *
3
 * 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4 5
 *
 *
Dimitri van Heesch's avatar
Dimitri van Heesch committed
6
 * Copyright (C) 1997-2013 by Dimitri van Heesch.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
7 8 9 10 11 12 13
 *
 * 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.
 *
Dimitri van Heesch's avatar
Dimitri van Heesch committed
14 15
 * Documents produced by Doxygen are derivative works derived from the
 * input used in their production; they are not affected by this license.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
16 17 18
 *
 */

19 20 21 22 23
#ifdef _WIN32
#include <windows.h>
#define BITMAP W_BITMAP
#endif

Dimitri van Heesch's avatar
Dimitri van Heesch committed
24 25
#include <stdlib.h>

26 27 28 29 30 31 32
#include <qdir.h>
#include <qfile.h>
#include <qqueue.h>
#include <qthread.h>
#include <qmutex.h>
#include <qwaitcondition.h>

Dimitri van Heesch's avatar
Dimitri van Heesch committed
33 34 35
#include "dot.h"
#include "doxygen.h"
#include "message.h"
36
#include "util.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
37
#include "config.h"
38
#include "language.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
39
#include "defargs.h"
40
#include "docparser.h"
41
#include "debug.h"
42
#include "pagedef.h"
43
#include "portable.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
44
#include "dirdef.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
45
#include "vhdldocgen.h"
46
#include "ftextstream.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
47
#include "md5.h"
48 49 50 51 52 53 54
#include "memberlist.h"
#include "groupdef.h"
#include "classlist.h"
#include "filename.h"
#include "namespacedef.h"
#include "memberdef.h"
#include "membergroup.h"
Dimitri van Heesch's avatar
Dimitri van Heesch committed
55

56
#define MAP_CMD "cmapx"
57

58
//#define FONTNAME "Helvetica"
59
#define FONTNAME getDotFontName()
Dimitri van Heesch's avatar
Dimitri van Heesch committed
60
#define FONTSIZE getDotFontSize()
Dimitri van Heesch's avatar
Dimitri van Heesch committed
61

Dimitri van Heesch's avatar
Dimitri van Heesch committed
62 63
//--------------------------------------------------------------------

64 65
static const char svgZoomHeader[] =
"<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)\">\n"
66 67 68 69 70 71
"<style type=\"text/css\"><![CDATA[\n"
".edge:hover path { stroke: red; }\n"
".edge:hover polygon { stroke: red; fill: red; }\n"
"]]></style>\n"
"<script type=\"text/javascript\"><![CDATA[\n"
"var edges = document.getElementsByTagName('g');\n"
72 73 74 75 76
"if (edges && edges.length) {\n"
"  for (var i=0;i<edges.length;i++) {\n"
"    if (edges[i].id.substr(0,4)=='edge') {\n"
"      edges[i].setAttribute('class','edge');\n"
"    }\n"
77 78 79
"  }\n"
"}\n"
"]]></script>\n"
80 81
"        <defs>\n"
"                <circle id=\"rim\" cx=\"0\" cy=\"0\" r=\"7\"/>\n"
82
"                <circle id=\"rim2\" cx=\"0\" cy=\"0\" r=\"3.5\"/>\n"
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
"                <g id=\"zoomPlus\">\n"
"                        <use xlink:href=\"#rim\" fill=\"#404040\">\n"
"                                <set attributeName=\"fill\" to=\"#808080\" begin=\"zoomplus.mouseover\" end=\"zoomplus.mouseout\"/>\n"
"                        </use>\n"
"                        <path d=\"M-4,0h8M0,-4v8\" fill=\"none\" stroke=\"white\" stroke-width=\"1.5\" pointer-events=\"none\"/>\n"
"                </g>\n"
"                <g id=\"zoomMin\">\n"
"                        <use xlink:href=\"#rim\" fill=\"#404040\">\n"
"                                <set attributeName=\"fill\" to=\"#808080\" begin=\"zoomminus.mouseover\" end=\"zoomminus.mouseout\"/>\n"
"                        </use>\n"
"                        <path d=\"M-4,0h8\" fill=\"none\" stroke=\"white\" stroke-width=\"1.5\" pointer-events=\"none\"/>\n"
"                </g>\n"
"                <g id=\"dirArrow\">\n"
"                        <path fill=\"none\" stroke=\"white\" stroke-width=\"1.5\" d=\"M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5\"/>\n"
"                </g>\n"
98 99 100 101 102
"               <g id=\"resetDef\">\n"
"                       <use xlink:href=\"#rim2\" fill=\"#404040\">\n"
"                               <set attributeName=\"fill\" to=\"#808080\" begin=\"reset.mouseover\" end=\"reset.mouseout\"/>\n"
"                       </use>\n"
"               </g>\n"
103 104 105 106 107 108
"        </defs>\n"
"\n"
"<script type=\"text/javascript\">\n"
;

static const char svgZoomFooter[] =
109
// navigation panel
110 111
"        <g id=\"navigator\" transform=\"translate(0 0)\" fill=\"#404254\">\n"
"                <rect fill=\"#f2f5e9\" fill-opacity=\"0.5\" stroke=\"#606060\" stroke-width=\".5\" x=\"0\" y=\"0\" width=\"60\" height=\"60\"/>\n"
112
// zoom in
113
"                <use id=\"zoomplus\" xlink:href=\"#zoomPlus\" x=\"17\" y=\"9\" onmousedown=\"handleZoom(evt,'in')\"/>\n"
114
// zoom out
115
"                <use id=\"zoomminus\" xlink:href=\"#zoomMin\" x=\"42\" y=\"9\" onmousedown=\"handleZoom(evt,'out')\"/>\n"
116
// reset zoom
117
"                <use id=\"reset\" xlink:href=\"#resetDef\" x=\"30\" y=\"36\" onmousedown=\"handleReset()\"/>\n"
118
// arrow up
119 120 121 122 123 124
"                <g id=\"arrowUp\" xlink:href=\"#dirArrow\" transform=\"translate(30 24)\" onmousedown=\"handlePan(0,-1)\">\n"
"                  <use xlink:href=\"#rim\" fill=\"#404040\">\n"
"                        <set attributeName=\"fill\" to=\"#808080\" begin=\"arrowUp.mouseover\" end=\"arrowUp.mouseout\"/>\n"
"                  </use>\n"
"                  <path fill=\"none\" stroke=\"white\" stroke-width=\"1.5\" d=\"M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5\"/>\n"
"                </g>\n"
125
// arrow right
126 127 128 129 130 131
"                <g id=\"arrowRight\" xlink:href=\"#dirArrow\" transform=\"rotate(90) translate(36 -43)\" onmousedown=\"handlePan(1,0)\">\n"
"                  <use xlink:href=\"#rim\" fill=\"#404040\">\n"
"                        <set attributeName=\"fill\" to=\"#808080\" begin=\"arrowRight.mouseover\" end=\"arrowRight.mouseout\"/>\n"
"                  </use>\n"
"                  <path fill=\"none\" stroke=\"white\" stroke-width=\"1.5\" d=\"M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5\"/>\n"
"                </g>\n"
132
// arrow down
133 134 135 136 137 138
"                <g id=\"arrowDown\" xlink:href=\"#dirArrow\" transform=\"rotate(180) translate(-30 -48)\" onmousedown=\"handlePan(0,1)\">\n"
"                  <use xlink:href=\"#rim\" fill=\"#404040\">\n"
"                        <set attributeName=\"fill\" to=\"#808080\" begin=\"arrowDown.mouseover\" end=\"arrowDown.mouseout\"/>\n"
"                  </use>\n"
"                  <path fill=\"none\" stroke=\"white\" stroke-width=\"1.5\" d=\"M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5\"/>\n"
"                </g>\n"
139
// arrow left
140 141 142 143 144 145 146
"                <g id=\"arrowLeft\" xlink:href=\"#dirArrow\" transform=\"rotate(270) translate(-36 17)\" onmousedown=\"handlePan(-1,0)\">\n"
"                  <use xlink:href=\"#rim\" fill=\"#404040\">\n"
"                        <set attributeName=\"fill\" to=\"#808080\" begin=\"arrowLeft.mouseover\" end=\"arrowLeft.mouseout\"/>\n"
"                  </use>\n"
"                  <path fill=\"none\" stroke=\"white\" stroke-width=\"1.5\" d=\"M0,-3.0v7 M-2.5,-0.5L0,-3.0L2.5,-0.5\"/>\n"
"                </g>\n"
"        </g>\n"
147
// link to orginial SVG
Dimitri van Heesch's avatar
Dimitri van Heesch committed
148 149 150 151 152 153 154 155 156 157 158
"        <svg viewBox=\"0 0 15 15\" width=\"100%\" height=\"30px\" preserveAspectRatio=\"xMaxYMin meet\">\n"
"         <g id=\"arrow_out\" transform=\"scale(0.3 0.3)\">\n"
"          <a xlink:href=\"$orgname\" target=\"_base\">\n"
"           <rect id=\"button\" ry=\"5\" rx=\"5\" y=\"6\" x=\"6\" height=\"38\" width=\"38\"\n"
"                fill=\"#f2f5e9\" fill-opacity=\"0.5\" stroke=\"#606060\" stroke-width=\"1.0\"/>\n"
"           <path id=\"arrow\"\n"
"             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\"\n"
"             style=\"fill:#404040;\"/>\n"
"          </a>\n"
"         </g>\n"
"        </svg>\n"
159 160 161 162 163
"</svg>\n"
;

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

164
static const int maxCmdLine = 40960;
165

Dimitri van Heesch's avatar
Dimitri van Heesch committed
166
/*! mapping from protection levels to color names */
167
static const char *normalEdgeColorMap[] =
Dimitri van Heesch's avatar
Dimitri van Heesch committed
168 169 170 171 172
{
  "midnightblue",  // Public
  "darkgreen",     // Protected
  "firebrick4",    // Private
  "darkorchid3",   // "use" relation
173 174
  "grey75",        // Undocumented
  "orange"         // template relation
Dimitri van Heesch's avatar
Dimitri van Heesch committed
175 176
};

177
static const char *normalArrowStyleMap[] =
178 179 180 181 182 183 184 185
{
  "empty",         // Public
  "empty",         // Protected
  "empty",         // Private
  "open",          // "use" relation
  0,               // Undocumented
  0                // template relation
};
186

187
static const char *normalEdgeStyleMap[] =
Dimitri van Heesch's avatar
Dimitri van Heesch committed
188 189 190 191 192
{
  "solid",         // inheritance
  "dashed"         // usage
};

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
static const char *umlEdgeColorMap[] =
{
  "midnightblue",  // Public
  "darkgreen",     // Protected
  "firebrick4",    // Private
  "grey25",        // "use" relation
  "grey75",        // Undocumented
  "orange"         // template relation
};

static const char *umlArrowStyleMap[] =
{
  "onormal",         // Public
  "onormal",         // Protected
  "onormal",         // Private
  "odiamond",        // "use" relation
  0,                 // Undocumented
  0                  // template relation
};

static const char *umlEdgeStyleMap[] =
{
  "solid",         // inheritance
  "solid"          // usage
};

Dimitri van Heesch's avatar
Dimitri van Heesch committed
219
/** Helper struct holding the properties of a edge in a dot graph. */
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
struct EdgeProperties
{
  const char * const *edgeColorMap;
  const char * const *arrowStyleMap;
  const char * const *edgeStyleMap;
};

static EdgeProperties normalEdgeProps = 
{
  normalEdgeColorMap, normalArrowStyleMap, normalEdgeStyleMap
};

static EdgeProperties umlEdgeProps =
{
  umlEdgeColorMap, umlArrowStyleMap, umlEdgeStyleMap
};


238 239 240
static QCString getDotFontName()
{
  static QCString dotFontName = Config_getString("DOT_FONTNAME");
241 242 243 244 245
  if (dotFontName.isEmpty()) 
  {
    //dotFontName="FreeSans.ttf";
    dotFontName="Helvetica";
  }
246 247 248
  return dotFontName;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
249 250 251 252 253 254 255
static int getDotFontSize()
{
  static int dotFontSize = Config_getInt("DOT_FONTSIZE");
  if (dotFontSize<4) dotFontSize=4;
  return dotFontSize;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
256
static void writeGraphHeader(FTextStream &t,const QCString &title=QCString())
257
{
258
  static bool interactiveSVG = Config_getBool("INTERACTIVE_SVG");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
259 260 261 262 263 264 265 266 267 268
  t << "digraph ";
  if (title.isEmpty())
  {
    t << "\"Dot Graph\"";
  }
  else
  {
    t << "\"" << convertToXML(title) << "\"";
  }
  t << endl << "{" << endl;
269 270 271 272 273
  if (interactiveSVG) // insert a comment to force regeneration when this
                      // option is toggled
  {
    t << " // INTERACTIVE_SVG=YES\n";
  }
274 275 276 277
  if (Config_getBool("DOT_TRANSPARENT"))
  {
    t << "  bgcolor=\"transparent\";" << endl;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
278 279 280 281 282 283
  t << "  edge [fontname=\"" << FONTNAME << "\","
       "fontsize=\"" << FONTSIZE << "\","
       "labelfontname=\"" << FONTNAME << "\","
       "labelfontsize=\"" << FONTSIZE << "\"];\n";
  t << "  node [fontname=\"" << FONTNAME << "\","
       "fontsize=\"" << FONTSIZE << "\",shape=record];\n";
284 285
}

286
static void writeGraphFooter(FTextStream &t)
287 288 289 290
{
  t << "}" << endl;
}

291 292 293 294 295
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";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
296
  //bool isXLink=FALSE;
297 298 299 300 301 302 303
  int len = 6;
  int indexS = buf.find("href=\""), indexE;
  if (indexS>5 && buf.find("xlink:href=\"")!=-1) // XLink href (for SVG)
  {
    indexS-=6;
    len+=6;
    href.prepend("xlink:");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
304
    //isXLink=TRUE;
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
  }
  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.left(5)=="\\ref " || link.left(5)=="@ref ") // \ref url
      {
        result=href+"=\"";
        // fake ref node to resolve the url
        DocRef *df = new DocRef( (DocNode*) 0, link.mid(5), context );
        result+=externalRef(relPath,df->ref(),TRUE);
        if (!df->file().isEmpty())  
          result += df->file().data() + Doxygen::htmlFileExtension;
        if (!df->anchor().isEmpty()) 
          result += "#" + df->anchor();
        delete df;
        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() + externalRef(relPath,ref,FALSE);
        }
        result+= href+"=\"";
        result+=externalRef(relPath,ref,TRUE);
        result+= url + "\"";
      }
      else // should not happen, but handle properly anyway
      {
        result = href+"=\"" + link + "\"";
      }
    }
    if (!target.isEmpty())
    {
      result+=" target=\""+target+"\"";
    }
    QCString leftPart = buf.left(indexS);
    QCString rightPart = buf.mid(indexE+1);
    return leftPart + result + rightPart;
  }
  else
  {
    return buf;
  }
}

364 365 366 367 368
/*! 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).
369 370 371
 *  \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
372
 *                 map file was found
373
 *  \returns TRUE if successful.
374
 */
375
static bool convertMapFile(FTextStream &t,const char *mapName,
376
                           const QCString relPath, bool urlOnly=FALSE,
377
                           const QCString &context=QCString())
378 379 380 381
{
  QFile f(mapName);
  if (!f.open(IO_ReadOnly)) 
  {
382
    err("problems opening map file %s for inclusion in the docs!\n"
383 384
        "If you installed Graphviz/dot after a previous failing run, \n"
        "try deleting the output directory and rerun doxygen.\n",mapName);
385 386 387 388 389 390 391 392 393
    return FALSE;
  }
  const int maxLineLen=10240;
  while (!f.atEnd()) // foreach line
  {
    QCString buf(maxLineLen);
    int numBytes = f.readLine(buf.data(),maxLineLen);
    buf[numBytes-1]='\0';

394
    if (buf.left(5)=="<area")
395
    {
396
      t << replaceRef(buf,relPath,urlOnly,context);
397 398 399 400
    }
  }
  return TRUE;
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
401

402
static QArray<int> s_newNumber;
403 404 405 406 407 408 409 410 411 412
static int s_max_newNumber=0;

inline int reNumberNode(int number, bool doReNumbering)
{
  if (!doReNumbering) 
  {
    return number;
  } 
  else 
  {
413
    int s = s_newNumber.size();
414 415 416 417 418 419 420 421
    if (number>=s) 
    {
      int ns=0;
      ns = s * 3 / 2 + 5; // new size
      if (number>=ns) // number still doesn't fit
      {
        ns = number * 3 / 2 + 5;
      }
422
      s_newNumber.resize(ns);
423 424
      for (int i=s;i<ns;i++) // clear new part of the array
      {
425
        s_newNumber.at(i)=0;
426 427
      }
    }
428
    int i = s_newNumber.at(number);
429 430 431
    if (i == 0) // not yet mapped
    {
      i = ++s_max_newNumber; // start from 1
432
      s_newNumber.at(number) = i;
433 434 435 436 437 438 439 440
    }
    return i;
  }
}

static void resetReNumbering() 
{
  s_max_newNumber=0;
441
  s_newNumber.resize(s_max_newNumber);
442 443
}

444 445 446 447 448 449 450
static QCString g_dotFontPath;

static void setDotFontPath(const char *path)
{
  ASSERT(g_dotFontPath.isEmpty());
  g_dotFontPath = portable_getenv("DOTFONTPATH");
  QCString newFontPath = Config_getString("DOT_FONTPATH");
451 452
  QCString spath = path;
  if (!newFontPath.isEmpty() && !spath.isEmpty())
453
  {
454
    newFontPath.prepend(spath+portable_pathListSeparator());
455
  }
456
  else if (newFontPath.isEmpty() && !spath.isEmpty())
457 458 459 460 461 462 463 464 465 466 467 468 469
  {
    newFontPath=path;
  }
  else
  {
    portable_unsetenv("DOTFONTPATH");
    return;
  }
  portable_setenv("DOTFONTPATH",newFontPath);
}

static void unsetDotFontPath()
{
470 471 472 473 474 475 476 477
  if (g_dotFontPath.isEmpty())
  {
    portable_unsetenv("DOTFONTPATH");
  }
  else
  {
    portable_setenv("DOTFONTPATH",g_dotFontPath);
  }
478 479 480
  g_dotFontPath="";
}

481
static bool readBoundingBox(const char *fileName,int *width,int *height,bool isEps)
482
{
483
  QCString bb = isEps ? QCString("%%PageBoundingBox:") : QCString("/MediaBox [");
484
  QFile f(fileName);
485 486 487 488 489
  if (!f.open(IO_ReadOnly|IO_Raw)) 
  {
    //printf("readBoundingBox: could not open %s\n",fileName);
    return FALSE;
  }
490 491 492 493
  const int maxLineLen=1024;
  char buf[maxLineLen];
  while (!f.atEnd())
  {
494
    int numBytes = f.readLine(buf,maxLineLen-1); // read line
495
    if (numBytes>0)
496
    {
497
      buf[numBytes]='\0';
498 499
      const char *p = strstr(buf,bb);
      if (p) // found PageBoundingBox or /MediaBox string
Dimitri van Heesch's avatar
Dimitri van Heesch committed
500
      {
501
        int x,y;
502
        if (sscanf(p+bb.length(),"%d %d %d %d",&x,&y,width,height)!=4)
503 504 505 506 507
        {
          //printf("readBoundingBox sscanf fail\n");
          return FALSE;
        }
        return TRUE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
508
      }
509 510 511 512 513
    }
    else // read error!
    {
      //printf("Read error %d!\n",numBytes);
      return FALSE;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
514 515
    }
  }
516
  err("Failed to extract bounding box from generated diagram file %s\n",fileName);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
517 518 519
  return FALSE;
}

520 521 522
static bool writeVecGfxFigure(FTextStream &out,const QCString &baseName,
                           const QCString &figureName)
{
523
  int width=400,height=550;
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  static bool usePdfLatex = Config_getBool("USE_PDFLATEX");
  if (usePdfLatex)
  {
    if (!readBoundingBox(figureName+".pdf",&width,&height,FALSE))
    {
      //printf("writeVecGfxFigure()=0\n");
      return FALSE;
    }
  }
  else
  {
    if (!readBoundingBox(figureName+".eps",&width,&height,TRUE))
    {
      //printf("writeVecGfxFigure()=0\n");
      return FALSE;
    }
  }
  //printf("Got PDF/EPS size %d,%d\n",width,height);
542 543
  int maxWidth  = 350;  /* approx. page width in points, excl. margins */
  int maxHeight = 550;  /* approx. page height in points, excl. margins */ 
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  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;
}

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
// extract size from a dot generated SVG file
static bool readSVGSize(const QCString &fileName,int *width,int *height)
{
  bool found=FALSE;
  QFile f(fileName);
  if (!f.open(IO_ReadOnly))
  {
    return FALSE;
  }
  const int maxLineLen=4096;
  char buf[maxLineLen];
  while (!f.atEnd() && !found)
  {
    int numBytes = f.readLine(buf,maxLineLen-1); // read line
    if (numBytes>0)
    {
      buf[numBytes]='\0';
Dimitri van Heesch's avatar
Dimitri van Heesch committed
590
      if (qstrncmp(buf,"<!--zoomable ",13)==0)
591
      {
592 593
        *width=-1;
        *height=-1;
594 595
        sscanf(buf,"<!--zoomable %d",height);
        //printf("Found zoomable for %s!\n",fileName.data());
596 597 598 599 600
        found=TRUE;
      }
      else if (sscanf(buf,"<svg width=\"%dpt\" height=\"%dpt\"",width,height)==2)
      {
        //printf("Found fixed size %dx%d for %s!\n",*width,*height,fileName.data());
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
        found=TRUE;
      }
    }
    else // read error!
    {
      //printf("Read error %d!\n",numBytes);
      return FALSE;
    }
  }
  return TRUE;
}

static void writeSVGNotSupported(FTextStream &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 does so if possible.
// return FALSE if not possible (for instance because the SVG file is not yet generated).
static bool writeSVGFigureLink(FTextStream &out,const QCString &relPath,
                           const QCString &baseName,const QCString &absImgName)
{
623
  int width=600,height=600;
624 625 626 627
  if (!readSVGSize(absImgName,&width,&height))
  {
    return FALSE;
  }
628
  if (width==-1)
629
  {
630
    if (height<=60) 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
631
      height=300;
632
    else 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
633
      height+=300; // add some extra space for zooming
634
    if (height>600) height=600; // clip to maximum height of 600 pixels
635 636 637 638
    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=\"" 
639
        << relPath << baseName << ".svg\" width=\"100%\" height=\"" << height << "\">";
640 641 642
  }
  else
  {
643 644 645
    //out << "<object type=\"image/svg+xml\" data=\"" 
    //out << "<embed type=\"image/svg+xml\" src=\"" 
    out << "<iframe scrolling=\"no\" frameborder=\"0\" src=\"" 
646 647
        << relPath << baseName << ".svg\" width=\"" 
        << ((width*96+48)/72) << "\" height=\"" 
648
        << ((height*96+48)/72) << "\">";
649
  }
650
  writeSVGNotSupported(out);
651 652
  //out << "</object>";
  //out << "</embed>";
653
  out << "</iframe>";
654
  if (width==-1)
655 656 657
  {
    out << "</div>";
  }
658 659 660 661

  return TRUE;
}

662 663 664 665 666 667
// since dot silently reproduces the input file when it does not
// support the PNG format, we need to check the result.
static void checkDotResult(const QCString &imgName)
{
  if (Config_getEnum("DOT_IMAGE_FORMAT")=="png")
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
668 669
    FILE *f = fopen(imgName,"rb");
    if (f)
670 671
    {
      char data[4];
Dimitri van Heesch's avatar
Dimitri van Heesch committed
672
      if (fread(data,1,4,f)==4)
673 674 675
      {
        if (!(data[1]=='P' && data[2]=='N' && data[3]=='G'))
        {
676
          err("Image `%s' produced by dot is not a valid PNG!\n"
677 678 679 680 681 682 683 684
              "You should either select a different format "
              "(DOT_IMAGE_FORMAT in the config file) or install a more "
              "recent version of graphviz (1.7+)\n",imgName.data()
             );
        }
      }
      else
      {
685
        err("Could not read image `%s' generated by dot!\n",imgName.data());
686
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
687
      fclose(f);
688 689 690
    }
    else
    {
691
      err("Could not open image `%s' generated by dot!\n",imgName.data());
692 693 694 695
    }
  }
}

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
static bool insertMapFile(FTextStream &out,const QCString &mapFile,
                          const QCString &relPath,const QCString &mapLabel)
{
  QFileInfo fi(mapFile);
  if (fi.exists() && fi.size()>0) // reuse existing map file
  {
    QGString tmpstr;
    FTextStream tmpout(&tmpstr);
    convertMapFile(tmpout,mapFile,relPath);
    if (!tmpstr.isEmpty())
    {
      out << "<map name=\"" << mapLabel << "\" id=\"" << mapLabel << "\">" << endl;
      out << tmpstr;
      out << "</map>" << endl;
    }
    return TRUE;
  }
  return FALSE; // no map file yet, need to generate it
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
716 717 718 719 720 721 722 723 724 725 726
static void removeDotGraph(const QCString &dotName)
{
  static bool dotCleanUp = Config_getBool("DOT_CLEANUP"); 
  if (dotCleanUp)
  {
    QDir d;
    d.remove(dotName);
  }
}


727

728 729 730 731 732
/*! Checks if a file "baseName".md5 exists. If so the contents
 *  are compared with \a md5. If equal FALSE is returned. If the .md5
 *  file does not exist or its contents are not equal to \a md5, 
 *  a new .md5 is generated with the \a md5 string as contents.
 */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
733 734
static bool checkAndUpdateMd5Signature(const QCString &baseName,
            const QCString &md5)
735 736 737 738 739 740 741
{
  QFile f(baseName+".md5");
  if (f.open(IO_ReadOnly))
  {
    // read checksum
    QCString md5stored(33);
    int bytesRead=f.readBlock(md5stored.data(),32);
742
    md5stored[32]='\0';
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
    // compare checksum
    if (bytesRead==32 && md5==md5stored)
    {
      // bail out if equal
      return FALSE;
    }
  }
  f.close();
  // create checksum file
  if (f.open(IO_WriteOnly))
  {
    f.writeBlock(md5.data(),32); 
    f.close();
  }
  return TRUE;
}

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
static bool checkDeliverables(const QCString &file1,
                              const QCString &file2=QCString())
{
  bool file1Ok = TRUE;
  bool file2Ok = TRUE;
  if (!file1.isEmpty())
  {
    QFileInfo fi(file1);
    file1Ok = (fi.exists() && fi.size()>0);
  }
  if (!file2.isEmpty())
  {
    QFileInfo fi(file2);
    file2Ok = (fi.exists() && fi.size()>0);
  }
  return file1Ok && file2Ok;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
778 779
//--------------------------------------------------------------------

Dimitri van Heesch's avatar
Dimitri van Heesch committed
780
/** Class representing a list of DotNode objects. */
Dimitri van Heesch's avatar
Dimitri van Heesch committed
781 782 783 784 785
class DotNodeList : public QList<DotNode>
{
  public:
    DotNodeList() : QList<DotNode>() {}
   ~DotNodeList() {}
786
   int compareItems(QCollection::Item item1,QCollection::Item item2)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
787
   {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
788
     return qstricmp(((DotNode *)item1)->m_label,((DotNode *)item2)->m_label);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
789 790 791 792 793
   }
};

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

794 795 796 797
DotRunner::DotRunner(const QCString &file,const QCString &path,
                     bool checkResult,const QCString &imageName) 
  : m_file(file), m_path(path), 
    m_checkResult(checkResult), m_imageName(imageName)
798
{
799 800
  static bool dotCleanUp = Config_getBool("DOT_CLEANUP"); 
  m_cleanUp = dotCleanUp;
801 802 803 804 805 806 807 808 809
  m_jobs.setAutoDelete(TRUE);
}

void DotRunner::addJob(const char *format,const char *output)
{
  QCString args = QCString("-T")+format+" -o \""+output+"\"";
  m_jobs.append(new QCString(args));
}

810 811 812 813 814 815
void DotRunner::addPostProcessing(const char *cmd,const char *args)
{
  m_postCmd = cmd;
  m_postArgs = args;
}

816 817
bool DotRunner::run()
{
818
  int exitCode=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
819 820
  QCString dotExe   = Config_getString("DOT_PATH")+"dot";
  bool multiTargets = Config_getBool("DOT_MULTI_TARGETS");
821
  QCString dotArgs;
822 823
  QListIterator<QCString> li(m_jobs);
  QCString *s;
824 825 826 827 828 829 830
  QCString file      = m_file;
  QCString path      = m_path;
  QCString imageName = m_imageName;
  QCString postCmd   = m_postCmd;
  QCString postArgs  = m_postArgs;
  bool checkResult   = m_checkResult;
  bool cleanUp       = m_cleanUp;
831
  if (multiTargets)
832
  {
833
    dotArgs="\""+file+"\"";
834 835 836 837 838
    for (li.toFirst();(s=li.current());++li)
    {
      dotArgs+=' ';
      dotArgs+=*s;
    }
839
    if ((exitCode=portable_system(dotExe,dotArgs,FALSE))!=0)
840 841 842 843 844 845 846 847
    {
      goto error;
    }
  }
  else
  {
    for (li.toFirst();(s=li.current());++li)
    {
848
      dotArgs="\""+file+"\" "+*s;
849
      if ((exitCode=portable_system(dotExe,dotArgs,FALSE))!=0)
850 851 852 853 854
      {
        goto error;
      }
    }
  }
855
  if (!postCmd.isEmpty() && portable_system(postCmd,postArgs)!=0)
856
  {
857
    err("Problems running '%s' as a post-processing step for dot output\n",m_postCmd.data());
858 859
    return FALSE;
  }
860 861
  if (checkResult) checkDotResult(imageName);
  if (cleanUp) 
862 863
  {
    //printf("removing dot file %s\n",m_file.data());
864 865 866
    //QDir(path).remove(file);
    m_cleanupItem.file = file;
    m_cleanupItem.path = path;
867
  }
868 869
  return TRUE;
error:
870 871
  err("Problems running dot: exit code=%d, command='%s', arguments='%s'\n",
      exitCode,dotExe.data(),dotArgs.data());
872 873 874
  return FALSE;
}

875 876
//--------------------------------------------------------------------

877
DotFilePatcher::DotFilePatcher(const char *patchFile) 
878 879 880 881 882
  : m_patchFile(patchFile)
{
  m_maps.setAutoDelete(TRUE);
}

883 884 885 886 887
QCString DotFilePatcher::file() const
{
  return m_patchFile;
}

888
int DotFilePatcher::addMap(const QCString &mapFile,const QCString &relPath,
889 890 891 892
               bool urlOnly,const QCString &context,const QCString &label)
{
  int id = m_maps.count();
  Map *map = new Map;
893 894 895 896 897 898
  map->mapFile  = mapFile;
  map->relPath  = relPath;
  map->urlOnly  = urlOnly;
  map->context  = context;
  map->label    = label;
  map->zoomable = FALSE;
899
  map->graphId  = -1;
900 901 902 903
  m_maps.append(map);
  return id;
}

904 905
int DotFilePatcher::addFigure(const QCString &baseName,
                              const QCString &figureName,bool heightCheck)
906 907 908
{
  int id = m_maps.count();
  Map *map = new Map;
909 910 911 912
  map->mapFile  = figureName;
  map->urlOnly  = heightCheck;
  map->label    = baseName;
  map->zoomable = FALSE;
913
  map->graphId  = -1;
914 915 916 917
  m_maps.append(map);
  return id;
}

918
int DotFilePatcher::addSVGConversion(const QCString &relPath,bool urlOnly,
919 920
                                     const QCString &context,bool zoomable,
                                     int graphId)
921
{
922 923
  int id = m_maps.count();
  Map *map = new Map;
924 925 926 927
  map->relPath  = relPath;
  map->urlOnly  = urlOnly;
  map->context  = context;
  map->zoomable = zoomable;
928
  map->graphId  = graphId;
929 930 931 932 933 934 935 936 937 938
  m_maps.append(map);
  return id;
}

int DotFilePatcher::addSVGObject(const QCString &baseName,
                                 const QCString &absImgName,
                                 const QCString &relPath)
{
  int id = m_maps.count();
  Map *map = new Map;
939 940 941 942
  map->mapFile  = absImgName;
  map->relPath  = relPath;
  map->label    = baseName;
  map->zoomable = FALSE;
943
  map->graphId  = -1;
944 945 946 947 948 949 950
  m_maps.append(map);
  return id;
}

bool DotFilePatcher::run()
{
  //printf("DotFilePatcher::run(): %s\n",m_patchFile.data());
951
  static bool interactiveSVG = Config_getBool("INTERACTIVE_SVG");
952
  bool isSVGFile = m_patchFile.right(4)==".svg";
953 954
  int graphId = -1;
  QCString relPath;
955 956 957 958
  if (isSVGFile)
  {
    Map *map = m_maps.at(0); // there is only one 'map' for a SVG file
    interactiveSVG = interactiveSVG && map->zoomable;
959 960
    graphId = map->graphId;
    relPath = map->relPath;
961 962 963
    //printf("DotFilePatcher::addSVGConversion: file=%s zoomable=%d\n",
    //    m_patchFile.data(),map->zoomable);
  }
964 965 966 967 968 969 970 971 972 973
  QCString tmpName = m_patchFile+".tmp";
  if (!QDir::current().rename(m_patchFile,tmpName))
  {
    err("Failed to rename file %s to %s!\n",m_patchFile.data(),tmpName.data());
    return FALSE;
  }
  QFile fi(tmpName);
  QFile fo(m_patchFile);
  if (!fi.open(IO_ReadOnly)) 
  {
974
    err("problem opening file %s for patching!\n",tmpName.data());
975 976 977 978 979
    QDir::current().rename(tmpName,m_patchFile);
    return FALSE;
  }
  if (!fo.open(IO_WriteOnly))
  {
980
    err("problem opening file %s for patching!\n",m_patchFile.data());
981 982 983 984 985
    QDir::current().rename(tmpName,m_patchFile);
    return FALSE;
  }
  FTextStream t(&fo);
  const int maxLineLen=100*1024;
986 987 988 989 990
  int lineNr=1;
  int width,height;
  bool insideHeader=FALSE;
  bool replacedHeader=FALSE;
  bool foundSize=FALSE;
991 992 993 994
  while (!fi.atEnd()) // foreach line
  {
    QCString line(maxLineLen);
    int numBytes = fi.readLine(line.data(),maxLineLen);
995 996 997 998 999
    if (numBytes<=0)
    {
      break;
    }

1000
    //printf("line=[%s]\n",line.stripWhiteSpace().data());
1001 1002
    int i;
    ASSERT(numBytes<maxLineLen);
1003 1004
    if (isSVGFile)
    {
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
      if (interactiveSVG) 
      {
        if (line.find("<svg")!=-1 && !replacedHeader)
        {
          int count;
          count = sscanf(line.data(),"<svg width=\"%dpt\" height=\"%dpt\"",&width,&height);
          //printf("width=%d height=%d\n",width,height);
          foundSize = count==2 && (width>500 || height>450);
          if (foundSize) insideHeader=TRUE;
        }
        else if (insideHeader && !replacedHeader && line.find("<title>")!=-1)
        {
          if (foundSize)
          {
            // insert special replacement header for interactive SVGs
1020
            t << "<!--zoomable " << height << " -->\n";
1021 1022 1023
            t << svgZoomHeader;
            t << "var viewWidth = " << width << ";\n";
            t << "var viewHeight = " << height << ";\n";
1024 1025 1026 1027
            if (graphId>=0)
            {
              t << "var sectionId = 'dynsection-" << graphId << "';\n";
            }
1028
            t << "</script>\n";
1029
            t << "<script xlink:href=\"" << relPath << "svgpan.js\"/>\n";
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
            t << "<svg id=\"graph\" class=\"graph\">\n";
            t << "<g id=\"viewport\">\n";
          }
          insideHeader=FALSE;
          replacedHeader=TRUE;
        }
      }
      if (!insideHeader || !foundSize) // copy SVG and replace refs, 
                                       // unless we are inside the header of the SVG.
                                       // Then we replace it with another header.
      {
        Map *map = m_maps.at(0); // there is only one 'map' for a SVG file
        t << replaceRef(line,map->relPath,map->urlOnly,map->context,"_top");
      }
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    }
    else if ((i=line.find("<!-- SVG"))!=-1 || (i=line.find("[!-- SVG"))!=-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<(int)m_maps.count())
      {
        int e = QMAX(line.find("--]"),line.find("-->"));
        Map *map = m_maps.at(mapId);
1055 1056
        //printf("DotFilePatcher::writeSVGFigure: file=%s zoomable=%d\n",
        //  m_patchFile.data(),map->zoomable);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
        if (!writeSVGFigureLink(t,map->relPath,map->label,map->mapFile))
        {
          err("Problem extracting size from SVG file %s\n",map->mapFile.data());
        }
        if (e!=-1) t << line.mid(e+3);
      }
      else // error invalid map id!
      {
        err("Found invalid SVG id in file %s!\n",m_patchFile.data());
        t << line.mid(i);
      }
    }
    else if ((i=line.find("<!-- MAP"))!=-1)
1070 1071
    {
      int mapId=-1;
1072 1073
      t << line.left(i);
      int n = sscanf(line.data()+i,"<!-- MAP %d",&mapId);
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
      if (n==1 && mapId>=0 && mapId<(int)m_maps.count())
      {
        Map *map = m_maps.at(mapId);
        //printf("patching MAP %d in file %s with contents of %s\n",
        //   mapId,m_patchFile.data(),map->mapFile.data());
        t << "<map name=\"" << map->label << "\" id=\"" << map->label << "\">" << endl;
        convertMapFile(t,map->mapFile,map->relPath,map->urlOnly,map->context);
        t << "</map>" << endl;
      }
      else // error invalid map id!
      {
1085 1086
        err("Found invalid MAP id in file %s!\n",m_patchFile.data());
        t << line.mid(i);
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
      }
    }
    else if ((i=line.find("% FIG"))!=-1)
    {
      int mapId=-1;
      int n = sscanf(line.data()+i+2,"FIG %d",&mapId);
      //printf("line='%s' n=%d\n",line.data()+i,n);
      if (n==1 && mapId>=0 && mapId<(int)m_maps.count())
      {
        Map *map = m_maps.at(mapId);
        //printf("patching FIG %d in file %s with contents of %s\n",
        //   mapId,m_patchFile.data(),map->mapFile.data());
        writeVecGfxFigure(t,map->label,map->mapFile);
      }
      else // error invalid map id!
      {
        err("Found invalid bounding FIG id in file %s!\n",mapId,m_patchFile.data());
        t << line;
      }
    }
    else
    {
      t << line;
    }
1111 1112
    lineNr++;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1113
  fi.close();
1114 1115
  if (isSVGFile && interactiveSVG && replacedHeader)
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1116
    QCString orgName=m_patchFile.left(m_patchFile.length()-4)+"_org.svg";
1117
    t << substitute(svgZoomFooter,"$orgname",stripPath(orgName));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1118 1119 1120 1121 1122 1123 1124
    fo.close();
    // keep original SVG file so we can refer to it, we do need to replace
    // dummy link by real ones
    QFile fi(tmpName);
    QFile fo(orgName);
    if (!fi.open(IO_ReadOnly)) 
    {
1125
      err("problem opening file %s for reading!\n",tmpName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1126 1127 1128 1129
      return FALSE;
    }
    if (!fo.open(IO_WriteOnly))
    {
1130
      err("problem opening file %s for writing!\n",orgName.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
      return FALSE;
    }
    FTextStream t(&fo);
    while (!fi.atEnd()) // foreach line
    {
      QCString line(maxLineLen);
      int numBytes = fi.readLine(line.data(),maxLineLen);
      if (numBytes<=0)
      {
        break;
      }
      Map *map = m_maps.at(0); // there is only one 'map' for a SVG file
      t << replaceRef(line,map->relPath,map->urlOnly,map->context,"_top");
    }
    fi.close();
    fo.close();
1147
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1148
  // remove temporary file
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
  QDir::current().remove(tmpName);
  return TRUE;
}

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

void DotRunnerQueue::enqueue(DotRunner *runner)
{
  QMutexLocker locker(&m_mutex);
  m_queue.enqueue(runner);
  m_bufferNotEmpty.wakeAll();
}

DotRunner *DotRunnerQueue::dequeue()
{
  QMutexLocker locker(&m_mutex);
  while (m_queue.isEmpty())
  {
    // wait until something is added to the queue
    m_bufferNotEmpty.wait(&m_mutex);
  }
  DotRunner *result = m_queue.dequeue();
  return result;
}

uint DotRunnerQueue::count() const
{
  QMutexLocker locker(&m_mutex);
  return m_queue.count();
}

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

DotWorkerThread::DotWorkerThread(int id,DotRunnerQueue *queue)
      : m_id(id), m_queue(queue)
{
1185
  m_cleanupItems.setAutoDelete(TRUE);
1186 1187 1188 1189 1190 1191 1192 1193
}

void DotWorkerThread::run()
{
  DotRunner *runner;
  while ((runner=m_queue->dequeue()))
  {
    runner->run();
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    DotRunner::CleanupItem cleanup = runner->cleanup();
    if (!cleanup.file.isEmpty())
    {
      m_cleanupItems.append(new DotRunner::CleanupItem(cleanup));
    }
  }
}

void DotWorkerThread::cleanup()
{
  QListIterator<DotRunner::CleanupItem> it(m_cleanupItems);
  DotRunner::CleanupItem *ci;
  for (;(ci=it.current());++it)
  {
    QDir(ci->path).remove(ci->file);
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
  }
}

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

DotManager *DotManager::m_theInstance = 0;

DotManager *DotManager::instance()
{
  if (!m_theInstance)
  {
    m_theInstance = new DotManager;
  }
  return m_theInstance;
}

DotManager::DotManager() : m_dotMaps(1007)
{
  m_dotRuns.setAutoDelete(TRUE);
  m_dotMaps.setAutoDelete(TRUE);
  m_queue = new DotRunnerQueue;
  int i;
  int numThreads = QMIN(32,Config_getInt("DOT_NUM_THREADS"));
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1232
  if (numThreads!=1)
1233
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1234 1235
    if (numThreads==0) numThreads = QMAX(2,QThread::idealThreadCount()+1);
    for (i=0;i<numThreads;i++)
1236
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
      DotWorkerThread *thread = new DotWorkerThread(i,m_queue);
      thread->start();
      if (thread->isRunning())
      {
        m_workers.append(thread);
      }
      else // no more threads available!
      {
        delete thread;
      }
1247
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1248
    ASSERT(m_workers.count()>0);
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
  }
}

DotManager::~DotManager()
{
  delete m_queue;
}

void DotManager::addRun(DotRunner *run)
{
  m_dotRuns.append(run);
}

int DotManager::addMap(const QCString &file,const QCString &mapFile,
                const QCString &relPath,bool urlOnly,const QCString &context,
                const QCString &label)
{
1266
  DotFilePatcher *map = m_dotMaps.find(file);
1267 1268
  if (map==0)
  {
1269
    map = new DotFilePatcher(file);
1270 1271 1272 1273 1274 1275 1276 1277
    m_dotMaps.append(file,map);
  }
  return map->addMap(mapFile,relPath,urlOnly,context,label);
}

int DotManager::addFigure(const QCString &file,const QCString &baseName,
                          const QCString &figureName,bool heightCheck)
{
1278
  DotFilePatcher *map = m_dotMaps.find(file);
1279 1280
  if (map==0)
  {
1281
    map = new DotFilePatcher(file);
1282 1283 1284 1285 1286
    m_dotMaps.append(file,map);
  }
  return map->addFigure(baseName,figureName,heightCheck);
}

1287
int DotManager::addSVGConversion(const QCString &file,const QCString &relPath,
1288 1289
                       bool urlOnly,const QCString &context,bool zoomable,
                       int graphId)
1290 1291 1292 1293 1294 1295 1296
{
  DotFilePatcher *map = m_dotMaps.find(file);
  if (map==0)
  {
    map = new DotFilePatcher(file);
    m_dotMaps.append(file,map);
  }
1297
  return map->addSVGConversion(relPath,urlOnly,context,zoomable,graphId);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
}

int DotManager::addSVGObject(const QCString &file,const QCString &baseName,
                             const QCString &absImgName,const QCString &relPath)
{
  DotFilePatcher *map = m_dotMaps.find(file);
  if (map==0)
  {
    map = new DotFilePatcher(file);
    m_dotMaps.append(file,map);
  }
  return map->addSVGObject(baseName,absImgName,relPath);
}

1312 1313 1314 1315
bool DotManager::run()
{
  uint numDotRuns = m_dotRuns.count();
  uint numDotMaps = m_dotMaps.count();
1316
  if (numDotRuns+numDotMaps>1)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1317
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1318 1319 1320 1321 1322 1323 1324 1325
    if (m_workers.count()==0)
    {
      msg("Generating dot graphs in single threaded mode...\n");
    }
    else
    {
      msg("Generating dot graphs using %d parallel threads...\n",QMIN(numDotRuns+numDotMaps,m_workers.count()));
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1326
  }
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
  int i=1;
  QListIterator<DotRunner> li(m_dotRuns);

  bool setPath=FALSE;
  if (Config_getBool("GENERATE_HTML"))
  {
    setDotFontPath(Config_getString("HTML_OUTPUT"));
    setPath=TRUE;
  }
  else if (Config_getBool("GENERATE_LATEX"))
  {
    setDotFontPath(Config_getString("LATEX_OUTPUT"));
    setPath=TRUE;
  }
  else if (Config_getBool("GENERATE_RTF"))
  {
    setDotFontPath(Config_getString("RTF_OUTPUT"));
    setPath=TRUE;
  }
  portable_sysTimerStart();
  // fill work queue with dot operations
  DotRunner *dr;
  int prev=1;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1350
  if (m_workers.count()==0) // no threads to work with
1351
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1352
    for (li.toFirst();(dr=li.current());++li)
1353 1354
    {
      msg("Running dot for graph %d/%d\n",prev,numDotRuns);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1355
      dr->run();
1356 1357 1358
      prev++;
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1359
  else // use multiple threads to run instances of dot in parallel
1360
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    for (li.toFirst();(dr=li.current());++li)
    {
      m_queue->enqueue(dr);
    }
    // wait for the queue to become empty
    while ((i=m_queue->count())>0)
    {
      i = numDotRuns - i;
      while (i>=prev)
      {
        msg("Running dot for graph %d/%d\n",prev,numDotRuns);
        prev++;
      }
      portable_sleep(100);
    }
    while ((int)numDotRuns>=prev)
    {
      msg("Running dot for graph %d/%d\n",prev,numDotRuns);
      prev++;
    }
    // signal the workers we are done
    for (i=0;i<(int)m_workers.count();i++)
    {
      m_queue->enqueue(0); // add terminator for each worker
    }
    // wait for the workers to finish
    for (i=0;i<(int)m_workers.count();i++)
    {
      m_workers.at(i)->wait();
    }
    // clean up dot files from main thread
    for (i=0;i<(int)m_workers.count();i++)
    {
      m_workers.at(i)->cleanup();
    }
1396
  }
1397 1398 1399 1400 1401 1402 1403 1404
  portable_sysTimerStop();
  if (setPath)
  {
    unsetDotFontPath();
  }

  // patch the output file and insert the maps and figures
  i=1;
1405 1406
  SDict<DotFilePatcher>::Iterator di(m_dotMaps);
  DotFilePatcher *map;
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
  // since patching the svg files may involve patching the header of the SVG
  // (for zoomable SVGs), and patching the .html files requires reading that
  // header after the SVG is patched, we first process the .svg files and 
  // then the other files. 
  for (di.toFirst();(map=di.current());++di)
  {
    if (map->file().right(4)==".svg")
    {
      msg("Patching output file %d/%d\n",i,numDotMaps);
      if (!map->run()) return FALSE;
      i++;
    }
  }
1420 1421
  for (di.toFirst();(map=di.current());++di)
  {
1422 1423 1424 1425 1426 1427
    if (map->file().right(4)!=".svg")
    {
      msg("Patching output file %d/%d\n",i,numDotMaps);
      if (!map->run()) return FALSE;
      i++;
    }
1428 1429 1430 1431
  }
  return TRUE;
}

1432 1433
//--------------------------------------------------------------------

1434 1435 1436 1437

/*! helper function that deletes all nodes in a connected graph, given
 *  one of the graph's nodes
 */
1438
static void deleteNodes(DotNode *node,SDict<DotNode> *skipNodes=0)
1439
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1440
  //printf("deleteNodes skipNodes=%p\n",skipNodes);
1441 1442
  static DotNodeList deletedNodes;
  deletedNodes.setAutoDelete(TRUE);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1443
  node->deleteNode(deletedNodes,skipNodes); // collect nodes to be deleted.
1444 1445 1446
  deletedNodes.clear(); // actually remove the nodes.
}

1447
DotNode::DotNode(int n,const char *lab,const char *tip, const char *url,
1448
                 bool isRoot,ClassDef *cd)
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
  : m_subgraphId(-1)
  , m_number(n)
  , m_label(lab)
  , m_tooltip(tip)
  , m_url(url)
  , m_parents(0)
  , m_children(0)
  , m_edgeInfo(0)
  , m_deleted(FALSE)
  , m_written(FALSE)
  , m_hasDoc(FALSE)
  , m_isRoot(isRoot)
  , m_classDef(cd)
  , m_visible(FALSE)
  , m_truncated(Unknown)
1464
  , m_distance(1000)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
{
}

DotNode::~DotNode()
{
  delete m_children;
  delete m_parents;
  delete m_edgeInfo;
}

void DotNode::addChild(DotNode *n,
                       int edgeColor,
                       int edgeStyle,
                       const char *edgeLab,
                       const char *edgeURL,
                       int edgeLabCol
                      )
{
  if (m_children==0)
  {
    m_children = new QList<DotNode>;
    m_edgeInfo = new QList<EdgeInfo>;
    m_edgeInfo->setAutoDelete(TRUE);
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1489
  m_children->append(n);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1490 1491 1492 1493 1494 1495 1496 1497 1498
  EdgeInfo *ei = new EdgeInfo;
  ei->m_color = edgeColor;
  ei->m_style = edgeStyle; 
  ei->m_label = edgeLab;
  ei->m_url   = edgeURL;
  if (edgeLabCol==-1)
    ei->m_labColor=edgeColor;
  else
    ei->m_labColor=edgeLabCol;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1499
  m_edgeInfo->append(ei);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
}

void DotNode::addParent(DotNode *n)
{
  if (m_parents==0)
  {
    m_parents = new QList<DotNode>;
  }
  m_parents->append(n);
}

void DotNode::removeChild(DotNode *n)
{
  if (m_children) m_children->remove(n);
}

void DotNode::removeParent(DotNode *n)
{
  if (m_parents) m_parents->remove(n);
}

1521
void DotNode::deleteNode(DotNodeList &deletedList,SDict<DotNode> *skipNodes)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1522 1523 1524
{
  if (m_deleted) return; // avoid recursive loops in case the graph has cycles
  m_deleted=TRUE;
1525
  if (m_parents!=0) // delete all parent nodes of this node
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1526 1527 1528 1529 1530
  {
    QListIterator<DotNode> dnlip(*m_parents);
    DotNode *pn;
    for (dnlip.toFirst();(pn=dnlip.current());++dnlip)
    {
1531
      //pn->removeChild(this);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1532
      pn->deleteNode(deletedList,skipNodes);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1533 1534
    }
  }
1535
  if (m_children!=0) // delete all child nodes of this node
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1536 1537 1538 1539 1540
  {
    QListIterator<DotNode> dnlic(*m_children);
    DotNode *cn;
    for (dnlic.toFirst();(cn=dnlic.current());++dnlic)
    {
1541
      //cn->removeParent(this);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1542
      cn->deleteNode(deletedList,skipNodes);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1543 1544
    }
  }
1545
  // add this node to the list of deleted nodes.
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1546
  //printf("skipNodes=%p find(%p)=%p\n",skipNodes,this,skipNodes ? skipNodes->find((int)this) : 0);
1547
  if (skipNodes==0 || skipNodes->find((char*)this)==0)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1548 1549 1550 1551
  {
    //printf("deleting\n");
    deletedList.append(this);
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1552 1553
}

1554 1555 1556 1557 1558
void DotNode::setDistance(int distance)
{
  if (distance<m_distance) m_distance = distance;
}

1559 1560 1561
static QCString convertLabel(const QCString &l)
{
  QCString result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1562
  QCString bBefore("\\_/<({[: =-+@%#~?$"); // break before character set
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1563
  QCString bAfter(">]),:;|");              // break after  character set
1564
  const char *p=l.data();
1565
  if (p==0) return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1566
  char c,pc=0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1567 1568 1569 1570 1571 1572
  char cs[2];
  cs[1]=0;
  int len=l.length();
  int charsLeft=len;
  int sinceLast=0;
  int foldLen=17; // ideal text length
1573 1574
  while ((c=*p++))
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1575
    QCString replacement;
1576 1577
    switch(c)
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1578 1579 1580 1581 1582 1583 1584 1585 1586
      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;
      default:   cs[0]=c; replacement=cs; break;
1587
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1588 1589 1590 1591 1592 1593 1594 1595
    // 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;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1596
    else if ((pc!=':' || c!=':') && charsLeft>foldLen/3 && sinceLast>foldLen && bBefore.contains(c))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1597
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1598
      result+="\\l";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1599 1600 1601 1602 1603 1604 1605 1606
      result+=replacement;
      foldLen = (foldLen+sinceLast+1)/2;
      sinceLast=1;
    }
    else if (charsLeft>1+foldLen/4 && sinceLast>foldLen+foldLen/3 && 
            !isupper(c) && isupper(*p))
    {
      result+=replacement;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1607
      result+="\\l";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1608 1609 1610
      foldLen = (foldLen+sinceLast+1)/2;
      sinceLast=0;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1611
    else if (charsLeft>foldLen/3 && sinceLast>foldLen && bAfter.contains(c) && (c!=':' || *p!=':'))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1612 1613
    {
      result+=replacement;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1614
      result+="\\l";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1615 1616 1617 1618 1619 1620 1621 1622 1623
      foldLen = (foldLen+sinceLast+1)/2;
      sinceLast=0;
    }
    else
    {
      result+=replacement;
      sinceLast++;
    }
    charsLeft--;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1624
    pc=c;
1625 1626 1627 1628
  }
  return result;
}

1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
static QCString escapeTooltip(const QCString &tooltip)
{
  QCString result;
  const char *p=tooltip.data();
  if (p==0) return result;
  char c;
  while ((c=*p++))
  {
    switch(c)
    {
1639 1640
      case '"': result+="\\\""; break;
      default: result+=c; break;
1641 1642 1643 1644 1645
    }
  }
  return result;
}

1646 1647
static void writeBoxMemberList(FTextStream &t,
            char prot,MemberList *ml,ClassDef *scope,
1648
            bool isStatic=FALSE,const QDict<void> *skipNames=0)
1649
{
1650
  (void)isStatic;
1651
  if (ml)
1652
  {
1653 1654
    MemberListIterator mlia(*ml);
    MemberDef *mma;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1655
    int totalCount=0;
1656
    for (mlia.toFirst();(mma = mlia.current());++mlia)
1657
    {
1658 1659
      if (mma->getClassDef()==scope && 
          (skipNames==0 || skipNames->find(mma->name())==0))
1660
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1661 1662 1663 1664 1665 1666 1667
        totalCount++;
      }
    }

    int count=0;
    for (mlia.toFirst();(mma = mlia.current());++mlia)
    {
1668 1669
      if (mma->getClassDef() == scope &&
          (skipNames==0 || skipNames->find(mma->name())==0))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1670
      {
1671
        static int limit = Config_getInt("UML_LIMIT_NUM_FIELDS");
1672
        if (limit>0 && (totalCount>limit*3/2 && count>=limit))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1673
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1674
          t << theTranslator->trAndMore(QCString().sprintf("%d",totalCount-count)) << "\\l";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
          break;
        }
        else
        {
          t << prot << " ";
          t << convertLabel(mma->name());
          if (!mma->isObjCMethod() && 
              (mma->isFunction() || mma->isSlot() || mma->isSignal())) t << "()";
          t << "\\l";
          count++;
        }
1686
      }
1687
    }
1688 1689 1690
    // write member groups within the memberlist
    MemberGroupList *mgl = ml->getMemberGroupList();
    if (mgl)
1691
    {
1692 1693 1694
      MemberGroupListIterator mgli(*mgl);
      MemberGroup *mg;
      for (mgli.toFirst();(mg=mgli.current());++mgli)
1695
      {
1696 1697
        if (mg->members())
        {
1698
          writeBoxMemberList(t,prot,mg->members(),scope,isStatic,skipNames);
1699
        }
1700 1701 1702
      }
    }
  }
1703 1704
}

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
static QCString stripProtectionPrefix(const QCString &s)
{
  if (!s.isEmpty() && (s[0]=='-' || s[0]=='+' || s[0]=='~' || s[0]=='#'))
  {
    return s.mid(1);
  }
  else
  {
    return s;
  }
}

1717
void DotNode::writeBox(FTextStream &t,
1718
                       GraphType gt,
1719
                       GraphOutputFormat /*format*/,
1720 1721
                       bool hasNonReachableChildren,
                       bool reNumber)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1722
{
1723
  const char *labCol = 
1724
          m_url.isEmpty() ? "grey75" :  // non link
1725 1726 1727
           (
            (hasNonReachableChildren) ? "red" : "black"
           );
1728
  t << "  Node" << reNumberNode(m_number,reNumber) << " [label=\"";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1729
  static bool umlLook = Config_getBool("UML_LOOK");
1730

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1731
  if (m_classDef && umlLook && (gt==Inheritance || gt==Collaboration))
1732
  {
1733
    // add names shown as relations to a dictionary, so we don't show
1734 1735
    // them as attributes as well
    QDict<void> arrowNames(17);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1736
    if (m_edgeInfo)
1737
    {
1738
      // for each edge
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1739 1740 1741
      QListIterator<EdgeInfo> li(*m_edgeInfo);
      EdgeInfo *ei;
      for (li.toFirst();(ei=li.current());++li)
1742
      {
1743
        if (!ei->m_label.isEmpty()) // labels joined by \n
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1744
        {
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
          int li=ei->m_label.find('\n');
          int p=0;
          QCString lab;
          while ((li=ei->m_label.find('\n',p))!=-1)
          {
            lab = stripProtectionPrefix(ei->m_label.mid(p,li-p));
            arrowNames.insert(lab,(void*)0x8);
            p=li+1;
          }
          lab = stripProtectionPrefix(ei->m_label.right(ei->m_label.length()-p));
          arrowNames.insert(lab,(void*)0x8);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1756
        }
1757 1758 1759
      }
    }

1760 1761
    //printf("DotNode::writeBox for %s\n",m_classDef->name().data());
    static bool extractPrivate = Config_getBool("EXTRACT_PRIVATE");
1762 1763
    t << "{" << convertLabel(m_label);
    t << "\\n|";
1764 1765 1766 1767 1768 1769 1770
    writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType_pubAttribs),m_classDef,FALSE,&arrowNames);
    writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType_pubStaticAttribs),m_classDef,TRUE,&arrowNames);
    writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType_properties),m_classDef,FALSE,&arrowNames);
    writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType_pacAttribs),m_classDef,FALSE,&arrowNames);
    writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType_pacStaticAttribs),m_classDef,TRUE,&arrowNames);
    writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType_proAttribs),m_classDef,FALSE,&arrowNames);
    writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType_proStaticAttribs),m_classDef,TRUE,&arrowNames);
1771 1772
    if (extractPrivate)
    {
1773 1774
      writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType_priAttribs),m_classDef,FALSE,&arrowNames);
      writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType_priStaticAttribs),m_classDef,TRUE,&arrowNames);
1775
    }
1776
    t << "|";
1777 1778 1779 1780 1781 1782 1783 1784
    writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType_pubMethods),m_classDef);
    writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType_pubStaticMethods),m_classDef,TRUE);
    writeBoxMemberList(t,'+',m_classDef->getMemberList(MemberListType_pubSlots),m_classDef);
    writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType_pacMethods),m_classDef);
    writeBoxMemberList(t,'~',m_classDef->getMemberList(MemberListType_pacStaticMethods),m_classDef,TRUE);
    writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType_proMethods),m_classDef);
    writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType_proStaticMethods),m_classDef,TRUE);
    writeBoxMemberList(t,'#',m_classDef->getMemberList(MemberListType_proSlots),m_classDef);
1785 1786
    if (extractPrivate)
    {
1787 1788 1789
      writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType_priMethods),m_classDef);
      writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType_priStaticMethods),m_classDef,TRUE);
      writeBoxMemberList(t,'-',m_classDef->getMemberList(MemberListType_priSlots),m_classDef);
1790
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1791
    if (m_classDef->getLanguage()!=SrcLangExt_Fortran &&
1792
        m_classDef->getMemberGroupSDict())
1793 1794
    {
      MemberGroupSDict::Iterator mgdi(*m_classDef->getMemberGroupSDict());
1795 1796 1797 1798 1799
      MemberGroup *mg;
      for (mgdi.toFirst();(mg=mgdi.current());++mgdi)
      {
        if (mg->members())
        {
1800
          writeBoxMemberList(t,'*',mg->members(),m_classDef,FALSE,&arrowNames);
1801 1802 1803
        }
      }
    }
1804 1805
    t << "}";
  }
1806
  else // standard look
1807 1808 1809 1810
  {
    t << convertLabel(m_label);
  }
  t << "\",height=0.2,width=0.4";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1811 1812
  if (m_isRoot)
  {
1813
    t << ",color=\"black\", fillcolor=\"grey75\", style=\"filled\" fontcolor=\"black\"";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1814
  }
1815
  else 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1816
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1817 1818
    static bool dotTransparent = Config_getBool("DOT_TRANSPARENT");
    if (!dotTransparent)
1819
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1820
      t << ",color=\"" << labCol << "\", fillcolor=\"";
1821
      t << "white";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1822
      t << "\", style=\"filled\"";
1823 1824 1825 1826 1827
    }
    else
    {
      t << ",color=\"" << labCol << "\"";
    }
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
    if (!m_url.isEmpty())
    {
      int anchorPos = m_url.findRev('#');
      if (anchorPos==-1)
      {
        t << ",URL=\"" << m_url << Doxygen::htmlFileExtension << "\"";
      }
      else
      {
        t << ",URL=\"" << m_url.left(anchorPos) << Doxygen::htmlFileExtension
          << m_url.right(m_url.length()-anchorPos) << "\"";
      }
    }
1841 1842
    if (!m_tooltip.isEmpty())
    {
1843
      t << ",tooltip=\"" << escapeTooltip(m_tooltip) << "\"";
1844
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1845 1846
  }
  t << "];" << endl; 
1847 1848
}

1849
void DotNode::writeArrow(FTextStream &t,
1850
                         GraphType gt,
1851 1852 1853 1854
                         GraphOutputFormat format,
                         DotNode *cn,
                         EdgeInfo *ei,
                         bool topDown, 
1855 1856
                         bool pointBack,
                         bool reNumber
1857
                        )
1858 1859
{
  t << "  Node";
1860 1861 1862 1863
  if (topDown) 
    t << reNumberNode(cn->number(),reNumber); 
  else 
    t << reNumberNode(m_number,reNumber);
1864
  t << " -> Node";
1865 1866 1867 1868
  if (topDown) 
    t << reNumberNode(m_number,reNumber); 
  else 
    t << reNumberNode(cn->number(),reNumber);
1869
  t << " [";
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879

  static bool umlLook = Config_getBool("UML_LOOK");
  const EdgeProperties *eProps = umlLook ? &umlEdgeProps : &normalEdgeProps;
  QCString aStyle = eProps->arrowStyleMap[ei->m_color];
  bool umlUseArrow = aStyle=="odiamond";

  if (pointBack && !umlUseArrow) t << "dir=\"back\",";
  t << "color=\"" << eProps->edgeColorMap[ei->m_color] 
    << "\",fontsize=\"" << FONTSIZE << "\",";
  t << "style=\"" << eProps->edgeStyleMap[ei->m_style] << "\"";
1880 1881
  if (!ei->m_label.isEmpty())
  {
1882
    t << ",label=\" " << convertLabel(ei->m_label) << "\" ";
1883
  }
1884 1885
  if (umlLook &&
      eProps->arrowStyleMap[ei->m_color] && 
1886 1887 1888
      (gt==Inheritance || gt==Collaboration)
     )
  {
1889 1890 1891 1892
    bool rev = pointBack;
    if (umlUseArrow) rev=!rev; // UML use relates has arrow on the start side
    if (rev) 
      t << ",arrowtail=\"" << eProps->arrowStyleMap[ei->m_color] << "\""; 
1893
    else 
1894
      t << ",arrowhead=\"" << eProps->arrowStyleMap[ei->m_color] << "\"";
1895 1896
  }

Dimitri van Heesch's avatar
Dimitri van Heesch committed
1897
  if (format==BITMAP) t << ",fontname=\"" << FONTNAME << "\"";
1898 1899 1900
  t << "];" << endl; 
}

1901
void DotNode::write(FTextStream &t,
1902
                    GraphType gt,
1903 1904 1905
                    GraphOutputFormat format,
                    bool topDown,
                    bool toChildren,
1906 1907
                    bool backArrows,
                    bool reNumber
1908
                   )
1909
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1910
  //printf("DotNode::write(%d) name=%s this=%p written=%d\n",distance,m_label.data(),this,m_written);
1911
  if (m_written) return; // node already written to the output
1912 1913
  if (!m_visible) return; // node is not visible
  writeBox(t,gt,format,m_truncated==Truncated,reNumber);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1914
  m_written=TRUE;
1915
  QList<DotNode> *nl = toChildren ? m_children : m_parents; 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1916
  if (nl)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1917
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1918 1919 1920 1921 1922 1923 1924
    if (toChildren)
    {
      QListIterator<DotNode>  dnli1(*nl);
      QListIterator<EdgeInfo> dnli2(*m_edgeInfo);
      DotNode *cn;
      for (dnli1.toFirst();(cn=dnli1.current());++dnli1,++dnli2)
      {
1925
        if (cn->isVisible())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1926
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1927
          //printf("write arrow %s%s%s\n",label().data(),backArrows?"<-":"->",cn->label().data());
1928
          writeArrow(t,gt,format,cn,dnli2.current(),topDown,backArrows,reNumber);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1929
        }
1930
        cn->write(t,gt,format,topDown,toChildren,backArrows,reNumber);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1931 1932 1933
      }
    }
    else // render parents
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1934
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1935 1936 1937 1938
      QListIterator<DotNode> dnli(*nl);
      DotNode *pn;
      for (dnli.toFirst();(pn=dnli.current());++dnli)
      {
1939
        if (pn->isVisible())
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1940
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1941
          //printf("write arrow %s%s%s\n",label().data(),backArrows?"<-":"->",pn->label().data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1942
          writeArrow(t,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1943 1944 1945 1946 1947
              gt,
              format,
              pn,
              pn->m_edgeInfo->at(pn->m_children->findRef(this)),
              FALSE,
1948 1949
              backArrows,
              reNumber
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1950
              );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1951
        }
1952
        pn->write(t,gt,format,TRUE,FALSE,backArrows,reNumber);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1953
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1954 1955
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1956
  //printf("end DotNode::write(%d) name=%s\n",distance,m_label.data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
1957 1958
}

1959
void DotNode::writeXML(FTextStream &t,bool isClassGraph)
1960 1961
{
  t << "      <node id=\"" << m_number << "\">" << endl;
1962
  t << "        <label>" << convertToXML(m_label) << "</label>" << endl;
1963 1964 1965 1966 1967 1968 1969 1970
  if (!m_url.isEmpty())
  {
    QCString url(m_url);
    char *refPtr = url.data();
    char *urlPtr = strchr(url.data(),'$');
    if (urlPtr)
    {
      *urlPtr++='\0';
1971
      t << "        <link refid=\"" << convertToXML(urlPtr) << "\"";
1972 1973
      if (*refPtr!='\0')
      {
1974
        t << " external=\"" << convertToXML(refPtr) << "\"";
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
      }
      t << "/>" << endl;
    }
  }
  if (m_children)
  {
    QListIterator<DotNode> nli(*m_children);
    QListIterator<EdgeInfo> eli(*m_edgeInfo);
    DotNode *childNode;
    EdgeInfo *edgeInfo;
    for (;(childNode=nli.current());++nli,++eli)
    {
      edgeInfo=eli.current();
1988
      t << "        <childnode refid=\"" << childNode->m_number << "\" relation=\"";
1989
      if (isClassGraph)
1990
      {
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
        switch(edgeInfo->m_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::Grey:    ASSERT(0); break;
        }
      }
      else // include graph
      {
        t << "include"; 
2004 2005 2006 2007 2008 2009
      }
      t << "\">" << endl;
      if (!edgeInfo->m_label.isEmpty()) 
      {
        int p=0;
        int ni;
2010
        while ((ni=edgeInfo->m_label.find('\n',p))!=-1)
2011 2012
        {
          t << "          <edgelabel>" 
2013
            << convertToXML(edgeInfo->m_label.mid(p,ni-p))
2014
            << "</edgelabel>" << endl;
2015
          p=ni+1;
2016 2017
        }
        t << "          <edgelabel>" 
2018
          << convertToXML(edgeInfo->m_label.right(edgeInfo->m_label.length()-p))
2019 2020 2021 2022 2023 2024 2025 2026
          << "</edgelabel>" << endl;
      }
      t << "        </childnode>" << endl;
    } 
  }
  t << "      </node>" << endl;
}

2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
void DotNode::writeDocbook(FTextStream &t,bool isClassGraph)
{
  t << "      <node id=\"" << m_number << "\">" << endl;
  t << "        <label>" << convertToXML(m_label) << "</label>" << endl;
  if (!m_url.isEmpty())
  {
    QCString url(m_url);
    char *refPtr = url.data();
    char *urlPtr = strchr(url.data(),'$');
    if (urlPtr)
    {
      *urlPtr++='\0';
      t << "        <link refid=\"" << convertToXML(urlPtr) << "\"";
      if (*refPtr!='\0')
      {
        t << " external=\"" << convertToXML(refPtr) << "\"";
      }
      t << "/>" << endl;
    }
  }
  if (m_children)
  {
    QListIterator<DotNode> nli(*m_children);
    QListIterator<EdgeInfo> eli(*m_edgeInfo);
    DotNode *childNode;
    EdgeInfo *edgeInfo;
    for (;(childNode=nli.current());++nli,++eli)
    {
      edgeInfo=eli.current();
      t << "        <childnode refid=\"" << childNode->m_number << "\" relation=\"";
      if (isClassGraph)
      {
        switch(edgeInfo->m_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::Grey:    ASSERT(0); break;
        }
      }
      else // include graph
      {
        t << "include";
      }
      t << "\">" << endl;
      if (!edgeInfo->m_label.isEmpty())
      {
        int p=0;
        int ni;
        while ((ni=edgeInfo->m_label.find('\n',p))!=-1)
        {
          t << "          <edgelabel>"
            << convertToXML(edgeInfo->m_label.mid(p,ni-p))
            << "</edgelabel>" << endl;
          p=ni+1;
        }
        t << "          <edgelabel>"
          << convertToXML(edgeInfo->m_label.right(edgeInfo->m_label.length()-p))
          << "</edgelabel>" << endl;
      }
      t << "        </childnode>" << endl;
    }
  }
  t << "      </node>" << endl;
}

2095

2096
void DotNode::writeDEF(FTextStream &t)
2097
{
2098
  const char* nodePrefix = "        node-";
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159

  t << "      node = {" << endl;
  t << nodePrefix << "id    = " << m_number << ';' << endl;
  t << nodePrefix << "label = '" << m_label << "';" << endl;

  if (!m_url.isEmpty())
  {
    QCString url(m_url);
    char *refPtr = url.data();
    char *urlPtr = strchr(url.data(),'$');
    if (urlPtr)
    {
      *urlPtr++='\0';
      t << nodePrefix << "link = {" << endl << "  "
        << nodePrefix << "link-id = '" << urlPtr << "';" << endl;

      if (*refPtr!='\0')
      {
        t << "  " << nodePrefix << "link-external = '"
          << refPtr << "';" << endl;
      }
      t << "        };" << endl;
    }
  }
  if (m_children)
  {
    QListIterator<DotNode> nli(*m_children);
    QListIterator<EdgeInfo> eli(*m_edgeInfo);
    DotNode *childNode;
    EdgeInfo *edgeInfo;
    for (;(childNode=nli.current());++nli,++eli)
    {
      edgeInfo=eli.current();
      t << "        node-child = {" << endl;
      t << "          child-id = '" << childNode->m_number << "';" << endl;
      t << "          relation = ";

      switch(edgeInfo->m_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::Grey:    ASSERT(0); break;
      }
      t << ';' << endl;

      if (!edgeInfo->m_label.isEmpty()) 
      {
        t << "          edgelabel = <<_EnD_oF_dEf_TeXt_" << endl
          << edgeInfo->m_label << endl
          << "_EnD_oF_dEf_TeXt_;" << endl;
      }
      t << "        }; /* node-child */" << endl;
    } /* for (;childNode...) */
  }
  t << "      }; /* node */" << endl;
}


Dimitri van Heesch's avatar
Dimitri van Heesch committed
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
void DotNode::clearWriteFlag()
{
  m_written=FALSE;
  if (m_parents!=0)
  {
    QListIterator<DotNode> dnlip(*m_parents);
    DotNode *pn;
    for (dnlip.toFirst();(pn=dnlip.current());++dnlip)
    {
      if (pn->m_written)
      {
        pn->clearWriteFlag();
      }
    }
  }
  if (m_children!=0)
  {
    QListIterator<DotNode> dnlic(*m_children);
    DotNode *cn;
    for (dnlic.toFirst();(cn=dnlic.current());++dnlic)
    {
      if (cn->m_written)
      {
        cn->clearWriteFlag();
      }
    }
  }
}

void DotNode::colorConnectedNodes(int curColor)
2190
{ 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2191 2192 2193 2194 2195 2196 2197 2198 2199
  if (m_children)
  {
    QListIterator<DotNode> dnlic(*m_children);
    DotNode *cn;
    for (dnlic.toFirst();(cn=dnlic.current());++dnlic)
    {
      if (cn->m_subgraphId==-1) // uncolored child node
      {
        cn->m_subgraphId=curColor;
2200
        cn->markAsVisible();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2201
        cn->colorConnectedNodes(curColor);
2202
        //printf("coloring node %s (%p): %d\n",cn->m_label.data(),cn,cn->m_subgraphId);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
      }
    }
  }

  if (m_parents)
  {
    QListIterator<DotNode> dnlip(*m_parents);
    DotNode *pn;
    for (dnlip.toFirst();(pn=dnlip.current());++dnlip)
    {
      if (pn->m_subgraphId==-1) // uncolored parent node
      {
        pn->m_subgraphId=curColor;
2216
        pn->markAsVisible();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2217
        pn->colorConnectedNodes(curColor);
2218
        //printf("coloring node %s (%p): %d\n",pn->m_label.data(),pn,pn->m_subgraphId);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2219 2220 2221 2222 2223
      }
    }
  }
}

2224
const DotNode *DotNode::findDocNode() const
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2225
{
2226 2227 2228
  if (!m_url.isEmpty()) return this;
  //printf("findDocNode(): `%s'\n",m_label.data());
  if (m_parents)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2229
  {
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
    QListIterator<DotNode> dnli(*m_parents);
    DotNode *pn;
    for (dnli.toFirst();(pn=dnli.current());++dnli)
    {
      if (!pn->m_hasDoc)
      {
        pn->m_hasDoc=TRUE;
        const DotNode *dn = pn->findDocNode();
        if (dn) return dn;
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2241
  }
2242
  if (m_children)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2243
  {
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
    QListIterator<DotNode> dnli(*m_children);
    DotNode *cn;
    for (dnli.toFirst();(cn=dnli.current());++dnli)
    {
      if (!cn->m_hasDoc)
      {
        cn->m_hasDoc=TRUE;
        const DotNode *dn = cn->findDocNode();
        if (dn) return dn;
      }
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2255
  }
2256
  return 0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2257 2258 2259 2260 2261 2262
}

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

int DotGfxHierarchyTable::m_curNodeNumber;

2263 2264
void DotGfxHierarchyTable::writeGraph(FTextStream &out,
                      const char *path,const char *fileName) const
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2265 2266 2267
{
  //printf("DotGfxHierarchyTable::writeGraph(%s)\n",name);
  //printf("m_rootNodes=%p count=%d\n",m_rootNodes,m_rootNodes->count());
2268
  
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2269 2270 2271 2272
  if (m_rootSubgraphs->count()==0) return;

  QDir d(path);
  // store the original directory
2273 2274
  if (!d.exists())
  {
2275
    err("Output dir %s does not exist!\n",path); exit(1);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2276 2277
  }

2278
  // put each connected subgraph of the hierarchy in a row of the HTML output
2279
  out << "<table border=\"0\" cellspacing=\"10\" cellpadding=\"0\">" << endl;
2280 2281 2282

  QListIterator<DotNode> dnli(*m_rootSubgraphs);
  DotNode *n;
2283
  int count=0;
2284 2285
  for (dnli.toFirst();(n=dnli.current());++dnli)
  {
2286
    QCString baseName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2287
    QCString imgExt = Config_getEnum("DOT_IMAGE_FORMAT");
2288
    baseName.sprintf("inherit_graph_%d",count++);
2289
    //baseName = convertNameToFile(baseName);
2290 2291 2292 2293 2294
    QCString imgName = baseName+"."+ imgExt;
    QCString mapName = baseName+".map";
    QCString absImgName = QCString(d.absPath().data())+"/"+imgName;
    QCString absMapName = QCString(d.absPath().data())+"/"+mapName;
    QCString absBaseName = QCString(d.absPath().data())+"/"+baseName;
2295 2296
    QListIterator<DotNode> dnli2(*m_rootNodes);
    DotNode *node;
2297 2298

    // compute md5 checksum of the graph were are about to generate
2299 2300
    QGString theGraph;
    FTextStream md5stream(&theGraph);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2301
    writeGraphHeader(md5stream,theTranslator->trGraphicalHierarchy());
2302
    md5stream << "  rankdir=\"LR\";" << endl;
2303
    for (dnli2.toFirst();(node=dnli2.current());++dnli2)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2304
    {
2305
      if (node->m_subgraphId==n->m_subgraphId) 
2306 2307
      {
        node->clearWriteFlag();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2308 2309 2310 2311 2312 2313
      }
    }
    for (dnli2.toFirst();(node=dnli2.current());++dnli2)
    {
      if (node->m_subgraphId==n->m_subgraphId) 
      {
2314
        node->write(md5stream,DotNode::Hierarchy,BITMAP,FALSE,TRUE,TRUE,TRUE);
2315
      }
2316
    }
2317
    writeGraphFooter(md5stream);
2318
    resetReNumbering();
2319
    uchar md5_sig[16];
2320
    QCString sigStr(33);
2321
    MD5Buffer((const unsigned char *)theGraph.data(),theGraph.length(),md5_sig);
2322
    MD5SigToString(md5_sig,sigStr.data(),33);
2323
    bool regenerate=FALSE;
2324
    if (checkAndUpdateMd5Signature(absBaseName,sigStr) || 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2325
        !checkDeliverables(absImgName,absMapName))
2326
    {
2327
      regenerate=TRUE;
2328
      // image was new or has changed
2329
      QCString dotName=absBaseName+".dot";
2330 2331
      QFile f(dotName);
      if (!f.open(IO_WriteOnly)) return;
2332
      FTextStream t(&f);
2333
      t << theGraph;
2334
      f.close();
2335
      resetReNumbering();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2336

2337 2338 2339 2340
      DotRunner *dotRun = new DotRunner(dotName,d.absPath().data(),TRUE,absImgName);
      dotRun->addJob(imgExt,absImgName);
      dotRun->addJob(MAP_CMD,absMapName);
      DotManager::instance()->addRun(dotRun);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2341 2342 2343 2344
    }
    else
    {
      removeDotGraph(absBaseName+".dot");
2345
    }
2346
    Doxygen::indexList->addImageFile(imgName);
2347
    // write image and map in a table row
2348
    QCString mapLabel = escapeCharsInString(n->m_label,FALSE);
2349 2350 2351 2352 2353 2354 2355 2356
    out << "<tr><td>";
    if (imgExt=="svg") // vector graphics
    {
      if (regenerate || !writeSVGFigureLink(out,QCString(),baseName,absImgName))
      {
        if (regenerate)
        {
          DotManager::instance()->addSVGConversion(absImgName,QCString(),
2357
                                                   FALSE,QCString(),FALSE,0);
2358 2359 2360 2361 2362 2363 2364 2365 2366
        }
        int mapId = DotManager::instance()->addSVGObject(fileName,baseName,
                                                         absImgName,QCString());
        out << "<!-- SVG " << mapId << " -->" << endl;
      }
    }
    else // normal bitmap
    {
      out << "<img src=\"" << imgName << "\" border=\"0\" alt=\"\" usemap=\"#"
2367 2368
        << mapLabel << "\"/>" << endl;

2369 2370 2371 2372 2373 2374
      if (regenerate || !insertMapFile(out,absMapName,QCString(),mapLabel))
      {
        int mapId = DotManager::instance()->addMap(fileName,absMapName,QCString(),
                                                   FALSE,QCString(),mapLabel);
        out << "<!-- MAP " << mapId << " -->" << endl;
      }
2375 2376 2377
    }

    out << "</td></tr>" << endl;
2378 2379
  }
  out << "</table>" << endl;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2380 2381
}

2382
void DotGfxHierarchyTable::addHierarchy(DotNode *n,ClassDef *cd,bool hideSuper)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2383
{
2384
  //printf("addHierarchy `%s' baseClasses=%d\n",cd->name().data(),cd->baseClasses()->count());
2385 2386 2387 2388 2389 2390 2391 2392 2393
  if (cd->subClasses())
  {
    BaseClassListIterator bcli(*cd->subClasses());
    BaseClassDef *bcd;
    for ( ; (bcd=bcli.current()) ; ++bcli )
    {
      ClassDef *bClass=bcd->classDef; 
      //printf("  Trying sub class=`%s' usedNodes=%d\n",bClass->name().data(),m_usedNodes->count());
      if (bClass->isVisibleInHierarchy() && hasVisibleRoot(bClass->baseClasses()))
2394
      {
2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
        DotNode *bn;
        //printf("  Node `%s' Found visible class=`%s'\n",n->m_label.data(),
        //                                              bClass->name().data());
        if ((bn=m_usedNodes->find(bClass->name()))) // node already present 
        {
          if (n->m_children==0 || n->m_children->findRef(bn)==-1) // no arrow yet
          {
            n->addChild(bn,bcd->prot);
            bn->addParent(n);
            //printf("  Adding node %s to existing base node %s (c=%d,p=%d)\n",
            //       n->m_label.data(),
            //       bn->m_label.data(),
            //       bn->m_children ? bn->m_children->count() : 0,
            //       bn->m_parents  ? bn->m_parents->count()  : 0
            //     );
          }
          //else
          //{
          //  printf("  Class already has an arrow!\n");
          //}
        }
        else 
2417
        {
2418 2419 2420 2421
          QCString tmp_url="";
          if (bClass->isLinkable() && !bClass->isHidden())
          {
            tmp_url=bClass->getReference()+"$"+bClass->getOutputFileBase();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2422 2423 2424 2425
            if (!bClass->anchor().isEmpty())
            {
              tmp_url+="#"+bClass->anchor();
            }
2426
          }
2427
          QCString tooltip = bClass->briefDescriptionAsTooltip();
2428 2429
          bn = new DotNode(m_curNodeNumber++,
              bClass->displayName(),
2430
              tooltip,
2431 2432
              tmp_url.data()
              );
2433 2434
          n->addChild(bn,bcd->prot);
          bn->addParent(n);
2435 2436 2437 2438 2439 2440 2441 2442
          //printf("  Adding node %s to new base node %s (c=%d,p=%d)\n",
          //   n->m_label.data(),
          //   bn->m_label.data(),
          //   bn->m_children ? bn->m_children->count() : 0,
          //   bn->m_parents  ? bn->m_parents->count()  : 0
          //  );
          //printf("  inserting %s (%p)\n",bClass->name().data(),bn);
          m_usedNodes->insert(bClass->name(),bn); // add node to the used list
2443
        }
2444
        if (!bClass->visited && !hideSuper && bClass->subClasses())
2445
        {
2446 2447 2448
          bool wasVisited=bClass->visited;
          bClass->visited=TRUE;
          addHierarchy(bn,bClass,wasVisited);
2449
        }
2450
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2451 2452
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2453
  //printf("end addHierarchy\n");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2454 2455
}

2456
void DotGfxHierarchyTable::addClassList(ClassSDict *cl)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2457
{
2458
  ClassSDict::Iterator cli(*cl);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2459
  ClassDef *cd;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2460
  for (cli.toLast();(cd=cli.current());--cli)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2461
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2462
    //printf("Trying %s subClasses=%d\n",cd->name().data(),cd->subClasses()->count());
2463 2464
    if (cd->getLanguage()==SrcLangExt_VHDL  && !(VhdlDocGen::VhdlClasses)cd->protection()==VhdlDocGen::ENTITYCLASS)
      continue; 
2465 2466 2467
    if (!hasVisibleRoot(cd->baseClasses()) &&
        cd->isVisibleInHierarchy()
       ) // root node in the forest
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2468
    {
2469
      QCString tmp_url="";
2470 2471
      if (cd->isLinkable() && !cd->isHidden()) 
      {
2472
        tmp_url=cd->getReference()+"$"+cd->getOutputFileBase();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2473 2474 2475 2476
        if (!cd->anchor().isEmpty())
        {
          tmp_url+="#"+cd->anchor();
        }
2477
      }
2478
      //printf("Inserting root class %s\n",cd->name().data());
2479
      QCString tooltip = cd->briefDescriptionAsTooltip();
2480 2481
      DotNode *n = new DotNode(m_curNodeNumber++,
          cd->displayName(),
2482
          tooltip,
2483 2484 2485 2486 2487
          tmp_url.data());

      //m_usedNodes->clear();
      m_usedNodes->insert(cd->name(),n);
      m_rootNodes->insert(0,n);   
2488
      if (!cd->visited && cd->subClasses())
2489
      {
2490 2491
        addHierarchy(n,cd,cd->visited);
        cd->visited=TRUE;
2492
      }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2493 2494
    }
  }
2495 2496 2497 2498 2499 2500
}

DotGfxHierarchyTable::DotGfxHierarchyTable()
{
  m_curNodeNumber=0;
  m_rootNodes = new QList<DotNode>;
2501 2502
  m_usedNodes = new QDict<DotNode>(1009); 
  m_usedNodes->setAutoDelete(TRUE);
2503 2504 2505 2506
  m_rootSubgraphs = new DotNodeList;
  
  // build a graph with each class as a node and the inheritance relations
  // as edges
2507 2508 2509 2510
  initClassHierarchy(Doxygen::classSDict);
  initClassHierarchy(Doxygen::hiddenClasses);
  addClassList(Doxygen::classSDict);
  addClassList(Doxygen::hiddenClasses);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
  // m_usedNodes now contains all nodes in the graph
 
  // color the graph into a set of independent subgraphs
  bool done=FALSE; 
  int curColor=0;
  QListIterator<DotNode> dnli(*m_rootNodes);
  while (!done) // there are still nodes to color
  {
    DotNode *n;
    done=TRUE; // we are done unless there are still uncolored nodes
    for (dnli.toLast();(n=dnli.current());--dnli)
    {
      if (n->m_subgraphId==-1) // not yet colored
      {
2525
        //printf("Starting at node %s (%p): %d\n",n->m_label.data(),n,curColor);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2526 2527
        done=FALSE; // still uncolored nodes
        n->m_subgraphId=curColor;
2528
        n->markAsVisible();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2529 2530
        n->colorConnectedNodes(curColor);
        curColor++;
2531
        const DotNode *dn=n->findDocNode();
2532 2533 2534 2535
        if (dn!=0) 
          m_rootSubgraphs->inSort(dn);
        else
          m_rootSubgraphs->inSort(n);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
      }
    }
  }
  
  //printf("Number of independent subgraphs: %d\n",curColor);
  //QListIterator<DotNode> dnli2(*m_rootSubgraphs);
  //DotNode *n;
  //for (dnli2.toFirst();(n=dnli2.current());++dnli2)
  //{
  //  printf("Node %s color=%d (c=%d,p=%d)\n",
  //      n->m_label.data(),n->m_subgraphId,
  //      n->m_children?n->m_children->count():0,
  //      n->m_parents?n->m_parents->count():0);
  //}
}

DotGfxHierarchyTable::~DotGfxHierarchyTable()
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2554
  //printf("DotGfxHierarchyTable::~DotGfxHierarchyTable\n");
2555 2556 2557 2558 2559 2560 2561 2562

  //QDictIterator<DotNode> di(*m_usedNodes);
  //DotNode *n;
  //for (;(n=di.current());++di)
  //{
  //  printf("Node %p: %s\n",n,n->label().data());
  //}
  
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2563 2564 2565 2566 2567 2568 2569
  delete m_rootNodes;
  delete m_usedNodes;
  delete m_rootSubgraphs;
}

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

2570
int DotClassGraph::m_curNodeNumber = 0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2571

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2572
void DotClassGraph::addClass(ClassDef *cd,DotNode *n,int prot,
2573
    const char *label,const char *usedName,const char *templSpec,bool base,int distance)
2574
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2575 2576
  if (Config_getBool("HIDE_UNDOC_CLASSES") && !cd->isLinkable()) return;

2577
  int edgeStyle = (label || prot==EdgeInfo::Orange) ? EdgeInfo::Dashed : EdgeInfo::Solid;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2578
  QCString className;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2579 2580 2581 2582 2583 2584
  if (usedName) // name is a typedef
  {
    className=usedName;
  }
  else if (templSpec) // name has a template part
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2585
    className=insertTemplateSpecifierInScope(cd->name(),templSpec);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2586 2587 2588
  }
  else // just a normal name
  {
2589
    className=cd->displayName();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2590
  }
2591 2592
  //printf("DotClassGraph::addClass(class=`%s',parent=%s,prot=%d,label=%s,dist=%d,usedName=%s,templSpec=%s,base=%d)\n",
  //                                 className.data(),n->m_label.data(),prot,label,distance,usedName,templSpec,base);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2593
  DotNode *bn = m_usedNodes->find(className);
2594 2595
  if (bn) // class already inserted
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
    if (base)
    {
      n->addChild(bn,prot,edgeStyle,label);
      bn->addParent(n);
    }
    else
    {
      bn->addChild(n,prot,edgeStyle,label);
      n->addParent(bn);
    }
2606
    bn->setDistance(distance);
2607 2608 2609 2610
    //printf(" add exiting node %s of %s\n",bn->m_label.data(),n->m_label.data());
  }
  else // new class
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2611
    QCString displayName=className;
2612
    if (Config_getBool("HIDE_SCOPE_NAMES")) displayName=stripScope(displayName);
2613
    QCString tmp_url;
2614
    if (cd->isLinkable() && !cd->isHidden()) 
2615 2616
    {
      tmp_url=cd->getReference()+"$"+cd->getOutputFileBase();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2617 2618 2619 2620
      if (!cd->anchor().isEmpty())
      {
        tmp_url+="#"+cd->anchor();
      }
2621
    }
2622
    QCString tooltip = cd->briefDescriptionAsTooltip();
2623
    bn = new DotNode(m_curNodeNumber++,
2624
        displayName,
2625
        tooltip,
2626
        tmp_url.data(),
2627 2628
        FALSE,        // rootNode
        cd
2629
       );
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
    if (base)
    {
      n->addChild(bn,prot,edgeStyle,label);
      bn->addParent(n);
    }
    else
    {
      bn->addChild(n,prot,edgeStyle,label);
      n->addParent(bn);
    }
2640
    bn->setDistance(distance);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2641
    m_usedNodes->insert(className,bn);
2642 2643
    //printf(" add new child node `%s' to %s hidden=%d url=%s\n",
    //    className.data(),n->m_label.data(),cd->isHidden(),tmp_url.data());
2644
    
2645
    buildGraph(cd,bn,base,distance+1);
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
  }
}

void DotClassGraph::determineTruncatedNodes(QList<DotNode> &queue,bool includeParents)
{
  while (queue.count()>0)
  {
    DotNode *n = queue.take(0);
    if (n->isVisible() && n->isTruncated()==DotNode::Unknown)
    {
      bool truncated = FALSE;
      if (n->m_children)
      {
        QListIterator<DotNode> li(*n->m_children);
        DotNode *dn;
        for (li.toFirst();(dn=li.current());++li)
        {
          if (!dn->isVisible()) 
            truncated = TRUE;
          else 
            queue.append(dn);
        }
      }
      if (n->m_parents && includeParents)
      {
        QListIterator<DotNode> li(*n->m_parents);
        DotNode *dn;
        for (li.toFirst();(dn=li.current());++li)
        {
          if (!dn->isVisible()) 
            truncated = TRUE;
          else 
            queue.append(dn);
        }
      }
      n->markAsTruncated(truncated);
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2683 2684 2685
  }
}

2686 2687
bool DotClassGraph::determineVisibleNodes(DotNode *rootNode,
                                          int maxNodes,bool includeParents)
2688
{
2689 2690 2691 2692 2693 2694 2695 2696 2697
  QList<DotNode> childQueue;
  QList<DotNode> parentQueue;
  QArray<int> childTreeWidth;
  QArray<int> parentTreeWidth;
  childQueue.append(rootNode);
  if (includeParents) parentQueue.append(rootNode);
  bool firstNode=TRUE; // flag to force reprocessing rootNode in the parent loop 
                       // despite being marked visible in the child loop
  while ((childQueue.count()>0 || parentQueue.count()>0) && maxNodes>0)
2698
  {
2699
    static int maxDistance = Config_getInt("MAX_DOT_GRAPH_DEPTH");
2700
    if (childQueue.count()>0)
2701
    {
2702 2703
      DotNode *n = childQueue.take(0);
      int distance = n->distance();
2704
      if (!n->isVisible() && distance<=maxDistance) // not yet processed
2705
      {
2706
        if (distance>0)
2707
        {
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
          int oldSize=(int)childTreeWidth.size();
          if (distance>oldSize)
          {
            childTreeWidth.resize(QMAX(childTreeWidth.size(),(uint)distance));
            int i; for (i=oldSize;i<distance;i++) childTreeWidth[i]=0;
          }
          childTreeWidth[distance-1]+=n->label().length();
        }
        n->markAsVisible();
        maxNodes--;
        // add direct children
        if (n->m_children)
        {
          QListIterator<DotNode> li(*n->m_children);
          DotNode *dn;
          for (li.toFirst();(dn=li.current());++li)
          {
            childQueue.append(dn);
          }
2727 2728
        }
      }
2729 2730 2731 2732
    }
    if (includeParents && parentQueue.count()>0)
    {
      DotNode *n = parentQueue.take(0);
2733
      if ((!n->isVisible() || firstNode) && n->distance()<=maxDistance) // not yet processed
2734
      {
2735 2736 2737
        firstNode=FALSE;
        int distance = n->distance();
        if (distance>0)
2738
        {
2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
          int oldSize = (int)parentTreeWidth.size();
          if (distance>oldSize)
          {
            parentTreeWidth.resize(QMAX(parentTreeWidth.size(),(uint)distance));
            int i; for (i=oldSize;i<distance;i++) parentTreeWidth[i]=0;
          }
          parentTreeWidth[distance-1]+=n->label().length();
        }
        n->markAsVisible();
        maxNodes--;
        // add direct parents
        if (n->m_parents)
        {
          QListIterator<DotNode> li(*n->m_parents);
          DotNode *dn;
          for (li.toFirst();(dn=li.current());++li)
          {
            parentQueue.append(dn);
          }
2758 2759 2760 2761
        }
      }
    }
  }
2762
  if (Config_getBool("UML_LOOK")) return FALSE; // UML graph are always top to bottom
2763 2764 2765 2766 2767
  int maxWidth=0;
  int maxHeight=(int)QMAX(childTreeWidth.size(),parentTreeWidth.size());
  uint i;
  for (i=0;i<childTreeWidth.size();i++)
  {
2768
    if (childTreeWidth.at(i)>maxWidth) maxWidth=childTreeWidth.at(i);
2769 2770 2771
  }
  for (i=0;i<parentTreeWidth.size();i++)
  {
2772
    if (parentTreeWidth.at(i)>maxWidth) maxWidth=parentTreeWidth.at(i);
2773 2774 2775 2776 2777 2778
  }
  //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.
2779 2780
}

2781
void DotClassGraph::buildGraph(ClassDef *cd,DotNode *n,bool base,int distance)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2782
{
2783 2784
  //printf("DocClassGraph::buildGraph(%s,distance=%d,base=%d)\n",
  //    cd->name().data(),distance,base);
2785 2786
  // ---- Add inheritance relations

2787
  if (m_graphType == DotNode::Inheritance || m_graphType==DotNode::Collaboration)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2788
  {
2789 2790
    BaseClassList *bcl = base ? cd->baseClasses() : cd->subClasses();
    if (bcl)
2791
    {
2792 2793 2794 2795 2796 2797
      BaseClassListIterator bcli(*bcl);
      BaseClassDef *bcd;
      for ( ; (bcd=bcli.current()) ; ++bcli )
      {
        //printf("-------- inheritance relation %s->%s templ=`%s'\n",
        //            cd->name().data(),bcd->classDef->name().data(),bcd->templSpecifiers.data());
2798
        addClass(bcd->classDef,n,bcd->prot,0,bcd->usedName,
2799
            bcd->templSpecifiers,base,distance); 
2800
      }
2801
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2802
  }
2803
  if (m_graphType == DotNode::Collaboration)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2804
  {
2805 2806
    // ---- Add usage relations
    
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2807
    UsesClassDict *dict = 
2808 2809 2810
      base ? cd->usedImplementationClasses() : 
             cd->usedByImplementationClasses()
      ;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2811
    if (dict)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2812
    {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2813 2814 2815
      UsesClassDictIterator ucdi(*dict);
      UsesClassDef *ucd;
      for (;(ucd=ucdi.current());++ucdi)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2816
      {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2817 2818 2819 2820
        QCString label;
        QDictIterator<void> dvi(*ucd->accessors);
        const char *s;
        bool first=TRUE;
2821 2822 2823
        int count=0;
        int maxLabels=10;
        for (;(s=dvi.currentKey()) && count<maxLabels;++dvi,++count)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2824
        {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2825 2826 2827 2828 2829 2830 2831
          if (first) 
          {
            label=s;
            first=FALSE;
          }
          else
          {
2832
            label+=QCString("\n")+s;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2833
          }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2834
        }
2835 2836
        if (count==maxLabels) label+="\n...";
        //printf("addClass: %s templSpec=%s\n",ucd->classDef->name().data(),ucd->templSpecifiers.data());
2837
        addClass(ucd->classDef,n,EdgeInfo::Purple,label,0,
2838
            ucd->templSpecifiers,base,distance);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2839 2840 2841
      }
    }
  }
2842 2843 2844

  // ---- Add template instantiation relations

2845 2846
  static bool templateRelations = Config_getBool("TEMPLATE_RELATIONS");
  if (templateRelations)
2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
  {
    if (base) // template relations for base classes
    {
      ClassDef *templMaster=cd->templateMaster();
      if (templMaster)
      {
        QDictIterator<ClassDef> cli(*templMaster->getTemplateInstances());
        ClassDef *templInstance;
        for (;(templInstance=cli.current());++cli)
        {
          if (templInstance==cd)
          {
2859
            addClass(templMaster,n,EdgeInfo::Orange,cli.currentKey(),0,
2860
                0,TRUE,distance);
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873
          }
        }
      }
    }
    else // template relations for super classes
    {
      QDict<ClassDef> *templInstances = cd->getTemplateInstances();
      if (templInstances)
      {
        QDictIterator<ClassDef> cli(*templInstances);
        ClassDef *templInstance;
        for (;(templInstance=cli.current());++cli)
        {
2874
          addClass(templInstance,n,EdgeInfo::Orange,cli.currentKey(),0,
2875
              0,FALSE,distance);
2876 2877 2878 2879
        }
      }
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2880 2881
}

2882
DotClassGraph::DotClassGraph(ClassDef *cd,DotNode::GraphType t)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2883
{
2884
  //printf("--------------- DotClassGraph::DotClassGraph `%s'\n",cd->displayName().data());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2885
  m_graphType = t;
2886
  QCString tmp_url="";
2887 2888 2889
  if (cd->isLinkable() && !cd->isHidden()) 
  {
    tmp_url=cd->getReference()+"$"+cd->getOutputFileBase();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2890 2891 2892 2893
    if (!cd->anchor().isEmpty())
    {
      tmp_url+="#"+cd->anchor();
    }
2894
  }
2895
  QCString className = cd->displayName();
2896
  QCString tooltip = cd->briefDescriptionAsTooltip();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2897
  m_startNode = new DotNode(m_curNodeNumber++,
2898
                            className,
2899
                            tooltip,
2900
                            tmp_url.data(),
2901 2902
                            TRUE,                      // is a root node
                            cd
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2903
                           );
2904
  m_startNode->setDistance(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2905
  m_usedNodes = new QDict<DotNode>(1009);
2906
  m_usedNodes->insert(className,m_startNode);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2907

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2908
  //printf("Root node %s\n",cd->name().data());
2909 2910
  //if (m_recDepth>0) 
  //{
2911 2912
    buildGraph(cd,m_startNode,TRUE,1);
    if (t==DotNode::Inheritance) buildGraph(cd,m_startNode,FALSE,1);
2913 2914
  //}

2915
  static int maxNodes = Config_getInt("DOT_GRAPH_MAX_NODES");
2916 2917 2918 2919 2920 2921
  //int directChildNodes = 1;
  //if (m_startNode->m_children!=0) 
  //  directChildNodes+=m_startNode->m_children->count();
  //if (t==DotNode::Inheritance && m_startNode->m_parents!=0)
  //  directChildNodes+=m_startNode->m_parents->count();
  //if (directChildNodes>maxNodes) maxNodes=directChildNodes;
2922 2923
  //openNodeQueue.append(m_startNode);
  m_lrRank = determineVisibleNodes(m_startNode,maxNodes,t==DotNode::Inheritance);
2924 2925 2926 2927
  QList<DotNode> openNodeQueue;
  openNodeQueue.append(m_startNode);
  determineTruncatedNodes(openNodeQueue,t==DotNode::Inheritance);

2928
  m_diskName = cd->getFileBase().copy();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2929 2930
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
2931
bool DotClassGraph::isTrivial() const
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2932
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2933
  static bool umlLook = Config_getBool("UML_LOOK");
2934
  if (m_graphType==DotNode::Inheritance)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2935 2936
    return m_startNode->m_children==0 && m_startNode->m_parents==0;
  else
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2937
    return !umlLook && m_startNode->m_children==0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2938 2939
}

2940
bool DotClassGraph::isTooBig() const
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2941
{
2942 2943 2944 2945 2946 2947 2948 2949
  static int maxNodes = Config_getInt("DOT_GRAPH_MAX_NODES");
  int numNodes = 0;
  numNodes+= m_startNode->m_children ? m_startNode->m_children->count() : 0;
  if (m_graphType==DotNode::Inheritance)
  {
    numNodes+= m_startNode->m_parents ? m_startNode->m_parents->count() : 0;
  }
  return numNodes>=maxNodes;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2950 2951
}

2952
DotClassGraph::~DotClassGraph()
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2953
{
2954 2955
  deleteNodes(m_startNode);
  delete m_usedNodes;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2956 2957
}

2958 2959 2960 2961 2962 2963 2964 2965
/*! Computes a 16 byte md5 checksum for a given dot graph.
 *  The md5 checksum is returned as a 32 character ASCII string.
 */
QCString computeMd5Signature(DotNode *root,
                   DotNode::GraphType gt,
                   GraphOutputFormat format,
                   bool lrRank,
                   bool renderParents,
2966
                   bool backArrows,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2967
                   const QCString &title,
2968
                   QCString &graphStr
2969 2970
                  )
{
2971 2972
  bool reNumber=TRUE;
    
2973
  //printf("computeMd5Signature\n");
2974 2975
  QGString buf;
  FTextStream md5stream(&buf);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
2976
  writeGraphHeader(md5stream,title);
2977 2978
  if (lrRank)
  {
2979
    md5stream << "  rankdir=\"LR\";" << endl;
2980 2981
  }
  root->clearWriteFlag();
2982 2983 2984 2985 2986 2987 2988
  root->write(md5stream, 
      gt,
      format,
      gt!=DotNode::CallGraph && gt!=DotNode::Dependency,
      TRUE,
      backArrows,
      reNumber);
2989 2990 2991 2992 2993 2994
  if (renderParents && root->m_parents) 
  {
    QListIterator<DotNode>  dnli(*root->m_parents);
    DotNode *pn;
    for (dnli.toFirst();(pn=dnli.current());++dnli)
    {
2995
      if (pn->isVisible()) 
2996
      {
2997 2998 2999 3000 3001 3002 3003 3004
        root->writeArrow(md5stream,                              // stream
            gt,                                                  // graph type
            format,                                              // output format
            pn,                                                  // child node
            pn->m_edgeInfo->at(pn->m_children->findRef(root)),   // edge info
            FALSE,                                               // topDown?
            backArrows,                                          // point back?
            reNumber                                             // renumber nodes
3005 3006
            );
      }
3007 3008 3009 3010 3011 3012 3013 3014
      pn->write(md5stream,      // stream
                gt,             // graph type
                format,         // output format
                TRUE,           // topDown?
                FALSE,          // toChildren?
                backArrows,     // backward pointing arrows?
                reNumber        // renumber nodes?
               );
3015 3016
    }
  }
3017
  writeGraphFooter(md5stream);
3018
  uchar md5_sig[16];
3019
  QCString sigStr(33);
3020
  MD5Buffer((const unsigned char *)buf.data(),buf.length(),md5_sig);
3021
  MD5SigToString(md5_sig,sigStr.data(),33);
3022 3023 3024 3025
  if (reNumber)
  {
    resetReNumbering();
  }
3026
  graphStr=buf.data();
3027 3028 3029 3030
  //printf("md5: %s | file: %s\n",sigStr,baseName.data());
  return sigStr;
}

3031 3032 3033 3034 3035 3036
static bool updateDotGraph(DotNode *root,
                           DotNode::GraphType gt,
                           const QCString &baseName,
                           GraphOutputFormat format,
                           bool lrRank,
                           bool renderParents,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3037 3038
                           bool backArrows,
                           const QCString &title=QCString()
3039 3040 3041 3042 3043
                          )
{
  QCString theGraph;
  // TODO: write graph to theGraph, then compute md5 checksum
  QCString md5 = computeMd5Signature(
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3044 3045
                   root,gt,format,lrRank,renderParents,
                   backArrows,title,theGraph);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3046 3047
  QFile f(baseName+".dot");
  if (f.open(IO_WriteOnly))
3048
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3049 3050
    FTextStream t(&f);
    t << theGraph;
3051
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3052
  return checkAndUpdateMd5Signature(baseName,md5); // graph needs to be regenerated
3053 3054
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3055
QCString DotClassGraph::diskName() const
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3056
{
3057
  QCString result=m_diskName.copy();
3058 3059
  switch (m_graphType)
  {
3060
    case DotNode::Collaboration:
3061 3062
      result+="_coll_graph";
      break;
3063 3064 3065 3066
    //case Interface:
    //  result+="_intf_graph";
    //  break;
    case DotNode::Inheritance:
3067 3068
      result+="_inherit_graph";
      break;
3069 3070 3071
    default:
      ASSERT(0);
      break;
3072 3073
  }
  return result;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3074 3075
}

3076
QCString DotClassGraph::writeGraph(FTextStream &out,
3077 3078
                               GraphOutputFormat format,
                               const char *path,
3079
                               const char *fileName,
3080
                               const char *relPath,
3081
                               bool /*isTBRank*/,
3082 3083
                               bool generateImageMap,
                               int graphId) const
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3084 3085 3086
{
  QDir d(path);
  // store the original directory
3087 3088
  if (!d.exists())
  {
3089
    err("Output dir %s does not exist!\n",path); exit(1);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3090
  }
3091
  static bool usePDFLatex = Config_getBool("USE_PDFLATEX");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3092 3093

  QCString baseName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3094 3095 3096
  QCString mapName;
  switch (m_graphType)
  {
3097
    case DotNode::Collaboration:
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3098 3099
      mapName="coll_map";
      break;
3100 3101 3102 3103
    //case Interface:
    //  mapName="intf_map";
    //  break;
    case DotNode::Inheritance:
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3104 3105
      mapName="inherit_map";
      break;
3106 3107 3108
    default:
      ASSERT(0);
      break;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3109
  }
3110
  baseName = convertNameToFile(diskName());
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3111

3112
  // derive target file names from baseName
3113
  QCString imgExt = Config_getEnum("DOT_IMAGE_FORMAT");
3114
  QCString absBaseName = d.absPath().utf8()+"/"+baseName;
3115 3116 3117 3118 3119
  QCString absDotName  = absBaseName+".dot";
  QCString absMapName  = absBaseName+".map";
  QCString absPdfName  = absBaseName+".pdf";
  QCString absEpsName  = absBaseName+".eps";
  QCString absImgName  = absBaseName+"."+imgExt;
3120

3121
  bool regenerate = FALSE;
3122 3123
  if (updateDotGraph(m_startNode,
                 m_graphType,
3124
                 absBaseName,
3125
                 format,
3126
                 m_lrRank,
3127
                 m_graphType==DotNode::Inheritance,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3128 3129
                 TRUE,
                 m_startNode->label()
3130 3131 3132 3133 3134
                ) ||
      !checkDeliverables(format==BITMAP ? absImgName : 
                         usePDFLatex    ? absPdfName : absEpsName,
                         format==BITMAP && generateImageMap ? absMapName : QCString())
     )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3135
  {
3136
    regenerate=TRUE;
3137
    if (format==BITMAP) // run dot to create a bitmap image
3138
    {
3139
      QCString dotArgs(maxCmdLine);
3140

3141 3142 3143 3144 3145 3146
      DotRunner *dotRun = new DotRunner(absDotName,
                              d.absPath().data(),TRUE,absImgName);
      dotRun->addJob(imgExt,absImgName);
      if (generateImageMap) dotRun->addJob(MAP_CMD,absMapName);
      DotManager::instance()->addRun(dotRun);

3147 3148 3149
    }
    else if (format==EPS) // run dot to create a .eps image
    {
3150 3151
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),FALSE);
      if (usePDFLatex)
3152
      {
3153
        dotRun->addJob("pdf",absPdfName);
3154
      }
3155
      else
3156
      {
3157
        dotRun->addJob("ps",absEpsName);
3158
      }
3159
      DotManager::instance()->addRun(dotRun);
3160 3161
    }
  }
3162
  Doxygen::indexList->addImageFile(baseName+"."+imgExt);
3163

3164
  if (format==BITMAP && generateImageMap) // produce HTML to include the image
3165
  {
3166 3167
    QCString mapLabel = escapeCharsInString(m_startNode->m_label,FALSE)+"_"+
                        escapeCharsInString(mapName,FALSE);
3168
    if (imgExt=="svg") // add link to SVG file without map file
3169
    {
3170 3171 3172 3173 3174
      out << "<div class=\"center\">";
      if (regenerate || !writeSVGFigureLink(out,relPath,baseName,absImgName)) // need to patch the links in the generated SVG file
      {
        if (regenerate)
        {
3175
          DotManager::instance()->addSVGConversion(absImgName,relPath,FALSE,QCString(),TRUE,graphId);
3176 3177 3178 3179 3180
        }
        int mapId = DotManager::instance()->addSVGObject(fileName,baseName,absImgName,relPath);
        out << "<!-- SVG " << mapId << " -->" << endl;
      }
      out << "</div>" << endl;
3181
    }
3182
    else // add link to bitmap file with image map
3183
    {
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
      out << "<div class=\"center\">";
      out << "<img src=\"" << relPath << baseName << "." 
        << imgExt << "\" border=\"0\" usemap=\"#"
        << mapLabel << "\" alt=\"";
      switch (m_graphType)
      {
        case DotNode::Collaboration:
          out << "Collaboration graph";
          break;
        case DotNode::Inheritance:
          out << "Inheritance graph";
          break;
        default:
          ASSERT(0);
          break;
      } 
      out << "\"/>";
      out << "</div>" << endl;

      if (regenerate || !insertMapFile(out,absMapName,relPath,mapLabel))
      {
        int mapId = DotManager::instance()->addMap(fileName,absMapName,relPath,
            FALSE,QCString(),mapLabel);
        out << "<!-- MAP " << mapId << " -->" << endl;
      }
3209 3210
    }
  }
3211
  else if (format==EPS) // produce tex to include the .eps image
3212
  {
3213 3214 3215 3216 3217
    if (regenerate || !writeVecGfxFigure(out,baseName,absBaseName))
    {
      int figId = DotManager::instance()->addFigure(fileName,baseName,absBaseName,FALSE /*TRUE*/);
      out << endl << "% FIG " << figId << endl;
    }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3218
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3219
  if (!regenerate) removeDotGraph(absDotName);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3220

3221
  return baseName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3222 3223 3224 3225
}

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

3226
void DotClassGraph::writeXML(FTextStream &t)
3227 3228 3229 3230 3231
{
  QDictIterator<DotNode> dni(*m_usedNodes);
  DotNode *node;
  for (;(node=dni.current());++dni)
  {
3232
    node->writeXML(t,TRUE);
3233 3234 3235
  }
}

3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
void DotClassGraph::writeDocbook(FTextStream &t)
{
  QDictIterator<DotNode> dni(*m_usedNodes);
  DotNode *node;
  for (;(node=dni.current());++dni)
  {
    node->writeDocbook(t,TRUE);
  }
}

3246
void DotClassGraph::writeDEF(FTextStream &t)
3247 3248 3249 3250 3251 3252 3253 3254 3255
{
  QDictIterator<DotNode> dni(*m_usedNodes);
  DotNode *node;
  for (;(node=dni.current());++dni)
  {
    node->writeDEF(t);
  }
}

3256 3257
//--------------------------------------------------------------------

3258
int DotInclDepGraph::m_curNodeNumber = 0;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3259

3260
void DotInclDepGraph::buildGraph(DotNode *n,FileDef *fd,int distance)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3261
{
3262 3263
  QList<IncludeInfo> *includeFiles = 
     m_inverse ? fd->includedByFileList() : fd->includeFileList();
3264
  if (includeFiles)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3265
  {
3266 3267 3268
    QListIterator<IncludeInfo> ili(*includeFiles);
    IncludeInfo *ii;
    for (;(ii=ili.current());++ili)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3269
    {
3270 3271 3272 3273 3274
      FileDef *bfd = ii->fileDef;
      QCString in  = ii->includeName;
      //printf(">>>> in=`%s' bfd=%p\n",ii->includeName.data(),bfd);
      bool doc=TRUE,src=FALSE;
      if (bfd)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3275
      {
3276 3277 3278
        in  = bfd->absFilePath();  
        doc = bfd->isLinkable() && !bfd->isHidden();
        src = bfd->generateSourceFile();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3279
      }
3280
      if (doc || src || !Config_getBool("HIDE_UNDOC_RELATIONS"))
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3281
      {
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292
        QCString url="";
        if (bfd) url=bfd->getOutputFileBase().copy();
        if (!doc && src)
        {
          url=bfd->getSourceFileBase();
        }
        DotNode *bn  = m_usedNodes->find(in);
        if (bn) // file is already a node in the graph
        {
          n->addChild(bn,0,0,0);
          bn->addParent(n);
3293
          bn->setDistance(distance);
3294 3295 3296 3297
        }
        else
        {
          QCString tmp_url;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3298 3299 3300 3301 3302 3303
          QCString tooltip;
          if (bfd) 
          {
            tmp_url=doc || src ? bfd->getReference()+"$"+url : QCString();
            tooltip = bfd->briefDescriptionAsTooltip();
          }
3304
          bn = new DotNode(
3305 3306 3307 3308 3309 3310
              m_curNodeNumber++, // n
              ii->includeName,   // label
              tooltip,           // tip
              tmp_url,           // url
              FALSE,             // rootNode
              0                  // cd
3311 3312 3313 3314
              );
          n->addChild(bn,0,0,0);
          bn->addParent(n);
          m_usedNodes->insert(in,bn);
3315
          bn->setDistance(distance);
3316

3317
          if (bfd) buildGraph(bn,bfd,distance+1);
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327
        }
      }
    }
  }
}

void DotInclDepGraph::determineVisibleNodes(QList<DotNode> &queue, int &maxNodes)
{
  while (queue.count()>0 && maxNodes>0)
  {
3328
    static int maxDistance = Config_getInt("MAX_DOT_GRAPH_DEPTH");
3329
    DotNode *n = queue.take(0);
3330
    if (!n->isVisible() && n->distance()<=maxDistance) // not yet processed
3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
    {
      n->markAsVisible();
      maxNodes--;
      // add direct children
      if (n->m_children)
      {
        QListIterator<DotNode> li(*n->m_children);
        DotNode *dn;
        for (li.toFirst();(dn=li.current());++li)
        {
          queue.append(dn);
        }
      }
    }
  }
}

void DotInclDepGraph::determineTruncatedNodes(QList<DotNode> &queue)
{
  while (queue.count()>0)
  {
    DotNode *n = queue.take(0);
    if (n->isVisible() && n->isTruncated()==DotNode::Unknown)
    {
      bool truncated = FALSE;
      if (n->m_children)
      {
        QListIterator<DotNode> li(*n->m_children);
        DotNode *dn;
        for (li.toFirst();(dn=li.current());++li)
        {
          if (!dn->isVisible()) 
            truncated = TRUE;
          else 
            queue.append(dn);
3366
        }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3367
      }
3368
      n->markAsTruncated(truncated);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3369 3370 3371 3372
    }
  }
}

3373 3374

DotInclDepGraph::DotInclDepGraph(FileDef *fd,bool inverse)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3375
{
3376
  m_inverse = inverse;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3377
  ASSERT(fd!=0);
3378 3379
  m_diskName  = fd->getFileBase().copy();
  QCString tmp_url=fd->getReference()+"$"+fd->getFileBase();
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3380
  m_startNode = new DotNode(m_curNodeNumber++,
3381
                            fd->docName(),
3382
                            "",
3383
                            tmp_url.data(),
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3384 3385
                            TRUE     // root node
                           );
3386
  m_startNode->setDistance(0);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3387 3388
  m_usedNodes = new QDict<DotNode>(1009);
  m_usedNodes->insert(fd->absFilePath(),m_startNode);
3389 3390 3391 3392 3393 3394 3395 3396
  buildGraph(m_startNode,fd,1);

  static int nodes = Config_getInt("DOT_GRAPH_MAX_NODES");
  int maxNodes = nodes;
  //int directChildNodes = 1;
  //if (m_startNode->m_children!=0) 
  //  directChildNodes+=m_startNode->m_children->count();
  //if (directChildNodes>maxNodes) maxNodes=directChildNodes;
3397 3398 3399 3400 3401 3402
  QList<DotNode> openNodeQueue;
  openNodeQueue.append(m_startNode);
  determineVisibleNodes(openNodeQueue,maxNodes);
  openNodeQueue.clear();
  openNodeQueue.append(m_startNode);
  determineTruncatedNodes(openNodeQueue);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3403 3404 3405 3406
}

DotInclDepGraph::~DotInclDepGraph()
{
3407
  deleteNodes(m_startNode);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3408 3409 3410 3411 3412
  delete m_usedNodes;
}

QCString DotInclDepGraph::diskName() const
{
3413 3414 3415
  QCString result=m_diskName.copy();
  if (m_inverse) result+="_dep";
  result+="_incl";
3416
  return convertNameToFile(result); 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3417 3418
}

3419
QCString DotInclDepGraph::writeGraph(FTextStream &out,
3420
                                 GraphOutputFormat format,
3421
                                 const char *path,
3422
                                 const char *fileName,
3423
                                 const char *relPath,
3424 3425
                                 bool generateImageMap,
                                 int graphId
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3426
                                ) const
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3427 3428 3429
{
  QDir d(path);
  // store the original directory
3430 3431
  if (!d.exists())
  {
3432
    err("Output dir %s does not exist!\n",path); exit(1);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3433
  }
3434
  static bool usePDFLatex = Config_getBool("USE_PDFLATEX");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3435

3436 3437 3438
  QCString baseName=m_diskName;
  if (m_inverse) baseName+="_dep";
  baseName+="_incl";
3439
  baseName=convertNameToFile(baseName);
3440
  QCString mapName=escapeCharsInString(m_startNode->m_label,FALSE);
3441
  if (m_inverse) mapName+="dep";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3442

3443
  QCString imgExt = Config_getEnum("DOT_IMAGE_FORMAT");
3444
  QCString absBaseName = d.absPath().utf8()+"/"+baseName;
3445 3446 3447 3448 3449
  QCString absDotName  = absBaseName+".dot";
  QCString absMapName  = absBaseName+".map";
  QCString absPdfName  = absBaseName+".pdf";
  QCString absEpsName  = absBaseName+".eps";
  QCString absImgName  = absBaseName+"."+imgExt;
3450

3451
  bool regenerate = FALSE;
3452
  if (updateDotGraph(m_startNode,
3453
                 DotNode::Dependency,
3454
                 absBaseName,
3455
                 format,
3456
                 FALSE,        // lrRank
3457
                 FALSE,        // renderParents
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3458 3459
                 m_inverse,    // backArrows
                 m_startNode->label()
3460 3461 3462 3463 3464
                ) ||
      !checkDeliverables(format==BITMAP ? absImgName :
                         usePDFLatex ? absPdfName : absEpsName,
                         format==BITMAP && generateImageMap ? absMapName : QCString())
     )
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3465
  {
3466
    regenerate=TRUE;
3467
    if (format==BITMAP)
3468
    {
3469 3470
      // run dot to create a bitmap image
      QCString dotArgs(maxCmdLine);
3471 3472 3473 3474
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),TRUE,absImgName);
      dotRun->addJob(imgExt,absImgName);
      if (generateImageMap) dotRun->addJob(MAP_CMD,absMapName);
      DotManager::instance()->addRun(dotRun);
3475
    }
3476
    else if (format==EPS)
3477
    {
3478 3479
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),FALSE);
      if (usePDFLatex)
3480
      {
3481
        dotRun->addJob("pdf",absPdfName);
3482
      }
3483
      else
3484
      {
3485
        dotRun->addJob("ps",absEpsName);
3486
      }
3487 3488 3489
      DotManager::instance()->addRun(dotRun);
            
    }    
3490
  }
3491
  Doxygen::indexList->addImageFile(baseName+"."+imgExt);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3492

3493
  if (format==BITMAP && generateImageMap)
3494
  {
3495
    if (imgExt=="svg") // Scalable vector graphics
3496
    {
3497 3498 3499 3500 3501
      out << "<div class=\"center\">";
      if (regenerate || !writeSVGFigureLink(out,relPath,baseName,absImgName)) // need to patch the links in the generated SVG file
      {
        if (regenerate)
        {
3502
          DotManager::instance()->addSVGConversion(absImgName,relPath,FALSE,QCString(),TRUE,graphId);
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
        }
        int mapId = DotManager::instance()->addSVGObject(fileName,baseName,absImgName,relPath);
        out << "<!-- SVG " << mapId << " -->" << endl;
      }
      out << "</div>" << endl;
    }
    else // bitmap graphics
    {
      out << "<div class=\"center\"><img src=\"" << relPath << baseName << "." 
          << imgExt << "\" border=\"0\" usemap=\"#"
          << mapName << "\" alt=\"\"/>";
      out << "</div>" << endl;

      QCString absMapName = absBaseName+".map";
      if (regenerate || !insertMapFile(out,absMapName,relPath,mapName))
      {
        int mapId = DotManager::instance()->addMap(fileName,absMapName,relPath,
                                                 FALSE,QCString(),mapName);
        out << "<!-- MAP " << mapId << " -->" << endl;
      }
3523 3524
    }
  }
3525
  else if (format==EPS) // encapsulated postscript
3526
  {
3527
    if (regenerate || !writeVecGfxFigure(out,baseName,absBaseName))
3528
    {
3529 3530
      int figId = DotManager::instance()->addFigure(fileName,baseName,absBaseName,FALSE);
      out << endl << "% FIG " << figId << endl;
3531 3532
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3533
  if (!regenerate) removeDotGraph(absDotName);
3534

3535
  return baseName;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3536 3537 3538 3539 3540 3541
}

bool DotInclDepGraph::isTrivial() const
{
  return m_startNode->m_children==0;
}
3542

3543 3544 3545 3546 3547 3548 3549
bool DotInclDepGraph::isTooBig() const
{
  static int maxNodes = Config_getInt("DOT_GRAPH_MAX_NODES");
  int numNodes = m_startNode->m_children ? m_startNode->m_children->count() : 0;
  return numNodes>=maxNodes;
}

3550
void DotInclDepGraph::writeXML(FTextStream &t)
3551 3552 3553 3554 3555
{
  QDictIterator<DotNode> dni(*m_usedNodes);
  DotNode *node;
  for (;(node=dni.current());++dni)
  {
3556
    node->writeXML(t,FALSE);
3557 3558 3559
  }
}

3560 3561 3562 3563 3564 3565 3566 3567 3568 3569
void DotInclDepGraph::writeDocbook(FTextStream &t)
{
  QDictIterator<DotNode> dni(*m_usedNodes);
  DotNode *node;
  for (;(node=dni.current());++dni)
  {
    node->writeDocbook(t,FALSE);
  }
}

3570 3571
//-------------------------------------------------------------

3572 3573
int DotCallGraph::m_curNodeNumber = 0;

3574
void DotCallGraph::buildGraph(DotNode *n,MemberDef *md,int distance)
3575
{
3576 3577
  MemberSDict *refs = m_inverse ? md->getReferencedByMembers() : md->getReferencesMembers();
  if (refs)
3578 3579 3580 3581 3582
  {
    MemberSDict::Iterator mri(*refs);
    MemberDef *rmd;
    for (;(rmd=mri.current());++mri)
    {
3583
      if (rmd->showInCallGraph())
3584 3585 3586 3587 3588 3589 3590 3591 3592
      {
        QCString uniqueId;
        uniqueId=rmd->getReference()+"$"+
                 rmd->getOutputFileBase()+"#"+rmd->anchor();
        DotNode *bn  = m_usedNodes->find(uniqueId);
        if (bn) // file is already a node in the graph
        {
          n->addChild(bn,0,0,0);
          bn->addParent(n);
3593
          bn->setDistance(distance);
3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609
        }
        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();
          bn = new DotNode(
              m_curNodeNumber++,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3610
              linkToText(rmd->getLanguage(),name,FALSE),
3611 3612 3613 3614 3615 3616
              tooltip,
              uniqueId,
              0 //distance
              );
          n->addChild(bn,0,0,0);
          bn->addParent(n);
3617
          bn->setDistance(distance);
3618 3619
          m_usedNodes->insert(uniqueId,bn);

3620
          buildGraph(bn,rmd,distance+1);
3621 3622 3623 3624 3625 3626 3627 3628 3629 3630
        }
      }
    }
  }
}

void DotCallGraph::determineVisibleNodes(QList<DotNode> &queue, int &maxNodes)
{
  while (queue.count()>0 && maxNodes>0)
  {
3631
    static int maxDistance = Config_getInt("MAX_DOT_GRAPH_DEPTH");
3632
    DotNode *n = queue.take(0);
3633
    if (!n->isVisible() && n->distance()<=maxDistance) // not yet processed
3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
    {
      n->markAsVisible();
      maxNodes--;
      // add direct children
      if (n->m_children)
      {
        QListIterator<DotNode> li(*n->m_children);
        DotNode *dn;
        for (li.toFirst();(dn=li.current());++li)
        {
          queue.append(dn);
        }
      }
    }
  }
}

void DotCallGraph::determineTruncatedNodes(QList<DotNode> &queue)
{
  while (queue.count()>0)
  {
    DotNode *n = queue.take(0);
    if (n->isVisible() && n->isTruncated()==DotNode::Unknown)
    {
      bool truncated = FALSE;
      if (n->m_children)
      {
        QListIterator<DotNode> li(*n->m_children);
        DotNode *dn;
        for (li.toFirst();(dn=li.current());++li)
        {
          if (!dn->isVisible()) 
            truncated = TRUE;
          else 
            queue.append(dn);
        }
      }
      n->markAsTruncated(truncated);
    }
  }
}



DotCallGraph::DotCallGraph(MemberDef *md,bool inverse)
3679
{
3680
  m_inverse = inverse;
3681
  m_diskName = md->getOutputFileBase()+"_"+md->anchor();
3682
  m_scope    = md->getOuterScope();
3683
  QCString uniqueId;
3684 3685
  uniqueId = md->getReference()+"$"+
             md->getOutputFileBase()+"#"+md->anchor();
3686 3687 3688 3689 3690 3691 3692 3693 3694
  QCString name;
  if (Config_getBool("HIDE_SCOPE_NAMES"))
  {
    name = md->name();
  }
  else
  {
    name = md->qualifiedName();
  }
3695
  m_startNode = new DotNode(m_curNodeNumber++,
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3696
                            linkToText(md->getLanguage(),name,FALSE),
3697
                            "",
3698 3699 3700
                            uniqueId.data(),
                            TRUE     // root node
                           );
3701
  m_startNode->setDistance(0);
3702 3703
  m_usedNodes = new QDict<DotNode>(1009);
  m_usedNodes->insert(uniqueId,m_startNode);
3704
  buildGraph(m_startNode,md,1);
3705

3706 3707 3708 3709 3710 3711
  static int nodes = Config_getInt("DOT_GRAPH_MAX_NODES");
  int maxNodes = nodes;
  //int directChildNodes = 1;
  //if (m_startNode->m_children!=0) 
  //  directChildNodes+=m_startNode->m_children->count();
  //if (directChildNodes>maxNodes) maxNodes=directChildNodes;
3712 3713 3714 3715 3716 3717
  QList<DotNode> openNodeQueue;
  openNodeQueue.append(m_startNode);
  determineVisibleNodes(openNodeQueue,maxNodes);
  openNodeQueue.clear();
  openNodeQueue.append(m_startNode);
  determineTruncatedNodes(openNodeQueue);
3718 3719 3720 3721 3722 3723 3724 3725
}

DotCallGraph::~DotCallGraph()
{
  deleteNodes(m_startNode);
  delete m_usedNodes;
}

3726
QCString DotCallGraph::writeGraph(FTextStream &out, GraphOutputFormat format,
3727
                        const char *path,const char *fileName,
3728 3729
                        const char *relPath,bool generateImageMap,int
                        graphId) const
3730 3731 3732
{
  QDir d(path);
  // store the original directory
3733 3734
  if (!d.exists())
  {
3735
    err("Output dir %s does not exist!\n",path); exit(1);
3736
  }
3737
  static bool usePDFLatex = Config_getBool("USE_PDFLATEX");
3738

3739
  QCString baseName = m_diskName + (m_inverse ? "_icgraph" : "_cgraph");
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3740
  QCString mapName  = baseName;
3741

3742
  QCString imgExt = Config_getEnum("DOT_IMAGE_FORMAT");
3743
  QCString absBaseName = d.absPath().utf8()+"/"+baseName;
3744 3745 3746 3747 3748
  QCString absDotName  = absBaseName+".dot";
  QCString absMapName  = absBaseName+".map";
  QCString absPdfName  = absBaseName+".pdf";
  QCString absEpsName  = absBaseName+".eps";
  QCString absImgName  = absBaseName+"."+imgExt;
3749

Dimitri van Heesch's avatar
Dimitri van Heesch committed
3750
  bool regenerate = FALSE;
3751 3752
  if (updateDotGraph(m_startNode,
                 DotNode::CallGraph,
3753
                 absBaseName,
3754 3755 3756
                 format,
                 TRUE,         // lrRank
                 FALSE,        // renderParents
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3757 3758
                 m_inverse,    // backArrows
                 m_startNode->label()
3759 3760 3761 3762 3763
                ) ||
      !checkDeliverables(format==BITMAP ? absImgName :
                         usePDFLatex ? absPdfName : absEpsName,
                         format==BITMAP && generateImageMap ? absMapName : QCString())
     )
3764
  {
3765
    regenerate=TRUE;
3766
    if (format==BITMAP)
3767
    {
3768 3769
      // run dot to create a bitmap image
      QCString dotArgs(maxCmdLine);
3770 3771 3772 3773 3774
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),TRUE,absImgName);
      dotRun->addJob(imgExt,absImgName);
      if (generateImageMap) dotRun->addJob(MAP_CMD,absMapName);
      DotManager::instance()->addRun(dotRun);

3775 3776
    }
    else if (format==EPS)
3777
    {
3778
      // run dot to create a .eps image
3779 3780
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),FALSE);
      if (usePDFLatex)
3781
      {
3782
        dotRun->addJob("pdf",absPdfName);
3783
      }
3784
      else
3785
      {
3786
        dotRun->addJob("ps",absEpsName);
3787
      }
3788 3789
      DotManager::instance()->addRun(dotRun);

3790 3791
    }
  }
3792
  Doxygen::indexList->addImageFile(baseName+"."+imgExt);
3793

3794
  if (format==BITMAP && generateImageMap)
3795
  {
3796
    if (imgExt=="svg") // Scalable vector graphics
3797
    {
3798 3799 3800 3801 3802
      out << "<div class=\"center\">";
      if (regenerate || !writeSVGFigureLink(out,relPath,baseName,absImgName)) // need to patch the links in the generated SVG file
      {
        if (regenerate)
        {
3803
          DotManager::instance()->addSVGConversion(absImgName,relPath,FALSE,QCString(),TRUE,graphId);
3804 3805 3806 3807 3808
        }
        int mapId = DotManager::instance()->addSVGObject(fileName,baseName,absImgName,relPath);
        out << "<!-- SVG " << mapId << " -->" << endl;
      }
      out << "</div>" << endl;
3809
    }
3810 3811 3812 3813 3814 3815 3816
    else // bitmap graphics
    {
      out << "<div class=\"center\"><img src=\"" << relPath << baseName << "." 
          << imgExt << "\" border=\"0\" usemap=\"#"
          << mapName << "\" alt=\"";
      out << "\"/>";
      out << "</div>" << endl;
3817

3818 3819 3820 3821 3822 3823 3824
      if (regenerate || !insertMapFile(out,absMapName,relPath,mapName))
      {
        int mapId = DotManager::instance()->addMap(fileName,absMapName,relPath,
                                                   FALSE,QCString(),mapName);
        out << "<!-- MAP " << mapId << " -->" << endl;
      }
    }
3825
  }
3826
  else if (format==EPS) // encapsulated postscript
3827
  {
3828
    if (regenerate || !writeVecGfxFigure(out,baseName,absBaseName))
3829
    {
3830 3831
      int figId = DotManager::instance()->addFigure(fileName,baseName,absBaseName,FALSE);
      out << endl << "% FIG " << figId << endl;
3832 3833
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3834
  if (!regenerate) removeDotGraph(absDotName);
3835 3836 3837 3838 3839 3840 3841 3842 3843

  return baseName;
}

bool DotCallGraph::isTrivial() const
{
  return m_startNode->m_children==0;
}

3844 3845 3846 3847 3848 3849 3850
bool DotCallGraph::isTooBig() const
{
  static int maxNodes = Config_getInt("DOT_GRAPH_MAX_NODES");
  int numNodes = m_startNode->m_children ? m_startNode->m_children->count() : 0;
  return numNodes>=maxNodes;
}

3851 3852
//-------------------------------------------------------------

3853
DotDirDeps::DotDirDeps(DirDef *dir) : m_dir(dir)
3854 3855 3856 3857 3858 3859 3860
{
}

DotDirDeps::~DotDirDeps()
{
}

3861
QCString DotDirDeps::writeGraph(FTextStream &out,
3862 3863
                            GraphOutputFormat format,
                            const char *path,
3864
                            const char *fileName,
3865
                            const char *relPath,
3866 3867
                            bool generateImageMap,
                            int graphId) const
3868 3869 3870
{
  QDir d(path);
  // store the original directory
3871 3872
  if (!d.exists())
  {
3873
    err("Output dir %s does not exist!\n",path); exit(1);
3874
  }
3875
  static bool usePDFLatex = Config_getBool("USE_PDFLATEX");
3876 3877

  QCString baseName=m_dir->getOutputFileBase()+"_dep";
3878
  QCString mapName=escapeCharsInString(baseName,FALSE);
3879

3880
  QCString imgExt = Config_getEnum("DOT_IMAGE_FORMAT");
3881
  QCString absBaseName = d.absPath().utf8()+"/"+baseName;
3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
  QCString absDotName  = absBaseName+".dot";
  QCString absMapName  = absBaseName+".map";
  QCString absPdfName  = absBaseName+".pdf";
  QCString absEpsName  = absBaseName+".eps";
  QCString absImgName  = absBaseName+"."+imgExt;

  // compute md5 checksum of the graph were are about to generate
  QGString theGraph;
  FTextStream md5stream(&theGraph);
  m_dir->writeDepGraph(md5stream);
  uchar md5_sig[16];
  QCString sigStr(33);
  MD5Buffer((const unsigned char *)theGraph.data(),theGraph.length(),md5_sig);
  MD5SigToString(md5_sig,sigStr.data(),33);
  bool regenerate=FALSE;
  if (checkAndUpdateMd5Signature(absBaseName,sigStr) ||
      !checkDeliverables(format==BITMAP ? absImgName :
                         usePDFLatex ? absPdfName : absEpsName,
                         format==BITMAP && generateImageMap ? absMapName : QCString())
     )
3902
  {
3903 3904 3905
    regenerate=TRUE;

    QFile f(absDotName);
3906 3907 3908 3909
    if (!f.open(IO_WriteOnly))
    {
      err("Cannot create file %s.dot for writing!\n",baseName.data());
    }
3910
    FTextStream t(&f);
3911
    t << theGraph.data();
3912
    f.close();
3913

3914 3915 3916 3917
    if (format==BITMAP)
    {
      // run dot to create a bitmap image
      QCString dotArgs(maxCmdLine);
3918 3919 3920 3921
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),TRUE,absImgName);
      dotRun->addJob(imgExt,absImgName);
      if (generateImageMap) dotRun->addJob(MAP_CMD,absMapName);
      DotManager::instance()->addRun(dotRun);
3922 3923 3924
    }
    else if (format==EPS)
    {
3925 3926
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),FALSE);
      if (usePDFLatex)
3927
      {
3928
        dotRun->addJob("pdf",absPdfName);
3929
      }
3930
      else
3931
      {
3932
        dotRun->addJob("ps",absEpsName);
3933
      }
3934
      DotManager::instance()->addRun(dotRun);
3935 3936
    }
  }
3937
  Doxygen::indexList->addImageFile(baseName+"."+imgExt);
3938 3939 3940

  if (format==BITMAP && generateImageMap)
  {
3941 3942 3943 3944 3945 3946 3947
    if (imgExt=="svg") // Scalable vector graphics
    {
      out << "<div class=\"center\">";
      if (regenerate || !writeSVGFigureLink(out,relPath,baseName,absImgName)) // need to patch the links in the generated SVG file
      {
        if (regenerate)
        {
3948
          DotManager::instance()->addSVGConversion(absImgName,relPath,FALSE,QCString(),TRUE,graphId);
3949 3950 3951 3952 3953 3954 3955
        }
        int mapId = DotManager::instance()->addSVGObject(fileName,baseName,absImgName,relPath);
        out << "<!-- SVG " << mapId << " -->" << endl;
      }
      out << "</div>" << endl;
    }
    else // bitmap graphics
3956
    {
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
      out << "<div class=\"center\"><img src=\"" << relPath << baseName << "." 
          << imgExt << "\" border=\"0\" usemap=\"#"
          << mapName << "\" alt=\"";
      out << convertToXML(m_dir->displayName());
      out << "\"/>";
      out << "</div>" << endl;

      if (regenerate || !insertMapFile(out,absMapName,relPath,mapName))
      {
        int mapId = DotManager::instance()->addMap(fileName,absMapName,relPath,
                                                   TRUE,QCString(),mapName);
        out << "<!-- MAP " << mapId << " -->" << endl;
      }
3970 3971 3972 3973
    }
  }
  else if (format==EPS)
  {
3974
    if (regenerate || !writeVecGfxFigure(out,baseName,absBaseName))
3975
    {
3976 3977
      int figId = DotManager::instance()->addFigure(fileName,baseName,absBaseName,FALSE);
      out << endl << "% FIG " << figId << endl;
3978 3979
    }
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
3980
  if (!regenerate) removeDotGraph(absDotName);
3981 3982 3983 3984 3985 3986 3987 3988 3989

  return baseName;
}

bool DotDirDeps::isTrivial() const
{
  return m_dir->depGraphIsTrivial();
}

3990 3991
//-------------------------------------------------------------

3992 3993 3994 3995
void generateGraphLegend(const char *path)
{
  QDir d(path);
  // store the original directory
3996 3997
  if (!d.exists())
  {
3998
    err("Output dir %s does not exist!\n",path); exit(1);
3999 4000
  }

4001 4002
  QGString theGraph;
  FTextStream md5stream(&theGraph);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4003
  writeGraphHeader(md5stream,theTranslator->trLegendTitle());
4004
  md5stream << "  Node9 [shape=\"box\",label=\"Inherited\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",fillcolor=\"grey75\",style=\"filled\" fontcolor=\"black\"];\n";
4005
  md5stream << "  Node10 -> Node9 [dir=\"back\",color=\"midnightblue\",fontsize=\"" << FONTSIZE << "\",style=\"solid\",fontname=\"" << FONTNAME << "\"];\n";
4006
  md5stream << "  Node10 [shape=\"box\",label=\"PublicBase\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"black\",URL=\"$classPublicBase" << Doxygen::htmlFileExtension << "\"];\n";
4007
  md5stream << "  Node11 -> Node10 [dir=\"back\",color=\"midnightblue\",fontsize=\"" << FONTSIZE << "\",style=\"solid\",fontname=\"" << FONTNAME << "\"];\n";
4008
  md5stream << "  Node11 [shape=\"box\",label=\"Truncated\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"red\",URL=\"$classTruncated" << Doxygen::htmlFileExtension << "\"];\n";
4009
  md5stream << "  Node13 -> Node9 [dir=\"back\",color=\"darkgreen\",fontsize=\"" << FONTSIZE << "\",style=\"solid\",fontname=\"" << FONTNAME << "\"];\n";
4010
  md5stream << "  Node13 [shape=\"box\",label=\"ProtectedBase\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"black\",URL=\"$classProtectedBase" << Doxygen::htmlFileExtension << "\"];\n";
4011
  md5stream << "  Node14 -> Node9 [dir=\"back\",color=\"firebrick4\",fontsize=\"" << FONTSIZE << "\",style=\"solid\",fontname=\"" << FONTNAME << "\"];\n";
4012
  md5stream << "  Node14 [shape=\"box\",label=\"PrivateBase\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"black\",URL=\"$classPrivateBase" << Doxygen::htmlFileExtension << "\"];\n";
4013
  md5stream << "  Node15 -> Node9 [dir=\"back\",color=\"midnightblue\",fontsize=\"" << FONTSIZE << "\",style=\"solid\",fontname=\"" << FONTNAME << "\"];\n";
4014
  md5stream << "  Node15 [shape=\"box\",label=\"Undocumented\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"grey75\"];\n";
4015
  md5stream << "  Node16 -> Node9 [dir=\"back\",color=\"midnightblue\",fontsize=\"" << FONTSIZE << "\",style=\"solid\",fontname=\"" << FONTNAME << "\"];\n";
4016
  md5stream << "  Node16 [shape=\"box\",label=\"Templ< int >\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"black\",URL=\"$classTempl" << Doxygen::htmlFileExtension << "\"];\n";
4017
  md5stream << "  Node17 -> Node16 [dir=\"back\",color=\"orange\",fontsize=\"" << FONTSIZE << "\",style=\"dashed\",label=\"< int >\",fontname=\"" << FONTNAME << "\"];\n";
4018
  md5stream << "  Node17 [shape=\"box\",label=\"Templ< T >\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"black\",URL=\"$classTempl" << Doxygen::htmlFileExtension << "\"];\n";
4019
  md5stream << "  Node18 -> Node9 [dir=\"back\",color=\"darkorchid3\",fontsize=\"" << FONTSIZE << "\",style=\"dashed\",label=\"m_usedClass\",fontname=\"" << FONTNAME << "\"];\n";
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032
  md5stream << "  Node18 [shape=\"box\",label=\"Used\",fontsize=\"" << FONTSIZE << "\",height=0.2,width=0.4,fontname=\"" << FONTNAME << "\",color=\"black\",URL=\"$classUsed" << Doxygen::htmlFileExtension << "\"];\n";
  writeGraphFooter(md5stream);
  uchar md5_sig[16];
  QCString sigStr(33);
  MD5Buffer((const unsigned char *)theGraph.data(),theGraph.length(),md5_sig);
  MD5SigToString(md5_sig,sigStr.data(),33);
  QCString absBaseName = (QCString)path+"/graph_legend";
  QCString absDotName  = absBaseName+".dot";
  QCString imgExt      = Config_getEnum("DOT_IMAGE_FORMAT");
  QCString imgName     = "graph_legend."+imgExt;
  QCString absImgName  = absBaseName+"."+imgExt;
  if (checkAndUpdateMd5Signature(absBaseName,sigStr) ||
      !checkDeliverables(absImgName))
4033
  {
4034 4035 4036
    QFile dotFile(absDotName);
    if (!dotFile.open(IO_WriteOnly))
    {
4037
      err("Could not open file %s for writing\n",dotFile.name().data());
4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
      return;
    }

    FTextStream dotText(&dotFile); 
    dotText << theGraph;
    dotFile.close();

    // run dot to generate the a bitmap image from the graph

    DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),TRUE,absImgName);
    dotRun->addJob(imgExt,absImgName);
    DotManager::instance()->addRun(dotRun);
4050
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4051 4052 4053 4054
  else
  {
    removeDotGraph(absDotName);
  }
4055
  Doxygen::indexList->addImageFile(imgName);
4056

4057 4058 4059 4060 4061 4062 4063 4064
  if (imgExt=="svg")
  {
    DotManager::instance()->addSVGObject(
        absBaseName+Config_getString("HTML_FILE_EXTENSION"),
        "graph_legend",
        absImgName,QCString());
  }

4065
}
4066

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4067 4068
void writeDotGraphFromFile(const char *inFile,const char *outDir,
                           const char *outFile,GraphOutputFormat format)
4069
{
4070 4071
  QDir d(outDir);
  if (!d.exists())
4072
  {
4073
    err("Output dir %s does not exist!\n",outDir); exit(1);
4074
  }
4075

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4076
  QCString imgExt = Config_getEnum("DOT_IMAGE_FORMAT");
4077
  QCString imgName = (QCString)outFile+"."+imgExt;
4078 4079
  QCString absImgName = d.absPath().utf8()+"/"+imgName;
  QCString absOutFile = d.absPath().utf8()+"/"+outFile;
4080

4081
  DotRunner dotRun(inFile,d.absPath().data(),FALSE,absImgName);
4082 4083
  if (format==BITMAP)
    dotRun.addJob(imgExt,absImgName);
4084
  else // format==EPS
4085
  {
4086 4087 4088 4089 4090 4091 4092 4093
    if (Config_getBool("USE_PDFLATEX"))
    {
      dotRun.addJob("pdf",absOutFile+".pdf");
    }
    else
    {
      dotRun.addJob("ps",absOutFile+".eps");
    }
4094 4095
  }

4096
  dotRun.preventCleanUp();
4097
  if (!dotRun.run())
4098
  {
4099
     return;
4100 4101
  }

4102
  if (format==BITMAP) checkDotResult(absImgName);
4103

4104
  Doxygen::indexList->addImageFile(imgName);
4105

4106
}
4107

4108
 
4109 4110
/*! Writes user defined image map to the output.
 *  \param t text stream to write to
4111 4112
 *  \param inFile just the basename part of the filename
 *  \param outDir output directory
4113
 *  \param relPath relative path the to root of the output dir
4114
 *  \param baseName the base name of the output files
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4115
 *  \param context the scope in which this graph is found (for resolving links)
4116
 *  \param graphId a unique id for this graph, use for dynamic sections
4117
 */
4118
void writeDotImageMapFromFile(FTextStream &t,
4119 4120
                            const QCString &inFile, const QCString &outDir,
                            const QCString &relPath, const QCString &baseName,
4121
                            const QCString &context,int graphId)
4122 4123
{

4124 4125 4126
  QDir d(outDir);
  if (!d.exists())
  {
4127
    err("Output dir %s does not exist!\n",outDir.data()); exit(1);
4128 4129
  }

4130 4131 4132
  QCString mapName = baseName+".map";
  QCString imgExt = Config_getEnum("DOT_IMAGE_FORMAT");
  QCString imgName = baseName+"."+imgExt;
4133
  QCString absOutFile = d.absPath().utf8()+"/"+mapName;
4134

4135
  DotRunner dotRun(inFile,d.absPath().data(),FALSE);
4136
  dotRun.addJob(MAP_CMD,absOutFile);
4137
  dotRun.preventCleanUp();
4138
  if (!dotRun.run())
4139
  {
4140
    return;
4141
  }
4142

4143 4144
  if (imgExt=="svg") // vector graphics
  {
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4145 4146 4147 4148 4149
    //writeSVGFigureLink(t,relPath,inFile,inFile+".svg");
    //DotFilePatcher patcher(inFile+".svg");
    QCString svgName=outDir+"/"+baseName+".svg";
    writeSVGFigureLink(t,relPath,baseName,svgName);
    DotFilePatcher patcher(svgName);
4150
    patcher.addSVGConversion(relPath,TRUE,context,TRUE,graphId);
4151 4152 4153 4154
    patcher.run();
  }
  else // bitmap graphics
  {
4155
    t << "<img src=\"" << relPath << imgName << "\" alt=\""
4156
      << imgName << "\" border=\"0\" usemap=\"#" << mapName << "\"/>" << endl
4157 4158
      << "<map name=\"" << mapName << "\" id=\"" << mapName << "\">";

4159
    convertMapFile(t, absOutFile, relPath ,TRUE, context);
4160 4161 4162

    t << "</map>" << endl;
  }
4163
  d.remove(absOutFile);
4164 4165
}

4166 4167 4168 4169 4170 4171 4172
//-------------------------------------------------------------

DotGroupCollaboration::DotGroupCollaboration(GroupDef* gd)
{
    m_curNodeId = 0;
    QCString tmp_url = gd->getReference()+"$"+gd->getOutputFileBase();
    m_usedNodes = new QDict<DotNode>(1009);
4173 4174
    m_rootNode = new DotNode(m_curNodeId++, gd->groupTitle(), "", tmp_url, TRUE );
    m_rootNode->markAsVisible();
4175 4176 4177 4178 4179
    m_usedNodes->insert(gd->name(), m_rootNode );
    m_edges.setAutoDelete(TRUE);

    m_diskName = gd->getOutputFileBase();

4180
    buildGraph( gd );
4181 4182 4183 4184 4185 4186 4187
}

DotGroupCollaboration::~DotGroupCollaboration()
{
  delete m_usedNodes;
}

4188
void DotGroupCollaboration::buildGraph(GroupDef* gd)
4189 4190 4191 4192 4193 4194
{
  QCString tmp_url;
  //===========================
  // hierarchy.

  // Write parents
4195 4196
  GroupList *groups = gd->partOfGroups();
  if ( groups )
4197
  {
4198
    GroupListIterator gli(*groups);
4199 4200 4201 4202 4203 4204 4205
    GroupDef *d;
    for (gli.toFirst();(d=gli.current());++gli)
    {
      DotNode* nnode = m_usedNodes->find(d->name());
      if ( !nnode )
      { // add node
        tmp_url = d->getReference()+"$"+d->getOutputFileBase();
4206 4207 4208
        QCString tooltip = d->briefDescriptionAsTooltip();
        nnode = new DotNode(m_curNodeId++, d->groupTitle(), tooltip, tmp_url );
        nnode->markAsVisible();
4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226
        m_usedNodes->insert(d->name(), nnode );
      }
      tmp_url = "";
      addEdge( nnode, m_rootNode, DotGroupCollaboration::thierarchy, tmp_url, tmp_url );
    }
  }

  // Add subgroups
  if ( gd->getSubGroups() && gd->getSubGroups()->count() )
  {
    QListIterator<GroupDef> defli(*gd->getSubGroups());
    GroupDef *def;
    for (;(def=defli.current());++defli)
    {
      DotNode* nnode = m_usedNodes->find(def->name());
      if ( !nnode )
      { // add node
        tmp_url = def->getReference()+"$"+def->getOutputFileBase();
4227 4228 4229
        QCString tooltip = def->briefDescriptionAsTooltip();
        nnode = new DotNode(m_curNodeId++, def->groupTitle(), tooltip, tmp_url );
        nnode->markAsVisible();
4230 4231 4232 4233 4234 4235
        m_usedNodes->insert(def->name(), nnode );
      }
      tmp_url = "";
      addEdge( m_rootNode, nnode, DotGroupCollaboration::thierarchy, tmp_url, tmp_url );
    }
  }
4236

4237 4238 4239 4240
  //=======================
  // Write collaboration

  // Add members
4241
  addMemberList( gd->getMemberList(MemberListType_allMembersList) );
4242 4243 4244 4245 4246 4247 4248 4249 4250

  // Add classes
  if ( gd->getClasses() && gd->getClasses()->count() )
  {
    ClassSDict::Iterator defli(*gd->getClasses());
    ClassDef *def;
    for (;(def=defli.current());++defli)
    {
      tmp_url = def->getReference()+"$"+def->getOutputFileBase()+Doxygen::htmlFileExtension;
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4251 4252 4253 4254
      if (!def->anchor().isEmpty())
      {
        tmp_url+="#"+def->anchor();
      }
4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368
      addCollaborationMember( def, tmp_url, DotGroupCollaboration::tclass );          
    }
  }

  // Add namespaces
  if ( gd->getNamespaces() && gd->getNamespaces()->count() )
  {
    NamespaceSDict::Iterator defli(*gd->getNamespaces());
    NamespaceDef *def;
    for (;(def=defli.current());++defli)
    {
      tmp_url = def->getReference()+"$"+def->getOutputFileBase()+Doxygen::htmlFileExtension;
      addCollaborationMember( def, tmp_url, DotGroupCollaboration::tnamespace );          
    }
  }

  // Add files
  if ( gd->getFiles() && gd->getFiles()->count() )
  {
    QListIterator<FileDef> defli(*gd->getFiles());
    FileDef *def;
    for (;(def=defli.current());++defli)
    {
      tmp_url = def->getReference()+"$"+def->getOutputFileBase()+Doxygen::htmlFileExtension;
      addCollaborationMember( def, tmp_url, DotGroupCollaboration::tfile );          
    }
  }

  // Add pages
  if ( gd->getPages() && gd->getPages()->count() )
  {
    PageSDict::Iterator defli(*gd->getPages());
    PageDef *def;
    for (;(def=defli.current());++defli)
    {
      tmp_url = def->getReference()+"$"+def->getOutputFileBase()+Doxygen::htmlFileExtension;
      addCollaborationMember( def, tmp_url, DotGroupCollaboration::tpages );          
    }
  }

  // Add directories
  if ( gd->getDirs() && gd->getDirs()->count() )
  {
    QListIterator<DirDef> defli(*gd->getDirs());
    DirDef *def;
    for (;(def=defli.current());++defli)
    {
      tmp_url = def->getReference()+"$"+def->getOutputFileBase()+Doxygen::htmlFileExtension;
      addCollaborationMember( def, tmp_url, DotGroupCollaboration::tdir );          
    }
  }
}

void DotGroupCollaboration::addMemberList( MemberList* ml )
{
  if ( !( ml && ml->count()) ) return;
  MemberListIterator defli(*ml);
  MemberDef *def;
  for (;(def=defli.current());++defli)
  {
    QCString tmp_url = def->getReference()+"$"+def->getOutputFileBase()+Doxygen::htmlFileExtension
      +"#"+def->anchor();
    addCollaborationMember( def, tmp_url, DotGroupCollaboration::tmember );
  }
}

DotGroupCollaboration::Edge* DotGroupCollaboration::addEdge( 
    DotNode* _pNStart, DotNode* _pNEnd, EdgeType _eType,
    const QCString& _label, const QCString& _url )
{
  // search a existing link.
  QListIterator<Edge> lli(m_edges);
  Edge* newEdge = 0;
  for ( lli.toFirst(); (newEdge=lli.current()); ++lli)
  {
    if ( newEdge->pNStart==_pNStart && 
         newEdge->pNEnd==_pNEnd &&
         newEdge->eType==_eType 
       )
    { // edge already found
      break;
    }
  }
  if ( newEdge==0 ) // new link
  {
    newEdge = new Edge(_pNStart,_pNEnd,_eType);
    m_edges.append( newEdge );
  } 

  if (!_label.isEmpty())
  {
    newEdge->links.append(new Link(_label,_url));
  }

  return newEdge;
}

void DotGroupCollaboration::addCollaborationMember( 
    Definition* def, QCString& url, EdgeType eType )
{
  // Create group nodes
  if ( !def->partOfGroups() )
    return;
  GroupListIterator gli(*def->partOfGroups());
  GroupDef *d;
  QCString tmp_str;
  for (;(d=gli.current());++gli)
  {
    DotNode* nnode = m_usedNodes->find(d->name());
    if ( nnode != m_rootNode )
    {
      if ( nnode==0 )
      { // add node
        tmp_str = d->getReference()+"$"+d->getOutputFileBase();
4369 4370 4371
        QCString tooltip = d->briefDescriptionAsTooltip();
        nnode = new DotNode(m_curNodeId++, d->groupTitle(), tooltip, tmp_str );
        nnode->markAsVisible();
4372 4373 4374 4375 4376 4377 4378 4379 4380
        m_usedNodes->insert(d->name(), nnode );
      }
      tmp_str = def->qualifiedName();
      addEdge( m_rootNode, nnode, eType, tmp_str, url );
    }
  }
}


4381
QCString DotGroupCollaboration::writeGraph( FTextStream &t, GraphOutputFormat format,
4382
    const char *path, const char *fileName, const char *relPath,
4383
    bool writeImageMap,int graphId) const
4384 4385 4386
{
  QDir d(path);
  // store the original directory
4387 4388
  if (!d.exists())
  {
4389
    err("Output dir %s does not exist!\n",path); exit(1);
4390
  }
4391
  static bool usePDFLatex = Config_getBool("USE_PDFLATEX");
4392

4393 4394
  QGString theGraph;
  FTextStream md5stream(&theGraph);
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4395
  writeGraphHeader(md5stream,m_rootNode->label());
4396

4397 4398 4399 4400
  // clean write flags
  QDictIterator<DotNode> dni(*m_usedNodes);
  DotNode *pn;
  for (dni.toFirst();(pn=dni.current());++dni)
4401
  {
4402 4403
    pn->clearWriteFlag();
  }
4404

4405 4406 4407 4408
  // write other nodes.
  for (dni.toFirst();(pn=dni.current());++dni)
  {
    pn->write(md5stream,DotNode::Inheritance,format,TRUE,FALSE,FALSE,FALSE);
4409 4410
  }

4411 4412 4413 4414
  // write edges
  QListIterator<Edge> eli(m_edges);
  Edge* edge;
  for (eli.toFirst();(edge=eli.current());++eli)
4415
  {
4416 4417
    edge->write( md5stream );
  }
4418

4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443
  writeGraphFooter(md5stream);
  resetReNumbering();
  uchar md5_sig[16];
  QCString sigStr(33);
  MD5Buffer((const unsigned char *)theGraph.data(),theGraph.length(),md5_sig);
  MD5SigToString(md5_sig,sigStr.data(),33);
  QCString imgExt      = Config_getEnum("DOT_IMAGE_FORMAT");
  QCString baseName    = m_diskName;
  QCString imgName     = baseName+"."+imgExt;
  QCString mapName     = baseName+".map";
  QCString absPath     = d.absPath().data();
  QCString absBaseName = absPath+"/"+baseName;
  QCString absDotName  = absBaseName+".dot";
  QCString absImgName  = absBaseName+"."+imgExt;
  QCString absMapName  = absBaseName+".map";
  QCString absPdfName  = absBaseName+".pdf";
  QCString absEpsName  = absBaseName+".eps";
  bool regenerate=FALSE;
  if (checkAndUpdateMd5Signature(absBaseName,sigStr) ||
      !checkDeliverables(format==BITMAP ? absImgName :
                         usePDFLatex ? absPdfName : absEpsName,
                         format==BITMAP /*&& generateImageMap*/ ? absMapName : QCString())
     )
  {
    regenerate=TRUE;
4444

4445 4446
    QFile dotfile(absDotName);
    if (dotfile.open(IO_WriteOnly))
4447
    {
4448 4449 4450
      FTextStream tdot(&dotfile);
      tdot << theGraph;
      dotfile.close();
4451 4452
    }

4453
    if (format==BITMAP) // run dot to create a bitmap image
4454
    {
4455 4456 4457 4458 4459 4460 4461
      QCString dotArgs(maxCmdLine);

      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),FALSE);
      dotRun->addJob(imgExt,absImgName);
      if (writeImageMap) dotRun->addJob(MAP_CMD,absMapName);
      DotManager::instance()->addRun(dotRun);

4462
    }
4463
    else if (format==EPS)
4464
    {
4465 4466 4467 4468 4469 4470 4471 4472 4473 4474
      DotRunner *dotRun = new DotRunner(absDotName,d.absPath().data(),FALSE);
      if (usePDFLatex)
      {
        dotRun->addJob("pdf",absPdfName);
      }
      else
      {
        dotRun->addJob("ps",absEpsName);
      }
      DotManager::instance()->addRun(dotRun);
4475 4476
    }

4477 4478 4479 4480
  }
  if (format==BITMAP && writeImageMap)
  {
    QCString mapLabel = escapeCharsInString(baseName,FALSE);
4481 4482 4483 4484 4485 4486 4487 4488 4489
    t << "<center><table><tr><td>";

    if (imgExt=="svg")
    {
      t << "<div class=\"center\">";
      if (regenerate || !writeSVGFigureLink(t,relPath,baseName,absImgName)) // need to patch the links in the generated SVG file
      {
        if (regenerate)
        {
4490
          DotManager::instance()->addSVGConversion(absImgName,relPath,FALSE,QCString(),TRUE,graphId);
4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507
        }
        int mapId = DotManager::instance()->addSVGObject(fileName,baseName,absImgName,relPath);
        t << "<!-- SVG " << mapId << " -->" << endl;
      }
      t << "</div>" << endl;
    }
    else
    {
      t << "<img src=\"" << relPath << imgName
        << "\" border=\"0\" alt=\"\" usemap=\"#" 
        << mapLabel << "\"/>" << endl;
      if (regenerate || !insertMapFile(t,absMapName,relPath,mapLabel))
      {
        int mapId = DotManager::instance()->addMap(fileName,absMapName,relPath,
                                                   FALSE,QCString(),mapLabel);
        t << "<!-- MAP " << mapId << " -->" << endl;
      }
4508
    }
4509

4510
    t << "</td></tr></table></center>" << endl;
4511
  }
4512
  else if (format==EPS)
4513
  {
4514 4515 4516 4517 4518
    if (regenerate || !writeVecGfxFigure(t,baseName,absBaseName))
    {
      int figId = DotManager::instance()->addFigure(fileName,baseName,absBaseName,FALSE);
      t << endl << "% FIG " << figId << endl;
    }
4519
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4520
  if (!regenerate) removeDotGraph(absDotName);
4521 4522 4523 4524

  return baseName;
}

4525
void DotGroupCollaboration::Edge::write( FTextStream &t ) const
4526 4527
{
  const char* linkTypeColor[] = {
4528
       "darkorchid3"
4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563
      ,"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.count()>0) // 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\">";
    //QListIterator<Link> lli(links);
    //Link *link;
    //for( lli.toFirst(); (link=lli.current()); ++lli)
    //{
    //  t << "<TR><TD";
    //  if ( !link->url.isEmpty() )
    //    t << " HREF=\"" << link->url << "\"";
    //  t << ">" << link->label << "</TD></TR>";
    //}
    //t << "</TABLE>>";

    t << "label=\"";
    QListIterator<Link> lli(links);
    Link *link;
    bool first=TRUE;
4564 4565 4566
    int count=0;
    const int maxLabels = 10;
    for( lli.toFirst(); (link=lli.current()) && count<maxLabels; ++lli,++count)
4567 4568
    {
      if (first) first=FALSE; else t << "\\n"; 
4569
      t << convertLabel(link->label);
4570
    }
4571
    if (count==maxLabels) t << "\\n...";
4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591
    t << "\"";

  }
  switch( eType )
  {
    case thierarchy :
      arrowStyle = "dir=\"back\", style=\"solid\"";
    default :
      t << ", color=\"" << linkTypeColor[(int)eType] << "\"";
      break;
  }
  t << ", " << arrowStyle;
  t << "];" << endl;
}

bool DotGroupCollaboration::isTrivial() const
{
  return m_usedNodes->count() <= 1;
}

Dimitri van Heesch's avatar
Dimitri van Heesch committed
4592 4593
void DotGroupCollaboration::writeGraphHeader(FTextStream &t,
      const QCString &title) const
4594
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4595 4596 4597 4598 4599 4600 4601 4602 4603 4604
  t << "digraph ";
  if (title.isEmpty())
  {
    t << "\"Dot Graph\"";
  }
  else
  {
    t << "\"" << convertToXML(title) << "\"";
  }
  t << endl;
4605
  t << "{" << endl;
4606 4607 4608 4609
  if (Config_getBool("DOT_TRANSPARENT"))
  {
    t << "  bgcolor=\"transparent\";" << endl;
  }
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4610 4611 4612
  t << "  edge [fontname=\"" << FONTNAME << "\",fontsize=\"" << FONTSIZE << "\","
    "labelfontname=\"" << FONTNAME << "\",labelfontsize=\"" << FONTSIZE << "\"];\n";
  t << "  node [fontname=\"" << FONTNAME << "\",fontsize=\"" << FONTSIZE << "\",shape=record];\n";
4613
  t << "  rankdir=LR;\n";
4614
}
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4615

4616
void writeDotDirDepGraph(FTextStream &t,DirDef *dd)
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4617
{
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4618
    t << "digraph \"" << dd->displayName() << "\" {\n";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4619 4620 4621 4622 4623
    if (Config_getBool("DOT_TRANSPARENT"))
    {
      t << "  bgcolor=transparent;\n";
    }
    t << "  compound=true\n";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4624 4625
    t << "  node [ fontsize=\"" << FONTSIZE << "\", fontname=\"" << FONTNAME << "\"];\n";
    t << "  edge [ labelfontsize=\"" << FONTSIZE << "\", labelfontname=\"" << FONTNAME << "\"];\n";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4626 4627 4628 4629 4630 4631 4632 4633 4634

    QDict<DirDef> dirsInGraph(257);
    
    dirsInGraph.insert(dd->getOutputFileBase(),dd);
    if (dd->parent())
    {
      t << "  subgraph cluster" << dd->parent()->getOutputFileBase() << " {\n";
      t << "    graph [ bgcolor=\"#ddddee\", pencolor=\"black\", label=\"" 
        << dd->parent()->shortName() 
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4635
        << "\" fontname=\"" << FONTNAME << "\", fontsize=\"" << FONTSIZE << "\", URL=\"";
Dimitri van Heesch's avatar
Dimitri van Heesch committed
4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758
      t << dd->parent()->getOutputFileBase() << Doxygen::htmlFileExtension;
      t << "\"]\n";
    }
    if (dd->isCluster())
    {
      t << "  subgraph cluster" << dd->getOutputFileBase() << " {\n";
      t << "    graph [ bgcolor=\"#eeeeff\", pencolor=\"black\", label=\"\""
        << " URL=\"" << dd->getOutputFileBase() << Doxygen::htmlFileExtension 
        << "\"];\n";
      t << "    " << dd->getOutputFileBase() << " [shape=plaintext label=\"" 
        << dd->shortName() << "\"];\n";

      // add nodes for sub directories
      QListIterator<DirDef> sdi(dd->subDirs());
      DirDef *sdir;
      for (sdi.toFirst();(sdir=sdi.current());++sdi)
      {
        t << "    " << sdir->getOutputFileBase() << " [shape=box label=\"" 
          << sdir->shortName() << "\"";
        if (sdir->isCluster())
        {
          t << " color=\"red\"";
        }
        else
        {
          t << " color=\"black\"";
        }
        t << " fillcolor=\"white\" style=\"filled\"";
        t << " URL=\"" << sdir->getOutputFileBase() 
          << Doxygen::htmlFileExtension << "\"";
        t << "];\n";
        dirsInGraph.insert(sdir->getOutputFileBase(),sdir);
      }
      t << "  }\n";
    }
    else
    {
      t << "  " << dd->getOutputFileBase() << " [shape=box, label=\"" 
        << dd->shortName() << "\", style=\"filled\", fillcolor=\"#eeeeff\","
        << " pencolor=\"black\", URL=\"" << dd->getOutputFileBase() 
        << Doxygen::htmlFileExtension << "\"];\n";
    }
    if (dd->parent())
    {
      t << "  }\n";
    }

    // add nodes for other used directories
    QDictIterator<UsedDir> udi(*dd->usedDirs());
    UsedDir *udir;
    //printf("*** For dir %s\n",shortName().data());
    for (udi.toFirst();(udir=udi.current());++udi) 
      // for each used dir (=directly used or a parent of a directly used dir)
    {
      const DirDef *usedDir=udir->dir();
      DirDef *dir=dd;
      while (dir)
      {
        //printf("*** check relation %s->%s same_parent=%d !%s->isParentOf(%s)=%d\n",
        //    dir->shortName().data(),usedDir->shortName().data(),
        //    dir->parent()==usedDir->parent(),
        //    usedDir->shortName().data(),
        //    shortName().data(),
        //    !usedDir->isParentOf(this)
        //    );
        if (dir!=usedDir && dir->parent()==usedDir->parent() && 
            !usedDir->isParentOf(dd))
          // include if both have the same parent (or no parent)
        {
          t << "  " << usedDir->getOutputFileBase() << " [shape=box label=\"" 
            << usedDir->shortName() << "\"";
          if (usedDir->isCluster())
          {
            if (!Config_getBool("DOT_TRANSPARENT"))
            {
              t << " fillcolor=\"white\" style=\"filled\"";
            }
            t << " color=\"red\"";
          }
          t << " URL=\"" << usedDir->getOutputFileBase() 
            << Doxygen::htmlFileExtension << "\"];\n";
          dirsInGraph.insert(usedDir->getOutputFileBase(),usedDir);
          break;
        }
        dir=dir->parent();
      }
    }

    // add relations between all selected directories
    DirDef *dir;
    QDictIterator<DirDef> di(dirsInGraph);
    for (di.toFirst();(dir=di.current());++di) // foreach dir in the graph
    {
      QDictIterator<UsedDir> udi(*dir->usedDirs());
      UsedDir *udir;
      for (udi.toFirst();(udir=udi.current());++udi) // foreach used dir
      {
        const DirDef *usedDir=udir->dir();
        if ((dir!=dd || !udir->inherited()) &&     // only show direct dependendies for this dir
            (usedDir!=dd || !udir->inherited()) && // only show direct dependendies for this dir
            !usedDir->isParentOf(dir) &&             // don't point to own parent
            dirsInGraph.find(usedDir->getOutputFileBase())) // only point to nodes that are in the graph
        {
          QCString relationName;
          relationName.sprintf("dir_%06d_%06d",dir->dirCount(),usedDir->dirCount());
          if (Doxygen::dirRelations.find(relationName)==0)
          {
            // new relation
            Doxygen::dirRelations.append(relationName,
                new DirRelation(relationName,dir,udir));
          }
          int nrefs = udir->filePairs().count();
          t << "  " << dir->getOutputFileBase() << "->" 
                    << usedDir->getOutputFileBase();
          t << " [headlabel=\"" << nrefs << "\", labeldistance=1.5";
          t << " headhref=\"" << relationName << Doxygen::htmlFileExtension 
            << "\"];\n";
        }
      }
    }

    t << "}\n";
}