Doxygen
Loading...
Searching...
No Matches
DotRunner Class Reference

Helper class to run dot from doxygen. More...

#include <src/dotrunner.h>

Collaboration diagram for DotRunner:

Public Member Functions

 DotRunner ()
bool run (const DotJobs &jobs)
 Runs dot for all given jobs.

Static Public Member Functions

static bool readBoundingBox (const DString &fileName, int *width, int *height, bool isEps)

Private Attributes

DString m_dotExe

Detailed Description

Helper class to run dot from doxygen.

Holds a queue of jobs, each specifying an input .dot file and output format. Call run() to execute all queued jobs, batched as a single dot invocation per output format using the -O flag for automatic output file naming.

Definition at line 29 of file dotrunner.h.

Constructor & Destructor Documentation

◆ DotRunner()

DotRunner::DotRunner ( )

Definition at line 275 of file dotrunner.cpp.

277{
278}
DString m_dotExe
Definition dotrunner.h:42
static DString verifiedDotPath
Definition doxygen.h:130

References m_dotExe.

Member Function Documentation

◆ readBoundingBox()

bool DotRunner::readBoundingBox ( const DString & fileName,
int * width,
int * height,
bool isEps )
static

Definition at line 148 of file dotrunner.cpp.

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}
#define DBG(x)
Definition dotrunner.cpp:72
#define err(fmt,...)
Definition message.h:127
std::ifstream openInputStream(const DString &name, bool binary=false, bool openAtEnd=false)
Definition portable.cpp:676

References DBG, err, and Portable::openInputStream().

Referenced by run(), and DotFilePatcher::writeVecGfxFigure().

◆ run()

bool DotRunner::run ( const DotJobs & jobs)

Runs dot for all given jobs.

For each unique format, a single dot invocation is made with -O and all input files for that format.

Definition at line 280 of file dotrunner.cpp.

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}
DString()=default
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
static std::string currentDirPath()
Definition dir.cpp:343
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)
#define Config_getInt(name)
Definition config.h:34
#define Config_getBool(name)
Definition config.h:33
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_full(file, line, fmt,...)
Definition message.h:132
int system(const DString &command, const DString &args, bool commandHasConsole=true)
Definition portable.cpp:105
void unlink(const DString &fileName)
Definition portable.cpp:544
FILE * fopen(const DString &fileName, const DString &mode)
Definition portable.cpp:349
int fclose(FILE *f)
Definition portable.cpp:369

References checkPngResult(), Config_getBool, Config_getInt, Dir::currentDirPath(), DString::DString(), err, err_full, Portable::fopen(), getBaseNameOfOutput(), DString::length(), m_dotExe, MAX_LATEX_GRAPH_SIZE, msg, ThreadPool::queue(), readBoundingBox(), Dir::rename(), resetPDFSize(), Dir::setCurrent(), DString::str(), Portable::system(), and Portable::unlink().

Referenced by DotManager::run().

Member Data Documentation

◆ m_dotExe

DString DotRunner::m_dotExe
private

Definition at line 42 of file dotrunner.h.

Referenced by DotRunner(), and run().


The documentation for this class was generated from the following files: