Doxygen
Loading...
Searching...
No Matches
dotrunner.cpp
Go to the documentation of this file.
1/******************************************************************************
2*
3* Copyright (C) 1997-2019 by Dimitri van Heesch.
4*
5* Permission to use, copy, modify, and distribute this software and its
6* documentation under the terms of the GNU General Public License is hereby
7* granted. No representations are made about the suitability of this software
8* for any purpose. It is provided "as is" without express or implied warranty.
9* See the GNU General Public License for more details.
10*
11* Documents produced by Doxygen are derivative works derived from the
12* input used in their production; they are not affected by this license.
13*
14*/
15
16#include "dotrunner.h"
17
18#include <cassert>
19#include <cmath>
20#include <map>
21#include <set>
22#include <string>
23#include <algorithm>
24#include <numeric>
25#include <random>
26#include <sstream>
27
28#ifdef _MSC_VER
29#pragma warning( push )
30#pragma warning( disable : 4242 )
31#pragma warning( disable : 4244 )
32#pragma warning( disable : 4996 )
33#pragma warning( disable : 4456 )
34#pragma warning( disable : 4805 )
35#endif
36#if defined(__clang__)
37#pragma clang diagnostic push
38#pragma clang diagnostic ignored "-Wdeprecated-declarations"
39#pragma clang diagnostic ignored "-Wshadow"
40#endif
41#if defined(__GNUC__)
42#pragma GCC diagnostic push
43#pragma GCC diagnostic ignored "-Wshadow"
44#endif
45#include <gunzip.hh>
46#if defined(__GNUC__)
47#pragma GCC diagnostic pop
48#endif
49#if defined(__clang__)
50#pragma clang diagnostic pop
51#endif
52#ifdef _MSC_VER
53#pragma warning( pop )
54#endif
55
56#include "config.h"
57#include "dir.h"
58#include "dot.h"
59#include "doxygen.h"
60#include "message.h"
61#include "portable.h"
62#include "threadpool.h"
63#include "util.h"
64
65// the graphicx LaTeX has a limitation of maximum size of 16384
66// To be on the save side we take it a little bit smaller i.e. 150 inch * 72 dpi
67// It is anyway hard to view these size of images
68#define MAX_LATEX_GRAPH_INCH 150
69#define MAX_LATEX_GRAPH_SIZE (MAX_LATEX_GRAPH_INCH * 72)
70
71//#define DBG(x) printf x
72#define DBG(x) do {} while(0)
73
74//-----------------------------------------------------------------------------------------
75
76// since dot silently reproduces the input file when it does not
77// support the PNG format, we need to check the result.
78static void checkPngResult(const DString &imgName)
79{
80 FILE *f = Portable::fopen(imgName,"rb");
81 if (!f)
82 {
83 err("Could not read image '{}' generated by dot!\n",imgName);
84 return;
85 }
86
87 char data[4];
88 if (fread(data, 1, 4, f) != 4)
89 {
90 err("Could not read image '{}' generated by dot!\n",imgName);
91 fclose(f);
92 return;
93 }
94
95 if (!(data[1] == 'P' && data[2] == 'N' && data[3] == 'G'))
96 {
97 err("Image '{}' produced by dot is not a valid PNG!\n"
98 "You should either select a different format "
99 "(DOT_IMAGE_FORMAT in the config file) or install a more "
100 "recent version of graphviz (1.7+)\n", imgName);
101 }
102
103 fclose(f);
104}
105
106static bool resetPDFSize(const int width,const int height, const DString &base)
107{
108 DString tmpName = base+".tmp";
109 DString patchFile = base+".dot";
110 Dir thisDir;
111 if (!thisDir.rename(patchFile.str(),tmpName.str()))
112 {
113 err("Failed to rename file {} to {}!\n",patchFile,tmpName);
114 return false;
115 }
116 std::ifstream fi = Portable::openInputStream(tmpName);
117 std::ofstream t = Portable::openOutputStream(patchFile);
118 if (!fi.is_open())
119 {
120 err("problem opening file {} for patching!\n",tmpName);
121 thisDir.rename(tmpName.str(),patchFile.str());
122 return false;
123 }
124 if (!t.is_open())
125 {
126 err("problem opening file {} for patching!\n",patchFile);
127 thisDir.rename(tmpName.str(),patchFile.str());
128 return false;
129 }
130 std::string line;
131 while (getline(fi,line)) // foreach line
132 {
133 if (line.find("LATEX_PDF_SIZE") != std::string::npos)
134 {
135 double scale = (width > height ? width : height)/double(MAX_LATEX_GRAPH_INCH);
136 t << " size=\""<<width/scale << "," <<height/scale << "\";\n";
137 }
138 else
139 t << line << "\n";
140 }
141 fi.close();
142 t.close();
143 // remove temporary file
144 thisDir.remove(tmpName.str());
145 return true;
146}
147
148bool DotRunner::readBoundingBox(const DString &fileName,int *width,int *height,bool isEps)
149{
150 std::ifstream f = Portable::openInputStream(fileName);
151 if (!f.is_open())
152 {
153 err("Failed to open file {} for extracting bounding box\n",fileName);
154 return false;
155 }
156
157 // read file contents into string 'contents'
158 std::stringstream buffer;
159 buffer << f.rdbuf();
160 std::string contents = buffer.str();
161
162 // start of bounding box marker we are looking for
163 const std::string boundingBox = isEps ? "%%PageBoundingBox:" : "/MediaBox [";
164
165 // helper routine to extract the bounding boxes width and height
166 auto extractBoundingBox = [&fileName,&boundingBox,&width,&height](const char *s) -> bool
167 {
168 int x=0, y=0;
169 double w=0, h=0;
170 if (sscanf(s+boundingBox.length(),"%d %d %lf %lf",&x,&y,&w,&h)==4)
171 {
172 *width = static_cast<int>(std::ceil(w));
173 *height = static_cast<int>(std::ceil(h));
174 return true;
175 }
176 err("Failed to extract bounding box from generated diagram file {}\n",fileName);
177 return false;
178 };
179
180 // compressed segment start and end markers
181 const std::string streamStart = "stream\n";
182 const std::string streamEnd = "\nendstream";
183
184 auto detectDeflateStreamStart = [&streamStart](const char *s)
185 {
186 size_t len = streamStart.length();
187 bool streamOK = strncmp(s,streamStart.c_str(),len)==0;
188 if (streamOK) // ASCII marker matches, check stream header bytes as well
189 {
190 unsigned short header1 = static_cast<unsigned char>(s[len])<<8; // CMF byte
191 if (header1) // not end of string
192 {
193 unsigned short header = (static_cast<unsigned char>(s[len+1])) | header1; // FLG byte
194 // check for correct header (see https://www.rfc-editor.org/rfc/rfc1950)
195 return ((header&0x8F20)==0x0800) && (header%31)==0;
196 }
197 }
198 return false;
199 };
200
201 const size_t l = contents.length();
202 size_t i=0;
203 while (i<l)
204 {
205 if (!isEps && contents[i]=='s' && detectDeflateStreamStart(&contents[i]))
206 { // compressed stream start
207 int col=17;
208 i+=streamStart.length();
209 const size_t start=i;
210 DBG(("---- start stream at offset %08x\n",(int)i));
211 while (i<l)
212 {
213 if (contents[i]=='\n' && strncmp(&contents[i],streamEnd.c_str(),streamEnd.length())==0)
214 { // compressed block found in range [start..i]
215 DBG(("\n---- end stream at offset %08x\n",(int)i));
216 // decompress it into decompressBuf
217 std::vector<char> decompressBuf;
218 const char *source = &contents[start];
219 const size_t sourceLen = i-start;
220 size_t sourcePos = 0;
221 decompressBuf.reserve(sourceLen*2);
222 auto getter = [source,&sourcePos,sourceLen]() -> int {
223 return sourcePos<sourceLen ? static_cast<unsigned char>(source[sourcePos++]) : EOF;
224 };
225 auto putter = [&decompressBuf](const char c) -> int {
226 decompressBuf.push_back(c); return c;
227 };
228 Deflate(getter,putter);
229 // convert decompression buffer to string
230 std::string s(decompressBuf.begin(), decompressBuf.end());
231 DBG(("decompressed_data=[[[\n%s\n]]]\n",s.c_str()));
232 // search for bounding box marker
233 const size_t idx = s.find(boundingBox);
234 if (idx!=std::string::npos) // found bounding box in uncompressed data
235 {
236 return extractBoundingBox(s.c_str()+idx);
237 }
238 // continue searching after end stream marker
239 i+=streamEnd.length();
240 break;
241 }
242 else // compressed stream character
243 {
244 if (col>16) { col=0; DBG(("\n%08x: ",static_cast<int>(i))); }
245 DBG(("%02x ",static_cast<unsigned char>(contents[i])));
246 col++;
247 i++;
248 }
249 }
250 }
251 else if (((isEps && contents[i]=='%') || (!isEps && contents[i]=='/')) &&
252 strncmp(&contents[i],boundingBox.c_str(),boundingBox.length())==0)
253 { // uncompressed bounding box
254 return extractBoundingBox(&contents[i]);
255 }
256 else // uncompressed stream character
257 {
258 i++;
259 }
260 }
261 err("Failed to find bounding box in generated diagram file {}\n",fileName);
262 // nothing found
263 return false;
264}
265
266//---------------------------------------------------------------------------------
267
269{
270 size_t index = output.rfind('.');
271 if (index==DString::npos) return output;
272 return output.left(index);
273}
274
276 : m_dotExe(Doxygen::verifiedDotPath)
277{
278}
279
280bool DotRunner::run(const DotJobs &dotJobs)
281{
282 if (dotJobs.empty()) return true;
283
284 // Group jobs by format, then by directory so we can cd once per group
285 std::map<std::string, std::map<std::string, std::vector<const DotJob*>>> byFormatAndDir;
286 for (const auto &job : dotJobs)
287 {
288 byFormatAndDir[job.format.str()][job.absPath.str()].push_back(&job);
289 }
290
291 std::mt19937 rng(std::random_device{}());
292 bool ok = true;
293 size_t prev=0;
294 for (const auto &[fmtStr, byDir] : byFormatAndDir)
295 {
296 DString format = DString(fmtStr);
297
298 for (const auto &[dirStr, jobs] : byDir)
299 {
300 std::string oldDir = Dir::currentDirPath();
301 Dir::setCurrent(dirStr);
302
303 // settings controlling how to distribute the graphs over threads and batches
304 const size_t numThreads = static_cast<size_t>(Config_getInt(DOT_NUM_THREADS));
305 const size_t batchSize = static_cast<size_t>(Config_getInt(DOT_BATCH_SIZE));
306 const size_t exeLen = m_dotExe.length() + 1; // "exe " prefix
307 const size_t maxArgLen = 32000-exeLen; // Windows CreateProcess limit is 32767; keep safe margin
308
309 // create a pseudo random ordering in which to process the dot files
310 std::vector<size_t> indices(jobs.size());
311 std::iota(indices.begin(), indices.end(), 0);
312 std::shuffle(indices.begin(), indices.end(), rng);
313
314 // helper to keep track of dot command to run later
315 struct CommandArgument
316 {
317 CommandArgument(const DString &args) : arguments(args) {}
318 DString arguments;
319 size_t numDotFiles = 0;
320 const DotJob *firstJob = nullptr;
321 };
322
323 std::vector<CommandArgument> partialCommands;
324 std::vector<CommandArgument> finalCommands;
325
326 bool hasImageMap = std::any_of(jobs.begin(),jobs.end(),[](const auto &j) { return j->generateImageMap; });
327
328 // each dot command has a command arguments of the form: -Tformat -O basename1.dot basename2.dot ...
329 DString baseArgs = DString("-T") + format;
330 if (hasImageMap) // if any image needs a map we generate one for all images
331 {
332 baseArgs += " -Tcmapx";
333 }
334 baseArgs += " -O";
335
336 // prepare partial commands for each thread (command is later skipped if numDotFiles==0).
337 for (size_t i=0; i<numThreads; i++)
338 {
339 partialCommands.emplace_back(baseArgs);
340 }
341
342 // split the jobs into batches per thread iterating in pseudo random order to fill each batch with a random selection of graphs
343 size_t index=0;
344 for (size_t i : indices)
345 {
346 const auto &job = jobs[i];
347 DString fileArg = DString(" ") + job->relDotName;
348 auto &cmd = partialCommands[index];
349 if (cmd.numDotFiles<batchSize && cmd.arguments.length()+fileArg.length()<maxArgLen) // still room in this batch
350 {
351 cmd.arguments+=fileArg;
352 cmd.numDotFiles++;
353 }
354 else // this batch is full, move to finished commands and start a new one
355 {
356 finalCommands.push_back(cmd);
357 cmd.arguments=baseArgs+fileArg;
358 cmd.numDotFiles=1;
359 }
360 if (cmd.firstJob==nullptr) cmd.firstJob=job;
361 index = (index+1)%numThreads;
362 }
363
364 // append partial commands to the final commands
365 finalCommands.insert(finalCommands.end(),partialCommands.begin(),partialCommands.end());
366
367 // now run the finalCommands.
368 if (Config_getInt(DOT_NUM_THREADS)<=1) // no threads to work with
369 {
370 for (const auto &cmd : finalCommands)
371 {
372 if (cmd.numDotFiles>0) // check if there are graphs to generate first
373 {
374 if (cmd.numDotFiles>1) // batch mode
375 {
376 msg("Running dot for graphs {}-{}/{}\n",prev+1,prev+cmd.numDotFiles,dotJobs.size());
377 }
378 else // single graph mode
379 {
380 msg("Running dot for graph {}/{}\n",prev+1,dotJobs.size());
381 }
382 prev+=cmd.numDotFiles;
383 int exitCode;
384 if ((exitCode = Portable::system(m_dotExe, cmd.arguments, false)) != 0)
385 {
386 err_full(cmd.firstJob->srcFile, 1,
387 "Problems running dot: exit code={}, command='{}', dir='{}', arguments='{}'",
388 exitCode, m_dotExe, dirStr, cmd.arguments);
389 ok = false;
390 }
391 }
392 }
393 }
394 else // use multiple threads to run instances of dot in parallel
395 {
396 ThreadPool workers(numThreads);
397 std::vector< std::future<size_t> > results;
398 for (auto & cmd: finalCommands)
399 {
400 if (cmd.numDotFiles>0)
401 {
402 auto locDirStr = dirStr;
403 auto process = [this,cmd,locDirStr]() -> size_t
404 {
405 int exitCode;
406 if ((exitCode = Portable::system(m_dotExe, cmd.arguments, false)) != 0)
407 {
408 err_full(cmd.firstJob->srcFile, 1,
409 "Problems running dot: exit code={}, command='{}', dir='{}', arguments='{}'",
410 exitCode, m_dotExe, locDirStr, cmd.arguments);
411 }
412 return cmd.numDotFiles;
413 };
414 results.emplace_back(workers.queue(process));
415 }
416 }
417 for (auto &f : results)
418 {
419 size_t numDotFiles = f.get();
420 if (numDotFiles>1) // batch mode
421 {
422 msg("Finished running dot for graphs {}-{}/{}\n",prev+1,prev+numDotFiles,dotJobs.size());
423 }
424 else // single graph mode
425 {
426 msg("Finished running dot for graph {}/{}\n",prev+1,dotJobs.size());
427 }
428 prev+=numDotFiles;
429 }
430 }
431
432 // Post-process each output file. dot -O appends the format suffix to the
433 // full input filename, so the output is absPath + relDotName + "." + format.
434 // Rename to remove the .dot infix, producing absPath + baseName + "." + format.
435 for (const auto *job : jobs)
436 {
437 DString base = job->absPath + getBaseNameOfOutput(job->relDotName);
438 DString dotOutput = job->absPath + job->relDotName + "." + format;
439 DString output = base + "." + format;
440 Dir d;
441 if (!d.rename(dotOutput.str(), output.str()))
442 {
443 err("Failed to rename {} to {}!\n", dotOutput, output);
444 ok = false;
445 continue;
446 }
447 if (job->generateImageMap)
448 {
449 DString dotMapOutput = job->absPath + job->relDotName + ".cmapx";
450 DString mapOutput = base + ".map";
451 if (!d.rename(dotMapOutput.str(), mapOutput.str()))
452 {
453 err("Failed to rename {} to {}!\n", dotMapOutput, mapOutput);
454 ok = false;
455 continue;
456 }
457 }
458
459 if (format.startsWith("pdf"))
460 {
461 int width=0, height=0;
462 if (!readBoundingBox(output, &width, &height, false))
463 {
464 ok = false;
465 continue;
466 }
467 if ((width > MAX_LATEX_GRAPH_SIZE) || (height > MAX_LATEX_GRAPH_SIZE))
468 {
469 if (!resetPDFSize(width, height, base))
470 {
471 ok = false;
472 continue;
473 }
474 // Re-run dot for just this one file
475 DString rerunArgs = DString("-T") + format + " -O \"" + job->relDotName + "\"";
476 int exitCode;
477 if ((exitCode = Portable::system(m_dotExe, rerunArgs, false)) != 0)
478 {
479 err_full(job->srcFile, 1,
480 "Problems running dot: exit code={}, command='{}', dir='{}', arguments='{}'",
481 exitCode, m_dotExe, dirStr, rerunArgs);
482 ok = false;
483 }
484 else
485 {
486 Dir d2;
487 if (!d2.rename(dotOutput.str(), output.str()))
488 {
489 err("Failed to rename {} to {}!\n", dotOutput, output);
490 ok = false;
491 }
492 }
493 }
494 }
495 else if (format.startsWith("png"))
496 {
497 checkPngResult(output);
498 }
499 }
500 Dir::setCurrent(oldDir);
501 }
502 }
503
504 // Write .md5 files and clean up .dot files (once per unique dotFile)
505 std::set<std::string> processed;
506 for (const auto &job : dotJobs)
507 {
508 if (!processed.insert((job.absPath + job.relDotName).str()).second) continue;
509
510 if (!job.md5Hash.empty())
511 {
512 DString md5Name = job.absPath + getBaseNameOfOutput(job.relDotName) + ".md5";
513 FILE *f = Portable::fopen(md5Name, "w");
514 if (f)
515 {
516 fwrite(job.md5Hash.data(), 1, 32, f);
517 fclose(f);
518 }
519 }
520
521 if (Config_getBool(DOT_CLEANUP))
522 {
523 Portable::unlink(job.absPath + job.relDotName);
524 }
525 }
526
527 return ok;
528}
A String class for use with Doxygen wrapping std::string and adding some additional functionality off...
Definition dstring.h:88
DString()=default
size_t rfind(char c, size_t pos=npos) const
Definition dstring.h:248
static constexpr size_t npos
value used to indicate 'not found' or 'to the end of the string', matching std::string::npos
Definition dstring.h:182
DString left(size_t len) const
Definition dstring.h:310
const std::string & str() const
Definition dstring.h:649
size_t length() const
Returns the length of the string, not counting the 0-terminator.
Definition dstring.h:155
Class representing a directory in the file system.
Definition dir.h:73
static std::string currentDirPath()
Definition dir.cpp:343
bool remove(const std::string &path, bool acceptsAbsPath=true) const
Definition dir.cpp:315
bool rename(const std::string &orgName, const std::string &newName, bool acceptsAbsPath=true) const
Definition dir.cpp:322
static bool setCurrent(const std::string &path)
Definition dir.cpp:351
static bool readBoundingBox(const DString &fileName, int *width, int *height, bool isEps)
DString m_dotExe
Definition dotrunner.h:42
bool run(const DotJobs &jobs)
Runs dot for all given jobs.
This class serves as a namespace for global variables used by doxygen.
Definition doxygen.h:86
Class managing a pool of worker threads.
Definition threadpool.h:48
auto queue(F &&f, Args &&... args) -> std::future< decltype(f(args...))>
Queue the callable function f for the threads to execute.
Definition threadpool.h:77
#define Config_getInt(name)
Definition config.h:34
#define Config_getBool(name)
Definition config.h:33
std::vector< DotJob > DotJobs
Definition dotjob.h:37
#define MAX_LATEX_GRAPH_INCH
Definition dotrunner.cpp:68
#define DBG(x)
Definition dotrunner.cpp:72
static void checkPngResult(const DString &imgName)
Definition dotrunner.cpp:78
#define MAX_LATEX_GRAPH_SIZE
Definition dotrunner.cpp:69
static DString getBaseNameOfOutput(const DString &output)
static bool resetPDFSize(const int width, const int height, const DString &base)
#define msg(fmt,...)
Definition message.h:94
#define err(fmt,...)
Definition message.h:127
#define err_full(file, line, fmt,...)
Definition message.h:132
std::ifstream openInputStream(const DString &name, bool binary=false, bool openAtEnd=false)
Definition portable.cpp:676
int system(const DString &command, const DString &args, bool commandHasConsole=true)
Definition portable.cpp:105
void unlink(const DString &fileName)
Definition portable.cpp:544
std::ofstream openOutputStream(const DString &name, bool append=false)
Definition portable.cpp:665
FILE * fopen(const DString &fileName, const DString &mode)
Definition portable.cpp:349
Portable versions of functions that are platform dependent.
A bunch of utility functions.