Doxygen
Loading...
Searching...
No Matches
formula.cpp
Go to the documentation of this file.
1/******************************************************************************
2 *
3 * Copyright (C) 1997-2022 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// own header
17#include "formula.h"
18
19// standard includes
20#include <map>
21#include <string>
22#include <utility>
23#include <vector>
24
25// other includes
26#include "config.h"
27#include "debug.h"
28#include "dir.h"
29#include "doxygen.h"
30#include "fileinfo.h"
31#include "indexlist.h"
32#include "latexgen.h"
33#include "linkedmap.h"
34#include "message.h"
35#include "portable.h"
36#include "regex.h"
37#include "threadpool.h"
38#include "util.h"
39
40static int determineInkscapeVersion(const Dir &thisDir);
41
49
51{
52}
53
55{
56 static FormulaManager fm;
57 return fm;
58}
59
61{
62 std::ifstream f = Portable::openInputStream(dir+"/formula.repository");
63 if (f.is_open())
64 {
65 uint32_t formulaCount=0;
66 msg("Reading formula repository...\n");
67 std::string readLine;
68 std::string line;
69 std::string prefix("\\_form#");
70 int nextLineNr=1;
71 bool hasNextLine = !getline(f,readLine).fail();
72 while (hasNextLine)
73 {
74 line = readLine;
75 int lineNr = nextLineNr;
76
77 // look ahead a bit because a formula can be spread over several lines
78 while ((hasNextLine = !getline(f,readLine).fail()))
79 {
80 nextLineNr+=1;
81 if (!readLine.compare(0, prefix.size(), prefix)) break;
82 line += "\n" + readLine;
83 }
84
85 // new format: \_form#<digits>=<digits>x<digits>:formula
86 static const reg::Ex re_new(R"(\\_form#(\d+)=(\d+)x(\d+):)");
87 // old format: \_form#<digits>:formula
88 static const reg::Ex re_old(R"(\\_form#(\d+):)");
89
90 reg::Match match;
91 int id = -1;
92 int width = -1;
93 int height = -1;
94 std::string text;
95 if (reg::search(line,match,re_new)) // try new format first
96 {
97 id = std::stoi(match[1].str());
98 width = std::stoi(match[2].str());
99 height = std::stoi(match[3].str());
100 text = line.substr(match.position()+match.length());
101 //printf("new format found id=%d width=%d height=%d text=%s\n",id,width,height,qPrinf(text));
102 }
103 else if (reg::search(line,match,re_old)) // check for old format
104 {
105 //id = std::stoi(match[1].str());
106 //text = line.substr(match.position()+match.length());
107 //printf("old format found id=%d text=%s\n",id,qPrint(text));
108 msg("old formula.repository format detected; forcing upgrade.\n");
109 p->repositoriesValid = false;
110 break;
111 }
112 else // unexpected content
113 {
114 warn_uncond("{}/formula.repository contains invalid content at line {}: found: '{}'\n",dir,lineNr,line);
115 p->repositoriesValid = false;
116 break;
117 }
118
119 auto it = p->formulaIdMap.find(id);
120 Formula *formula=nullptr;
121 if (it!=p->formulaIdMap.end()) // formula already found in a repository for another output format
122 {
123 formula = it->second;
124 if (formula->text().str()!=text) // inconsistency between repositories detected
125 {
126 msg("differences detected between formula.repository files; forcing upgrade.\n");
127 p->repositoriesValid = false;
128 break;
129 }
130 formulaCount++;
131 }
132 else // create new formula from cache
133 {
134 //printf("formula not found adding it under id=%d\n",id);
135 formula = p->formulas.add(text,id,width,height);
136 p->formulaIdMap.emplace(id,formula);
137 }
138
139 if (formula) // if an entry in the repository exists also check if there is a generated image
140 {
141 DString formImgName;
142 formImgName.sprintf("form_%d",formula->id());
143 FileInfo fiPng((dir+"/"+formImgName+".png").str());
144 FileInfo fiSvg((dir+"/"+formImgName+".svg").str());
145 // mark formula as cached, so we do not need to regenerate the images
146 bool isCached = fiPng.exists() || fiSvg.exists();
147 formula->setCached(isCached);
148 //printf("formula %d: cached=%d\n",formula->id(),isCached);
149
150 FileInfo fiPngDark((dir+"/"+formImgName+"_dark.png").str());
151 FileInfo fiSvgDark((dir+"/"+formImgName+"_dark.svg").str());
152 bool isCachedDark = fiPngDark.exists() || fiSvgDark.exists();
153 formula->setCachedDark(isCachedDark);
154 //printf("formula %d: cachedDark=%d\n",formula->id(),isCachedDark);
155 }
156 }
157
158 // For the first repository all formulas should be new (e.g. formulaCount==0).
159 // For the other repositories the same number of formulas should be found
160 // (and number of formulas should be the same for all repositories, content is already check above)
161 if (formulaCount>0 && formulaCount!=p->formulas.size()) // inconsistency between repositories
162 {
163 msg("differences detected between formula.repository files; forcing upgrade.\n");
164 p->repositoriesValid = false;
165 }
166 }
167 else // no repository found for an output format
168 {
169 p->repositoriesValid = false;
170 }
171}
172
174{
175 //printf("checkRepositories valid=%d\n",p->repositoriesValid);
176 if (!p->repositoriesValid)
177 {
178 clear(); // clear cached formulas, so the corresponding images and repository files
179 // are regenerated
180 p->repositoriesValid = true;
181 }
182}
183
184void FormulaManager::createLatexFile(const DString &fileName,Format format,Mode mode,IntVector &formulasToGenerate,bool toIndex)
185{
186 // generate a latex file containing one formula per page.
187 DString texName=fileName+".tex";
188 std::ofstream f = Portable::openOutputStream(texName);
189 if (f.is_open())
190 {
191 TextStream t(&f);
192 t << "\\documentclass{article}\n";
193 t << "\\usepackage{iftex}\n";
194 t << "\\usepackage{ifthen}\n";
195 t << "\\usepackage{epsfig}\n"; // for those who want to include images
196 t << "\\usepackage[utf8]{inputenc}\n"; // looks like some older distributions with newunicode package 1.1 need this option.
197 t << "\\usepackage{xcolor}\n";
198
199 if (mode==Mode::Dark) // invert page and text colors
200 {
201 t << "\\color{white}\n";
202 t << "\\pagecolor{black}\n";
203 }
204
207
208 DString macroFile = Config_getString(FORMULA_MACROFILE);
209 if (!macroFile.empty())
210 {
211 FileInfo fi(macroFile.str());
212 DString stripMacroFile = fi.fileName();
213 t << "\\input{" << stripMacroFile << "}\n";
214 }
215
216 t << "\\pagestyle{empty}\n";
217 t << "\\begin{document}\n";
218 for (const auto &formula : p->formulas)
219 {
220 int id = formula->id();
221 // only formulas for which no image is cached are generated
222 //printf("check formula %d: cached=%d cachedDark=%d\n",formula->id(),formula->isCached(),formula->isCachedDark());
223 if ((mode==Mode::Light && !formula->isCached()) ||
224 (mode==Mode::Dark && !formula->isCachedDark())
225 )
226 {
227 // we force a pagebreak after each formula
228 t << formula->text() << "\n\\pagebreak\n\n";
229 formulasToGenerate.push_back(id);
230 }
231 DString resultName;
232 resultName.sprintf("form_%d%s.%s",id, mode==Mode::Light?"":"_dark", format==Format::Vector?"svg":"png");
233 if (toIndex) Doxygen::indexList->addImageFile(resultName);
234 }
235 t << "\\end{document}\n";
236 t.flush();
237 f.close();
238 }
239}
240
241static bool createDVIFile(const DString &fileName)
242{
243 DString latexCmd = "latex";
244 const size_t argsLen = 4096;
245 char args[argsLen];
246 int rerunCount=1;
247 while (rerunCount<8)
248 {
249 //printf("Running latex...\n");
250 snprintf(args,argsLen,"-interaction=batchmode %s >%s",qPrint(fileName),Portable::devNull());
251 if ((Portable::system(latexCmd,args)!=0) || (Portable::system(latexCmd,args)!=0))
252 {
253 err("Problems running latex. Check your installation or look "
254 "for typos in {0}.tex and check {0}.log!\n",fileName);
255 return false;
256 }
257 // check the log file if we need to run latex again to resolve references
258 DString logFile = fileToString(fileName+".log");
259 if (logFile.empty() ||
260 (logFile.find("Rerun to get cross-references right")==DString::npos &&
261 logFile.find("Rerun LaTeX")==DString::npos))
262 {
263 break;
264 }
265 rerunCount++;
266 }
267 return true;
268}
269
270static bool createPostscriptFile(const DString &fileName,const DString &formBase,int pageIndex)
271{
272 const size_t argsLen = 4096;
273 char args[argsLen];
274 // run dvips to convert the page with number pageIndex to an
275 // postscript file.
276 snprintf(args,argsLen,"-q -D 600 -n 1 -p %d -o %s_tmp.ps %s.dvi",pageIndex,qPrint(formBase),qPrint(fileName));
277 if (Portable::system("dvips",args)!=0)
278 {
279 err("Problems running dvips. Check your installation!\n");
280 return false;
281 }
282 return true;
283}
284
285static bool createEPSbboxFile(const DString &formBase)
286{
287 const size_t argsLen = 4096;
288 char args[argsLen];
289 // extract the bounding box for the postscript file
290 snprintf(args,argsLen,"-q -dBATCH -dNOPAUSE -P- -dNOSAFER -sDEVICE=bbox %s_tmp.ps 2>%s_tmp.epsi",
291 qPrint(formBase),qPrint(formBase));
293 {
294 err("Problems running {}. Check your installation!\n",Portable::ghostScriptCommand());
295 return false;
296 }
297 return true;
298}
299
300static bool extractBoundingBox(const DString &formBase,
301 int *x1,int *y1,int *x2,int *y2,
302 double *x1hi,double *y1hi,double *x2hi,double *y2hi)
303{
304 FileInfo fi((formBase+"_tmp.epsi").str());
305 if (fi.exists())
306 {
307 DString eps = fileToString(formBase+"_tmp.epsi");
308 if (size_t i = eps.find("%%BoundingBox:"); i!=DString::npos)
309 {
310 sscanf(eps.data()+i,"%%%%BoundingBox:%d %d %d %d",x1,y1,x2,y2);
311 }
312 else
313 {
314 err("Couldn't extract bounding box from {}_tmp.epsi\n",formBase);
315 return false;
316 }
317 if (size_t i = eps.find("%%HiResBoundingBox:"); i!=DString::npos)
318 {
319 sscanf(eps.data()+i,"%%%%HiResBoundingBox:%lf %lf %lf %lf",x1hi,y1hi,x2hi,y2hi);
320 }
321 else
322 {
323 err("Couldn't extract high resolution bounding box from {}_tmp.epsi\n",formBase);
324 return false;
325 }
326 }
327 //printf("Bounding box [%d %d %d %d]\n",x1,y1,x2,y2);
328 return true;
329}
330
331static std::mutex g_formulaUpdateMutex;
332
333static double updateFormulaSize(Formula *formula,int x1,int y1,int x2,int y2)
334{
335 double scaleFactor = 1.25;
336 int zoomFactor = Config_getInt(FORMULA_FONTSIZE);
337 if (zoomFactor<8 || zoomFactor>50) zoomFactor=10;
338 scaleFactor *= zoomFactor/10.0;
339
340 if (formula)
341 {
342 std::lock_guard<std::mutex> lock(g_formulaUpdateMutex);
343 formula->setWidth(static_cast<int>((x2-x1)*scaleFactor+0.5));
344 formula->setHeight(static_cast<int>((y2-y1)*scaleFactor+0.5));
345 }
346 return scaleFactor;
347}
348
349static bool createCroppedPDF(const DString &formBase,int x1,int y1,int x2,int y2)
350{
351 const size_t argsLen = 4096;
352 char args[argsLen];
353 // crop the image to its bounding box
354 snprintf(args,argsLen,"-q -dBATCH -dNOPAUSE -P- -dNOSAFER -sDEVICE=pdfwrite"
355 " -o %s_tmp.pdf -c \"[/CropBox [%d %d %d %d] /PAGES pdfmark\" -f %s_tmp.ps",
356 qPrint(formBase),x1,y1,x2,y2,qPrint(formBase));
358 {
359 err("Problems running {}. Check your installation!\n",Portable::ghostScriptCommand());
360 return false;
361 }
362 return true;
363}
364
365static bool createCroppedEPS(const DString &formBase)
366{
367 const size_t argsLen = 4096;
368 char args[argsLen];
369 // crop the image to its bounding box
370 snprintf(args,argsLen,"-q -dBATCH -dNOPAUSE -P- -dNOSAFER -sDEVICE=eps2write"
371 " -o %s_tmp.eps -f %s_tmp.ps",qPrint(formBase),qPrint(formBase));
373 {
374 err("Problems running {}. Check your installation!\n",Portable::ghostScriptCommand());
375 return false;
376 }
377 return true;
378}
379
380static bool createSVGFromPDF(const DString &formBase,const DString &outFile)
381{
382 const size_t argsLen = 4096;
383 char args[argsLen];
384 snprintf(args,argsLen,"%s_tmp.pdf %s",qPrint(formBase),qPrint(outFile));
385 if (Portable::system("pdf2svg",args)!=0)
386 {
387 err("Problems running pdf2svg. Check your installation!\n");
388 return false;
389 }
390 return true;
391}
392
393static bool createSVGFromPDFviaInkscape(const Dir &thisDir,const DString &formBase,const DString &outFile)
394{
395 const size_t argsLen = 4096;
396 char args[argsLen];
397 int inkscapeVersion = determineInkscapeVersion(thisDir);
398 if (inkscapeVersion == -1)
399 {
400 err("Problems determining the version of inkscape. Check your installation!\n");
401 return false;
402 }
403 else if (inkscapeVersion == 0)
404 {
405 snprintf(args,argsLen,"-l %s -z %s_tmp.pdf 2>%s",qPrint(outFile),qPrint(formBase),Portable::devNull());
406 }
407 else // inkscapeVersion >= 1
408 {
409 snprintf(args,argsLen,"--export-type=svg --export-filename=%s %s_tmp.pdf 2>%s",qPrint(outFile),qPrint(formBase),Portable::devNull());
410 }
411 if (Portable::system("inkscape",args)!=0)
412 {
413 err("Problems running inkscape. Check your installation!\n");
414 return false;
415 }
416 return true;
417}
418
419
420static bool updateEPSBoundingBox(const DString &formBase,
421 int x1,int y1,int x2,int y2,
422 double x1hi,double y1hi,double x2hi,double y2hi)
423{
424 // read back %s_tmp.eps and replace
425 // bounding box values with x1,y1,x2,y2 and remove the HiResBoundingBox
426 std::ifstream epsIn = Portable::openInputStream(formBase+"_tmp.eps");
427 std::ofstream epsOut = Portable::openOutputStream(formBase+"_tmp_corr.eps");
428 if (epsIn.is_open() && epsOut.is_open())
429 {
430 std::string line;
431 while (getline(epsIn,line))
432 {
433 if (line.rfind("%%BoundingBox",0)==0)
434 {
435 epsOut << "%%BoundingBox: " << std::max(0,x1-1) << " " << std::max(0,y1-1) << " " << (x2+1) << " " << (y2+1) << "\n";
436 }
437 else if (line.rfind("%%HiResBoundingBox",0)==0)
438 {
439 epsOut << "%%HiResBoundingBox: " << std::max(0.0,x1hi-1.0) << " " << std::max(0.0,y1hi-1.0) << " " << (x2hi+1.0) << " " << (y2hi+1.0) << "\n";
440 }
441 else
442 {
443 epsOut << line << "\n";
444 }
445 }
446 epsIn.close();
447 epsOut.close();
448 }
449 else
450 {
451 err("Problems correcting the eps files from {}_tmp.eps to {}_tmp_corr.eps\n",
452 formBase,formBase);
453 return false;
454 }
455 return true;
456}
457
458static bool createPNG(const DString &formBase,const DString &outFile,double scaleFactor)
459{
460 const size_t argsLen = 4096;
461 char args[argsLen];
462 snprintf(args,argsLen,"-q -dNOSAFER -dBATCH -dNOPAUSE -dEPSCrop -sDEVICE=pngalpha -dGraphicsAlphaBits=4 -dTextAlphaBits=4 "
463 "-r%d -sOutputFile=%s %s_tmp_corr.eps",static_cast<int>(scaleFactor*72),qPrint(outFile),qPrint(formBase));
465 {
466 err("Problems running {}. Check your installation!\n",Portable::ghostScriptCommand());
467 return false;
468 }
469 return true;
470}
471
472static StringVector generateFormula(const Dir &thisDir,const DString &formulaFileName,Formula *formula,int pageNum,int pageIndex,
474{
475 StringVector tempFiles;
476 DString outputFile;
477 outputFile.sprintf("form_%d%s.%s",pageNum, mode==FormulaManager::Mode::Light?"":"_dark", format==FormulaManager::Format::Vector?"svg":"png");
478 msg("Generating image {} for formula\n",outputFile);
479
480 DString formBase;
481 formBase.sprintf("_form%d%s",pageNum,mode==FormulaManager::Mode::Light?"":"_dark");
482
483 if (!createPostscriptFile(formulaFileName,formBase,pageIndex)) return tempFiles;
484
485 int x1=0,y1=0,x2=0,y2=0;
486 double x1hi=0.0,y1hi=0.0,x2hi=0.0,y2hi=0.0;
488 {
489 if (!createEPSbboxFile(formBase)) return tempFiles;
490 // extract the bounding box info from the generated .epsi file
491 if (!extractBoundingBox(formBase,&x1,&y1,&x2,&y2,&x1hi,&y1hi,&x2hi,&y2hi)) return tempFiles;
492 }
493 else // for dark images the bounding box is wrong (includes the black) so
494 // use the bounding box of the light image instead.
495 {
496 DString formBaseLight;
497 formBaseLight.sprintf("_form%d",pageNum);
498 if (!extractBoundingBox(formBaseLight,&x1,&y1,&x2,&y2,&x1hi,&y1hi,&x2hi,&y2hi)) return tempFiles;
499 }
500
501 // convert the corrected EPS to a bitmap
502 double scaleFactor = updateFormulaSize(formula,x1,y1,x2,y2);
503
505 {
506 if (!createCroppedPDF(formBase,x1,y1,x2,y2)) return tempFiles;
507
508 // if we have pdf2svg available use it to create a SVG image
509 if (Portable::checkForExecutable("pdf2svg"))
510 {
511 createSVGFromPDF(formBase,outputFile);
512 }
513 else if (Portable::checkForExecutable("inkscape")) // alternative is to use inkscape
514 {
515 createSVGFromPDFviaInkscape(thisDir,formBase,outputFile);
516 }
517 else
518 {
519 err("Neither 'pdf2svg' nor 'inkscape' present for conversion of formula to 'svg'\n");
520 return tempFiles;
521 }
522
523 tempFiles.push_back(formBase.str()+"_tmp.pdf");
524 }
525 else // format==FormulaManager::Format::Bitmap
526 {
527 if (!createCroppedEPS(formBase)) return tempFiles;
528
529 if (!updateEPSBoundingBox(formBase,x1,y1,x2,y2,x1hi,y1hi,x2hi,y2hi)) return tempFiles;
530
531 if (hd==FormulaManager::HighDPI::On) // for high DPI display it looks much better if the
532 // image resolution is higher than the display resolution
533 {
534 scaleFactor*=2;
535 }
536
537 if (!createPNG(formBase,outputFile,scaleFactor)) return tempFiles;
538
539 tempFiles.push_back(formBase.str()+"_tmp.eps");
540 tempFiles.push_back(formBase.str()+"_tmp_corr.eps");
541 }
542
543 // remove intermediate image files
544 tempFiles.push_back(formBase.str()+"_tmp.ps");
546 {
547 tempFiles.push_back(formBase.str()+"_tmp.epsi");
548 }
549 return tempFiles;
550}
551
552void FormulaManager::createFormulasTexFile(Dir &thisDir,Format format,HighDPI hd,Mode mode,bool toIndex)
553{
554 IntVector formulasToGenerate;
555 DString formulaFileName = mode==Mode::Light ? "_formulas" : "_formulas_dark";
556 createLatexFile(formulaFileName,format,mode,formulasToGenerate,toIndex);
557
558 if (!formulasToGenerate.empty()) // there are new formulas
559 {
560 if (!createDVIFile(formulaFileName)) return;
561
562 auto getFormula = [this](int pageNum) -> Formula *
563 {
564 auto it = p->formulaIdMap.find(pageNum);
565 if (it!=p->formulaIdMap.end())
566 {
567 return it->second;
568 }
569 return nullptr;
570 };
571
572 int pageIndex=1;
573 std::size_t numThreads = static_cast<std::size_t>(Config_getInt(NUM_PROC_THREADS));
574 if (numThreads>1) // multi-threaded version
575 {
576 ThreadPool threadPool(numThreads);
577 std::vector< std::future< StringVector > > results;
578 for (int pageNum : formulasToGenerate)
579 {
580 // create images for each formula.
581 auto formula = getFormula(pageNum);
582 auto processFormula = [=]() -> StringVector
583 {
584 return generateFormula(thisDir,formulaFileName,formula,pageNum,pageIndex,format,hd,mode);
585 };
586 results.emplace_back(threadPool.queue(processFormula));
587 pageIndex++;
588 }
589 for (auto &f : results)
590 {
591 auto tf = f.get();
592 p->tempFiles.insert(p->tempFiles.end(),tf.begin(),tf.end()); // append tf to p->tempFiles
593 }
594 }
595 else // single threaded version
596 {
597 for (int pageNum : formulasToGenerate)
598 {
599 // create images for each formula.
600 auto formula = getFormula(pageNum);
601 StringVector tf = generateFormula(thisDir,formulaFileName,formula,pageNum,pageIndex,format,hd,mode);
602 p->tempFiles.insert(p->tempFiles.end(),tf.begin(),tf.end()); // append tf to p->tempFiles
603
604 pageIndex++;
605 }
606 }
607 // remove intermediate files produced by latex
608 p->tempFiles.push_back(formulaFileName.str()+".dvi");
609 p->tempFiles.push_back(formulaFileName.str()+".log");
610 p->tempFiles.push_back(formulaFileName.str()+".aux");
611 }
612 // remove the latex file itself
613 p->tempFiles.push_back(formulaFileName.str()+".tex");
614
615 // write/update the formula repository so we know what text the
616 // generated images represent (we use this next time to avoid regeneration
617 // of the images, and to avoid forcing the user to delete all images in order
618 // to let a browser refresh the images).
619 std::ofstream f = Portable::openOutputStream("formula.repository");
620 if (f.is_open())
621 {
622 TextStream t(&f);
623 for (const auto &formula : p->formulas)
624 {
625 t << "\\_form#" << formula->id();
626 if (formula->width()!=-1 && formula->height()!=-1)
627 {
628 t << "=" << formula->width() << "x" << formula->height();
629 }
630 t << ":" << formula->text() << "\n";
631 }
632 }
633}
634
635void FormulaManager::generateImages(const DString &path,bool toIndex,Format format,HighDPI hd)
636{
637 Dir d(path.str());
638 // store the original directory
639 if (!d.exists())
640 {
641 term("Output directory '{}' does not exist!\n",path);
642 }
643 std::string oldDir = Dir::currentDirPath();
644
645 DString macroFile = Config_getString(FORMULA_MACROFILE);
646 DString stripMacroFile;
647 if (!macroFile.empty())
648 {
649 FileInfo fi(macroFile.str());
650 macroFile=fi.absFilePath();
651 stripMacroFile = fi.fileName();
652 }
653
654 // go to the html output directory (i.e. path)
656 Dir thisDir;
657
658 if (!macroFile.empty())
659 {
660 copyFile(macroFile,stripMacroFile);
661 }
662
663 createFormulasTexFile(thisDir,format,hd,Mode::Light,toIndex);
664 // for the HTML output format (toIndex == true) we possibly need the dark mode, not for the other formats
665 if (toIndex && Config_getEnum(HTML_COLORSTYLE)!=HTML_COLORSTYLE_t::LIGHT) // all modes other than light need a dark version
666 {
667 // note that the dark version reuses the bounding box of the light version so it needs to be
668 // created after the light version.
669 createFormulasTexFile(thisDir,format,hd,Mode::Dark,toIndex);
670 }
671
672 // clean up temporary files
674 {
675 for (const auto &file : p->tempFiles)
676 {
677 thisDir.remove(file);
678 }
679 }
680
681 // reset the directory to the original location.
682 Dir::setCurrent(oldDir);
683}
684
686{
687 p->formulas.clear();
688 p->formulaIdMap.clear();
689}
690
691int FormulaManager::addFormula(const DString &formulaText,int width,int height)
692{
693 Formula *formula = p->formulas.find(formulaText);
694 if (formula) // same formula already stored
695 {
696 return formula->id();
697 }
698 // add new formula
699 int id = static_cast<int>(p->formulas.size());
700 formula = p->formulas.add(formulaText,id,width,height);
701 p->formulaIdMap.emplace(id,formula);
702 return id;
703}
704
705const Formula *FormulaManager::findFormula(int formulaId) const
706{
707 auto it = p->formulaIdMap.find(formulaId);
708 return it != p->formulaIdMap.end() ? it->second : nullptr;
709}
710
711#if 0
713{
714 auto it = p->formulaIdMap.find(formulaId);
715 return it != p->formulaIdMap.end() ? it->second : nullptr;
716}
717#endif
718
719
721{
722 return !p->formulas.empty();
723}
724
725static std::mutex g_inkscapeDetectionMutex;
726
727// helper function to detect and return the major version of inkscape.
728// return -1 if the version cannot be determined.
729static int determineInkscapeVersion(const Dir &thisDir)
730{
731 std::lock_guard<std::mutex> lock(g_inkscapeDetectionMutex);
732 // The command line interface (CLI) of Inkscape 1.0 has changed in comparison to
733 // previous versions. In order to invokine Inkscape, the used version is detected
734 // and based on the version the right syntax of the CLI is chosen.
735 static int inkscapeVersion = -2;
736 if (inkscapeVersion == -2) // initial one time version check
737 {
738 DString inkscapeVersionFile = "inkscape_version" ;
739 inkscapeVersion = -1;
740 DString args = "-z --version >"+inkscapeVersionFile+" 2>"+Portable::devNull();
741 if (Portable::system("inkscape",args)!=0)
742 {
743 // looks like the old syntax gave problems, lets try the new syntax
744 args = " --version >"+inkscapeVersionFile+" 2>"+Portable::devNull();
745 if (Portable::system("inkscape",args)!=0)
746 {
747 return -1;
748 }
749 }
750 // read version file and determine major version
751 std::ifstream inkscapeVersionIn = Portable::openInputStream(inkscapeVersionFile);
752 if (inkscapeVersionIn.is_open())
753 {
754 std::string line;
755 while (getline(inkscapeVersionIn,line))
756 {
757 size_t dotPos = line.find('.');
758 if (line.rfind("Inkscape ",0)==0 && dotPos>0)
759 {
760 // get major version
761 inkscapeVersion = std::stoi(line.substr(9,dotPos-9));
762 break;
763 }
764 }
765 inkscapeVersionIn.close();
766 }
767 else // failed to open version file
768 {
769 return -1;
770 }
772 {
773 thisDir.remove(inkscapeVersionFile.str());
774 }
775 }
776 return inkscapeVersion;
777}
constexpr auto prefix
Definition anchor.cpp:47
A String class for use with Doxygen wrapping std::string and adding some additional functionality off...
Definition dstring.h:84
bool empty() const
Returns true iff the string is empty (std::string compatible alias for isEmpty()).
Definition dstring.h:148
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:178
size_t find(char c, size_t pos=0) const
Definition dstring.h:239
DString & sprintf(const char *format,...)
Definition dstring.cpp:34
const std::string & str() const
Definition dstring.h:645
const char * data() const
Returns a pointer to the contents of the string in the form of a 0-terminated C string.
Definition dstring.h:157
@ Formula
Definition debug.h:34
static bool isFlagSet(const DebugMask mask)
Definition debug.cpp:132
Class representing a directory in the file system.
Definition dir.h:73
static std::string currentDirPath()
Definition dir.cpp:348
std::string absPath() const
Definition dir.cpp:370
bool remove(const std::string &path, bool acceptsAbsPath=true) const
Definition dir.cpp:320
static bool setCurrent(const std::string &path)
Definition dir.cpp:356
bool exists() const
Definition dir.cpp:263
static IndexList * indexList
Definition doxygen.h:125
Minimal replacement for QFileInfo.
Definition fileinfo.h:26
bool exists() const
Definition fileinfo.cpp:34
std::string fileName() const
Definition fileinfo.cpp:122
std::string absFilePath() const
Definition fileinfo.cpp:105
Class representing a LaTeX formula as found in the documentation.
Definition formula.h:29
void setCachedDark(bool cached)
Definition formula.h:46
DString text() const
Definition formula.h:37
void setHeight(int height)
Definition formula.h:41
void setCached(bool cached)
Definition formula.h:45
void setWidth(int width)
Definition formula.h:40
int id() const
Definition formula.h:36
int addFormula(const DString &formulaText, int width=-1, int height=-1)
Definition formula.cpp:691
bool hasFormulas() const
Definition formula.cpp:720
void createFormulasTexFile(Dir &d, Format format, HighDPI hd, Mode mode, bool toIndex)
Definition formula.cpp:552
void initFromRepository(const DString &dir)
Definition formula.cpp:60
void checkRepositories()
Definition formula.cpp:173
const Formula * findFormula(int formulaId) const
Definition formula.cpp:705
static FormulaManager & instance()
Definition formula.cpp:54
void generateImages(const DString &outputDir, bool toIndex, Format format, HighDPI hd=HighDPI::Off)
Definition formula.cpp:635
std::unique_ptr< Private > p
Definition formula.h:90
void createLatexFile(const DString &fileName, Format format, Mode mode, IntVector &formulasToGenerate, bool toIndex)
Definition formula.cpp:184
void addImageFile(const DString &name)
Definition indexlist.h:124
Container class representing a vector of objects with keys.
Definition linkedmap.h:36
Text streaming class that buffers data.
Definition textstream.h:36
void flush()
Flushes the buffer.
Definition textstream.h:212
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
Class representing a regular expression.
Definition regex.h:39
Object representing the matching results.
Definition regex.h:154
#define Config_getInt(name)
Definition config.h:34
#define Config_getString(name)
Definition config.h:32
#define Config_getEnum(name)
Definition config.h:35
std::vector< int > IntVector
Definition containers.h:38
std::vector< std::string > StringVector
Definition containers.h:33
const char * qPrint(const char *s)
Definition dstring.h:783
static bool createPostscriptFile(const DString &fileName, const DString &formBase, int pageIndex)
Definition formula.cpp:270
static int determineInkscapeVersion(const Dir &thisDir)
Definition formula.cpp:729
static std::mutex g_formulaUpdateMutex
Definition formula.cpp:331
static std::mutex g_inkscapeDetectionMutex
Definition formula.cpp:725
static bool extractBoundingBox(const DString &formBase, int *x1, int *y1, int *x2, int *y2, double *x1hi, double *y1hi, double *x2hi, double *y2hi)
Definition formula.cpp:300
static double updateFormulaSize(Formula *formula, int x1, int y1, int x2, int y2)
Definition formula.cpp:333
static bool updateEPSBoundingBox(const DString &formBase, int x1, int y1, int x2, int y2, double x1hi, double y1hi, double x2hi, double y2hi)
Definition formula.cpp:420
static StringVector generateFormula(const Dir &thisDir, const DString &formulaFileName, Formula *formula, int pageNum, int pageIndex, FormulaManager::Format format, FormulaManager::HighDPI hd, FormulaManager::Mode mode)
Definition formula.cpp:472
static bool createSVGFromPDF(const DString &formBase, const DString &outFile)
Definition formula.cpp:380
static bool createPNG(const DString &formBase, const DString &outFile, double scaleFactor)
Definition formula.cpp:458
static bool createSVGFromPDFviaInkscape(const Dir &thisDir, const DString &formBase, const DString &outFile)
Definition formula.cpp:393
static bool createCroppedEPS(const DString &formBase)
Definition formula.cpp:365
static bool createCroppedPDF(const DString &formBase, int x1, int y1, int x2, int y2)
Definition formula.cpp:349
static bool createEPSbboxFile(const DString &formBase)
Definition formula.cpp:285
static bool createDVIFile(const DString &fileName)
Definition formula.cpp:241
void writeExtraLatexPackages(TextStream &t)
void writeLatexSpecialFormulaChars(TextStream &t)
#define warn_uncond(fmt,...)
Definition message.h:122
#define msg(fmt,...)
Definition message.h:94
#define err(fmt,...)
Definition message.h:127
#define term(fmt,...)
Definition message.h:137
std::ifstream openInputStream(const DString &name, bool binary=false, bool openAtEnd=false)
Definition portable.cpp:692
const char * ghostScriptCommand()
Definition portable.cpp:453
int system(const DString &command, const DString &args, bool commandHasConsole=true)
Definition portable.cpp:121
std::ofstream openOutputStream(const DString &name, bool append=false)
Definition portable.cpp:681
const char * devNull()
Definition portable.cpp:630
bool checkForExecutable(const DString &fileName)
Definition portable.cpp:439
bool search(std::string_view str, Match &match, const Ex &re, size_t pos)
Search in a given string str starting at position pos for a match against regular expression re.
Definition regex.cpp:850
Definition dstring.h:913
Portable versions of functions that are platform dependent.
LinkedMap< Formula > formulas
Definition formula.cpp:44
std::map< int, Formula * > formulaIdMap
Definition formula.cpp:45
StringVector tempFiles
Definition formula.cpp:47
DString fileToString(const DString &name, bool filter, bool isSourceCode)
Definition util.cpp:1053
bool copyFile(const DString &src, const DString &dest)
Copies the contents of file with name src to the newly created file with name dest.
Definition util.cpp:4619
A bunch of utility functions.