-
Notifications
You must be signed in to change notification settings - Fork 351
/
Copy pathbuildmanager.cpp
2555 lines (2281 loc) · 98 KB
/
buildmanager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "buildmanager.h"
#include "smallUsefulFunctions.h"
#include "configmanagerinterface.h"
#include "utilsSystem.h"
#include "execprogram.h"
#include "findindirs.h"
#include "userquickdialog.h"
#ifdef Q_OS_WIN32
#include "windows.h"
#endif
inline const char * onWin_Nix(const char * const win,const char * const nix){
#ifdef Q_OS_WIN32
(void) nix;
return win;
#else
(void) win;
return nix;
#endif
}
const QString BuildManager::TXS_CMD_PREFIX = "txs:///";
int BuildManager::autoRerunLatex = 5;
bool BuildManager::showLogInCaseOfCompileError = true;
bool BuildManager::m_replaceEnvironmentVariables = true;
bool BuildManager::m_interpetCommandDefinitionInMagicComment = true;
bool BuildManager::m_supportShellStyleLiteralQuotes = true;
bool BuildManager::singleViewerInstance = false;
QString BuildManager::autoRerunCommands;
QString BuildManager::additionalSearchPaths, BuildManager::additionalPdfPaths, BuildManager::additionalLogPaths;
// *INDENT-OFF* (astyle-config)
#define CMD_DEFINE(name,id) \
const QString BuildManager::CMD_##name = BuildManager::TXS_CMD_PREFIX + #id
CMD_DEFINE(LATEX,latex);
CMD_DEFINE(PDFLATEX,pdflatex);
CMD_DEFINE(XELATEX,xelatex);
CMD_DEFINE(LUALATEX,lualatex);
CMD_DEFINE(LATEXMK,latexmk);
CMD_DEFINE(VIEW_DVI,view-dvi);
CMD_DEFINE(VIEW_PS,view-ps);
CMD_DEFINE(VIEW_PDF,view-pdf);
CMD_DEFINE(VIEW_LOG,view-log);
CMD_DEFINE(DVIPNG,dvipng);
CMD_DEFINE(DVIPS,dvips);
CMD_DEFINE(DVIPDF,dvipdf);
CMD_DEFINE(PS2PDF,ps2pdf);
CMD_DEFINE(GS,gs);
CMD_DEFINE(MAKEINDEX,makeindex);
CMD_DEFINE(TEXINDY,texindy);
CMD_DEFINE(XINDEX,xindex);
CMD_DEFINE(MAKEGLOSSARIES,makeglossaries);
CMD_DEFINE(METAPOST,metapost);
CMD_DEFINE(ASY,asy);
CMD_DEFINE(BIBTEX,bibtex);
CMD_DEFINE(BIBTEX8,bibtex8);
CMD_DEFINE(BIBER,biber);
CMD_DEFINE(SVN,svn);
CMD_DEFINE(SVNADMIN,svnadmin);
CMD_DEFINE(GIT,git);
CMD_DEFINE(TEXDOC,texdoc);
CMD_DEFINE(COMPILE,compile);
CMD_DEFINE(VIEW,view);
CMD_DEFINE(BIBLIOGRAPHY,bibliography);
CMD_DEFINE(INDEX,index);
CMD_DEFINE(GLOSSARY,glossary);
CMD_DEFINE(QUICK,quick);
CMD_DEFINE(RECOMPILE_BIBLIOGRAPHY,recompile-bibliography);
CMD_DEFINE(VIEW_PDF_INTERNAL,view-pdf-internal);
CMD_DEFINE(CONDITIONALLY_RECOMPILE_BIBLIOGRAPHY,conditionally-recompile-bibliography);
CMD_DEFINE(INTERNAL_PRE_COMPILE,internal-pre-compile);
CMD_DEFINE(TERMINAL_EXTERNAL,terminal-external);
#undef CMD_DEFINE
// *INDENT-ON* (astyle-config)
//! These commands should not consist of a command list, but rather a single command.
//! Otherwise surpising side effects can happen, see https://sourceforge.net/p/texstudio/bugs/2119/
const QStringList atomicCommands = QStringList() << "txs:///latex" << "txs:///pdflatex" << "txs:///xelatex"<< "txs:///lualatex" << "txs:///latexmk";
QString searchBaseCommand(const QString &cmd, QString options, QString texPath="");
QString getCommandLineViewDvi();
QString getCommandLineViewPs();
QString getCommandLineViewPdfExternal();
QString getCommandLineGhostscript();
CommandInfo::CommandInfo(): user(false), meta(false), rerunCompiler(false), guessFunc(nullptr) {}
QString CommandInfo::guessCommandLine(const QString texpath) const
{
if (guessFunc) {
QString temp = (*guessFunc)();
if (!temp.isEmpty()) return temp;
}
if (!baseName.isEmpty()) {
//search it
QString bestCommand = searchBaseCommand(baseName, defaultArgs,texpath);
if (!bestCommand.isEmpty()) return bestCommand;
}
if (metaSuggestionList.size() > 0)
return metaSuggestionList.first();
return "";
}
void CommandInfo::setCommandLine(const QString &cmdString)
{
if (cmdString == "<default>") commandLine = guessCommandLine();
if (cmdString == BuildManager::tr("<unknown>")) commandLine = "";
else {
//force commands to include options (e.g. file name)
QString trimmed = cmdString.trimmed();
QString unquote = trimmed;
if (trimmed.startsWith('"') && trimmed.endsWith('"')) unquote = trimmed.mid(1, trimmed.length() - 2);
if (baseName != "" &&
((unquote == baseName) ||
( (unquote.endsWith(QDir::separator() + baseName) || unquote.endsWith("/" + baseName))
&& (!unquote.contains(" ") || (!unquote.contains('"') && unquote != trimmed)) //spaces mean options, if not everything is quoted
&& (QFileInfo::exists(unquote))
)
)) {
commandLine = cmdString + " " + defaultArgs;
} else {
commandLine = cmdString;
}
}
}
QString CommandInfo::getPrettyCommand() const
{
if (commandLine.isEmpty() && metaSuggestionList.isEmpty()) return BuildManager::tr("<unknown>");
else return commandLine;
}
QString CommandInfo::getProgramName(const QString &commandLine)
{
QString cmdStr = commandLine.trimmed();
int p = -1;
if (cmdStr.startsWith('"')) p = cmdStr.indexOf('"', 1) + 1;
else if (cmdStr.contains(' ')) p = cmdStr.indexOf(' ');
if (p == -1) p = cmdStr.length(); //indexOf failed if it returns -1
return cmdStr.mid(0, p);
}
QString CommandInfo::getProgramNameUnquoted(const QString &commandLine)
{
QString cmdStr = getProgramName(commandLine);
if (cmdStr.startsWith('"') && cmdStr.endsWith('"'))
cmdStr = cmdStr.mid(1, cmdStr.length() - 2);
return cmdStr;
}
QString CommandInfo::getProgramName() const
{
return getProgramName(commandLine);
}
QString CommandInfo::getProgramNameUnquoted() const
{
return getProgramNameUnquoted(commandLine);
}
ExpandingOptions::ExpandingOptions(const QFileInfo &mainFile, const QFileInfo ¤tFile, const int currentLine): mainFile(mainFile), currentFile(currentFile), currentLine(currentLine), nestingDeep(0), canceled(false)
{
override.removeAll = false;
}
/*
QString BuildManager::getLatexCommandExecutable(LatexCommand cmd){
QString cmdStr = getLatexCommand(cmd).trimmed();
int p=-1;
if (cmdStr.startsWith('"')) p = cmdStr.indexOf('"',1)+1;
else if (cmdStr.contains(' ')) p = cmdStr.indexOf(' ')+1;
if (p==-1) p = cmdStr.length(); //indexOf failed if it returns -1
return cmdStr.mid(0, p);
}*/
CommandToRun::CommandToRun() {}
CommandToRun::CommandToRun(const QString &cmd): command(cmd) {}
QString BuildManager::chainCommands(const QString &a)
{
return a;
}
QString BuildManager::chainCommands(const QString &a, const QString &b)
{
return a + "|" + b;
}
QString BuildManager::chainCommands(const QString &a, const QString &b, const QString &c)
{
return a + "|" + b + "|" + c;
}
QString BuildManager::chainCommands(const QString &a, const QString &b, const QString &c, const QString &d)
{
return a + "|" + b + "|" + c + "|" + d;
}
/** splits a string into options. Splitting occurs at spaces, except in quotes. **/
QStringList BuildManager::splitOptions(const QString &s)
{
QStringList options;
QChar c;
bool inQuote = false;
int start = 0;
int i;
for (i = 0; i < s.length(); i++) {
c = s[i];
if (inQuote) {
if (c == '"' && s[i - 1] != '\\') {
inQuote = false;
}
} else {
if (c == '"') {
inQuote = true;
} else if (c == ' ') {
if (start == i) start = i + 1; // multiple spaces;
else {
options << dequoteStr(s.mid(start, i - start));
start = i + 1;
}
}
}
}
if (start < i) options << dequoteStr(s.mid(start, i - start));
return options;
}
QHash<QString, QString> getEnvVariables(bool uppercaseNames)
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QHash<QString, QString> result;
foreach (const QString &name, env.keys()) {
if (uppercaseNames) {
result.insert(name.toUpper(), env.value(name));
} else {
result.insert(name, env.value(name));
}
}
return result;
}
QString BuildManager::replaceEnvironmentVariables(const QString &s)
{
#ifdef Q_OS_WIN
Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive;
#else
Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive;
#endif
static QHash<QString, QString> envVariables = getEnvVariables(caseSensitivity == Qt::CaseInsensitive); // environment variables can be static because they do not change during program execution.
return replaceEnvironmentVariables(s, envVariables, caseSensitivity == Qt::CaseInsensitive);
}
/*!
* Replace environment variables in the string.
*/
QString BuildManager::replaceEnvironmentVariables(const QString &s, const QHash<QString, QString> &variables, bool compareNamesToUpper)
{
QString result(s);
#ifdef Q_OS_WIN
QRegularExpression rxEnvVar("%([\\w()]+)%"); // word and brackets between %...%
#else
QRegularExpression rxEnvVar("\\$(\\w+)");
#endif
int i = 0;
while (i >= 0 && i < result.length()) {
QRegularExpressionMatch match;
i = result.indexOf(rxEnvVar, i,&match);
if (i >= 0) {
QString varName = match.captured(1);
if (compareNamesToUpper) {
varName = varName.toUpper();
}
QString varContent = variables.value(varName, "");
result.replace(match.captured(0), varContent);
i += varContent.length();
}
}
return result;
}
/*!
* returns paths with replaced [txs-app-dir], [txs-config-dir] and optionally with replaced environment variables
* paths may be an arbitrary string, in particular a single path or a list of paths
*/
QString BuildManager::resolvePaths(QString paths)
{
paths = ConfigManagerInterface::getInstance()->parseDir(paths);
if (m_replaceEnvironmentVariables)
return replaceEnvironmentVariables(paths);
else
return paths;
}
BuildManager::BuildManager(): processWaitedFor(nullptr)
#ifdef Q_OS_WIN32
, pidInst(0)
#endif
{
initDefaultCommandNames();
connect(this, SIGNAL(commandLineRequested(QString,QString*,bool*)), SLOT(commandLineRequestedDefault(QString,QString*,bool*)));
}
BuildManager::~BuildManager()
{
//remove preview file names
foreach (const QString &elem, previewFileNames)
removePreviewFiles(elem);
#ifdef Q_OS_WIN32
if (pidInst) DdeUninitialize(pidInst);
#endif
}
void BuildManager::initDefaultCommandNames()
{
REQUIRE (commands.isEmpty());
//id, platform-independent command, display name, arguments
registerCommand("latex", "latex", "LaTeX", "-src -interaction=nonstopmode %.tex", "Tools/Latex");
registerCommand("pdflatex", "pdflatex", "PdfLaTeX", "-synctex=1 -interaction=nonstopmode %.tex", "Tools/Pdflatex");
registerCommand("xelatex", "xelatex", "XeLaTeX", "-synctex=1 -interaction=nonstopmode %.tex", "");
registerCommand("lualatex", "lualatex", "LuaLaTeX", "-synctex=1 -interaction=nonstopmode %.tex", "");
registerCommand("view-dvi", "", tr("DVI Viewer"), "%.dvi", "Tools/Dvi", &getCommandLineViewDvi);
registerCommand("view-ps", "", tr("PS Viewer"), "%.ps", "Tools/Ps", &getCommandLineViewPs);
registerCommand("view-pdf-external", "", tr("External PDF Viewer"), "%.pdf", "Tools/Pdf", &getCommandLineViewPdfExternal);
registerCommand("dvips", "dvips", "DviPs", "-o %.ps %.dvi", "Tools/Dvips");
registerCommand("dvipng", "dvipng", "DviPng", "-T tight -D 120 %.dvi", "Tools/Dvipng");
registerCommand("ps2pdf", "ps2pdf", "Ps2Pdf", "%.ps", "Tools/Ps2pdf");
registerCommand("dvipdf", "dvipdfmx", "DviPdf", "%.dvi", "Tools/Dvipdf");
registerCommand("bibtex", "bibtex", "BibTeX", onWin_Nix("%","%.aux"), "Tools/Bibtex"); //miktex bibtex will stop (appears like crash in txs) if .aux is attached
registerCommand("bibtex8", "bibtex8", "BibTeX 8-Bit", onWin_Nix("%","%.aux"));
registerCommand("biber", "biber", "Biber" , "%"); //todo: correct parameter?
registerCommand("makeindex", "makeindex", "Makeindex", "%.idx", "Tools/Makeindex");
registerCommand("texindy", "texindy", "Texindy", "%.idx");
registerCommand("xindex", "xindex", "Xindex", "-l * %.idx");
registerCommand("makeglossaries", "makeglossaries", "Makeglossaries", "%");
registerCommand("metapost", "mpost", "MetaPost", "-interaction=nonstopmode ?me)", "Tools/MetaPost");
registerCommand("asy", "asy", "Asymptote", "?m*.asy", "Tools/Asy");
registerCommand("gs", "gs;mgs", "Ghostscript", "\"?am.ps\"", "Tools/Ghostscript", &getCommandLineGhostscript);
registerCommand("latexmk", "latexmk", "Latexmk", "-pdf -silent -synctex=1 %");
registerCommand("texdoc", "texdoc", "texdoc", "");
QStringList descriptionList;
descriptionList << tr("Compile & View") << tr("PS Chain") << tr("DVI Chain") << tr("PDF Chain") << tr("DVI->PDF Chain") << tr("DVI->PS->PDF Chain") << tr("Asymptote DVI Chain") << tr("Asymptote PDF Chain");
registerCommand("quick", tr("Build & View"), QStringList() << "txs:///compile | txs:///view" << "txs:///ps-chain" << "txs:///dvi-chain" << "txs:///pdf-chain" << "txs:///dvi-pdf-chain" << "txs:///dvi-ps-pdf-chain" << "txs:///asy-dvi-chain" << "txs:///asy-pdf-chain" /* too long breaks design<< "latex -interaction=nonstopmode %.tex|bibtex %.aux|latex -interaction=nonstopmode %.tex|latex -interaction=nonstopmode %.tex| txs:///view-dvi"*/, "Tools/Userquick", true, descriptionList);
descriptionList.clear();
descriptionList << tr("PdfLaTeX") << tr("LaTeX") << tr("XeLaTeX") << tr("LuaLaTeX") << tr("Latexmk");
registerCommand("compile", tr("Default Compiler"), QStringList() << "txs:///pdflatex" << "txs:///latex" << "txs:///xelatex" << "txs:///lualatex" << "txs:///latexmk", "", true, descriptionList);
descriptionList.clear();
descriptionList << tr("PDF Viewer") << tr("DVI Viewer") << tr("PS Viewer");
registerCommand("view", tr("Default Viewer"), QStringList() << "txs:///view-pdf" << "txs:///view-dvi" << "txs:///view-ps", "", true, descriptionList);
descriptionList.clear();
descriptionList << tr("Internal PDF Viewer (Embedded)") << tr("Internal PDF Viewer (Windowed)") << tr("External PDF Viewer");
registerCommand("view-pdf", tr("PDF Viewer"), QStringList() << "txs:///view-pdf-internal --embedded" << "txs:///view-pdf-internal" << "txs:///view-pdf-external", "", true, descriptionList);
descriptionList.clear();
descriptionList << tr("BibTeX") << tr("BibTeX 8-Bit") << tr("Biber");
registerCommand("bibliography", tr("Default Bibliography Tool"), QStringList() << "txs:///bibtex" << "txs:///bibtex8" << "txs:///biber", "", true, descriptionList);
descriptionList.clear();
descriptionList << tr("BibTeX") << tr("BibTeX 8-Bit") << tr("Biber");
registerCommand("index", tr("Default Index Tool"), QStringList() << "txs:///makeindex" << "txs:///texindy" << "txs:///xindex", "", true, descriptionList);
descriptionList.clear();
descriptionList << tr("Makeglossaries");
registerCommand("glossary", tr("Default Glossary Tool"), QStringList() << "txs:///makeglossaries", "", true, descriptionList);
registerCommand("ps-chain", tr("PS Chain"), QStringList() << "txs:///latex | txs:///dvips | txs:///view-ps");
registerCommand("dvi-chain", tr("DVI Chain"), QStringList() << "txs:///latex | txs:///view-dvi");
registerCommand("pdf-chain", tr("PDF Chain"), QStringList() << "txs:///pdflatex | txs:///view-pdf");
registerCommand("dvi-pdf-chain", tr("DVI->PDF Chain"), QStringList() << "txs:///latex | txs:///dvipdf | txs:///view-pdf");
registerCommand("dvi-ps-pdf-chain", tr("DVI->PS->PDF Chain"), QStringList() << "txs:///latex | txs:///dvips | txs:///ps2pdf | txs:///view-pdf");
registerCommand("asy-dvi-chain", tr("Asymptote DVI Chain"), QStringList() << "txs:///latex | txs:///asy | txs:///latex | txs:///view-dvi");
registerCommand("asy-pdf-chain", tr("Asymptote PDF Chain"), QStringList() << "txs:///pdflatex | txs:///asy | txs:///pdflatex | txs:///view-pdf");
registerCommand("pre-compile", tr("Precompile"), QStringList() << "", "Tools/Precompile");
registerCommand("internal-pre-compile", tr("Internal Precompile"), QStringList() << "txs:///pre-compile | txs:///conditionally-recompile-bibliography");
registerCommand("recompile-bibliography", tr("Recompile Bibliography"), QStringList() << "txs:///compile | txs:///bibliography | txs:///compile");
registerCommand("svn", "svn", "SVN", "", "Tools/SVN");
registerCommand("svnadmin", "svnadmin", "SVNADMIN", "", "Tools/SVNADMIN");
registerCommand("git", "git", "GIT", "", "Tools/GIT");
registerCommand("terminal-external", "", tr("External Terminal"), "", "", guessTerminalExternal, false);
internalCommands << CMD_VIEW_PDF_INTERNAL << CMD_CONDITIONALLY_RECOMPILE_BIBLIOGRAPHY << CMD_VIEW_LOG;
}
QString BuildManager::guessTerminalExternal(void)
{
#if defined(Q_OS_DARWIN)
return "open -a Terminal ?c:a\"";
#elif defined(Q_OS_UNIX)
// Linux/Unix does not have a uniform way to determine the default terminal application
// Gnome
ExecProgram execGsettings("gsettings get org.gnome.desktop.default-applications.terminal exec", "");
if (execGsettings.execAndWait()) {
/*
1. "gsettings" terminates with exit code 0 if settings were fetched successfully.
2. The returned value has a trailing LF so we trim it.
3. The command is wrapped in single quotes, e.g. 'gnome-terminal' so we remove the single quotes.
*/
return execGsettings.m_standardOutput.trimmed().replace('\'', "");
}
// Fallback
QStringList fallbacks = QStringList() << "konsole" << "xterm";
foreach (const QString &fallback, fallbacks) {
ExecProgram execWhich("which " + fallback, "");
if (execWhich.execAndWait()) {
// "which" terminates with exit code 0 if settings were fetched successfully
return execWhich.m_standardOutput;
}
}
#elif defined(Q_OS_WIN)
QString command = QString::fromLocal8Bit(qgetenv("COMSPEC"));
if (command != "") {
return command;
}
#endif
return QString("<unknown>");
}
CommandInfo &BuildManager::registerCommand(const QString &id, const QString &basename, const QString &displayName, const QString &args, const QString &oldConfig, const GuessCommandLineFunc guessFunc, bool user )
{
CommandInfo ci;
ci.id = id;
ci.baseName = basename;
ci.displayName = displayName;
ci.defaultArgs = args;
ci.deprecatedConfigName = oldConfig;
ci.guessFunc = guessFunc;
ci.user = user;
if (!user) commandSortingsOrder << id;
return commands.insert(id, ci).value();
}
CommandInfo &BuildManager::registerCommand(const QString &id, const QString &displayname, const QStringList &alternatives, const QString &oldConfig, const bool metaCommand, const QStringList simpleDescriptions)
{
CommandInfo ci;
ci.id = id;
ci.displayName = displayname;
ci.metaSuggestionList = alternatives;
ci.simpleDescriptionList = simpleDescriptions;
ci.meta = metaCommand;
ci.deprecatedConfigName = oldConfig;
commandSortingsOrder << id;
return commands.insert(id, ci).value();
}
QString BuildManager::getCommandLine(const QString &id, bool *user)
{
QString result;
emit commandLineRequested(id.trimmed(), &result, user);
return result;
}
QStringList BuildManager::parseExtendedCommandLine(QString str, const QFileInfo &mainFile, const QFileInfo ¤tFile, int currentline)
{
ConfigManagerInterface *config = ConfigManagerInterface::getInstance();
str = config->parseDir(str);
if (m_replaceEnvironmentVariables) {
str = replaceEnvironmentVariables(str);
}
// need to reformat literal quotes before the file insertion logic, because ?a"
// might be extended to "C:\somepath\" which would then be misinterpreted as an
// literal quote at the end.
if (config->getOption("Tools/SupportShellStyleLiteralQuotes", true).toBool()) {
str = ProcessX::reformatShellLiteralQuotes(str);
}
str = str + " "; //end character so str[i++] is always defined
QStringList result;
result.append("");
for (int i = 0; i < str.size(); i++) {
QString add;
if (str.at(i) == QChar('%')) {
if (str.at(i + 1) == QChar('%')) add = str.at(++i);
else add = "\"" + mainFile.completeBaseName() + "\"";
} else if (str.at(i) == QChar('@')) {
if (str.at(i + 1) == QChar('@')) add = str.at(++i);
else add = QString::number(currentline);
} else if (str.at(i) == QChar('?')) {
if (str.at(++i) == QChar('?')) add = "?";
else {
QString command, commandRem;
QString *createCommand = &command;
int endMode = 0;
bool fullSearch = false;
while (i < str.size()) {
if (str.at(i) == QChar(')')) {
endMode = 1;
break;
} else if (str.at(i) == QChar(' ') || str.at(i) == QChar('\t')) {
endMode = 2;
break;
} else if (str.at(i) == QChar('\"')) {
endMode = 3;
break;
} else if (str.at(i) == QChar('.') && !fullSearch) {
endMode = 4;
break;
} else if (str.at(i) == QChar('*')) {
fullSearch = true;
createCommand = &commandRem;
}
(*createCommand) += str.at(i);
i++;
}
QFileInfo selectedFile = parseExtendedSelectFile(command, mainFile, currentFile);
bool absPath = command.startsWith('a');
//check only sane commands
if (command == "ame")
command = QDir::toNativeSeparators(selectedFile.absoluteFilePath());
else if (command == "am") {
command = QDir::toNativeSeparators(selectedFile.absoluteFilePath());
if (selectedFile.suffix() != "") command.chop(1 + selectedFile.suffix().length());
} else if (command == "a") {
command = QDir::toNativeSeparators(selectedFile.absolutePath());
if (!command.endsWith(QDir::separator())) command += QDir::separator();
} else if (command == "rme")
command = QDir::toNativeSeparators(mainFile.dir().relativeFilePath(selectedFile.absoluteFilePath()));
else if (command == "rm") {
command = QDir::toNativeSeparators(mainFile.dir().relativeFilePath(selectedFile.absoluteFilePath()));
if (selectedFile.suffix() != "") command.chop(1 + selectedFile.suffix().length());
} else if (command == "r") {
command = QDir::toNativeSeparators(mainFile.dir().relativeFilePath(selectedFile.absolutePath()));
if (command == "") command = ".";
if (!command.endsWith(QDir::separator())) command += QDir::separator();
} else if (command == "me") command = selectedFile.fileName();
else if (command == "m") command = selectedFile.completeBaseName();
else if (command == "e") command = selectedFile.suffix();
else if (command.isEmpty() && !commandRem.isEmpty()); //empty search
else continue; //invalid command
command.append(commandRem);
switch (endMode) {
case 2:
command += " ";
break;
case 3:
command = "\"" + command + "\"";
break;
case 4:
command += ".";
break;
default:
;
}
if (!fullSearch) add = command;
else {
QDir dir(QFileInfo(mainFile).absoluteDir());
if (command.contains("/")) command = command.mid(command.lastIndexOf("/") + 1);
if (command.contains(QDir::separator())) command = command.mid(command.lastIndexOf(QDir::separator()) + 1);
QStringList commands = QDir(dir).entryList(QStringList() << command.trimmed(), QDir::Files);
QString mid;
if (absPath) {
mid = QDir::toNativeSeparators(dir.canonicalPath());
if (!mid.endsWith('/') && !mid.endsWith(QDir::separator())) mid += QDir::separator();
}
QStringList oldCommands = result;
result.clear();
for (int i = 0; i < oldCommands.size(); i++)
for (int j = 0; j < commands.size(); j++)
result.append(oldCommands[i] + mid + commands[j]);
}
}
} else add = str.at(i);
if (!add.isEmpty())
for (int i = 0; i < result.size(); i++)
result[i] += add;
}
// QMessageBox::information(0,"",str+"->"+result,0);
for (int i = 0; i < result.size(); i++) result[i] = result[i].trimmed(); //remove useless characters
return result;
}
/*
* Select a file which provides the pathname parts used by the "ame" expansions. Currently we can select
* one of the following files:
*
* - Master (root) .tex file (default).
* - Current .tex file. Selected by the c: prefix.
* - A file with the same complete basename as the master file and a chosen extension. The search for this
* file is done in the master file directory and then the extra PDF directories. Selected by the p{ext}:
* prefix.
*
* TODO: If selector ?p{ext}: is not flexible enough then maybe we should implement another selector:
* ?f{regexp_with_basename}:
*
* It will be processed like this:
*
* 1. regexp_with_basename undergoes %-token replacement
* %m is replaced by the complete basename of the master file.
* %% is replaced by %
* 2. The expression from 1 is used to search the master file directory, the current file
* directory and the extra PDF directories.
* 3. If step 2 finds a matching file it is used as a selected file. If step 2 does not
* find a file, then some reasonable default is used.
*/
QFileInfo BuildManager::parseExtendedSelectFile(QString &command, const QFileInfo &mainFile, const QFileInfo ¤tFile)
{
QFileInfo selectedFile;
QRegExp rxPdf("^p\\{([^{}]+)\\}:");
if (command.startsWith("c:")) {
selectedFile = currentFile.fileName().isEmpty() ? mainFile : currentFile;
command = command.mid(2);
} else if (rxPdf.indexIn(command) != -1) {
QString compiledFilename = mainFile.completeBaseName() + '.' + rxPdf.cap(1);
QString compiledFound = findCompiledFile(compiledFilename, mainFile);
selectedFile = QFileInfo(compiledFound);
command = command.mid(rxPdf.matchedLength());
} else {
selectedFile = mainFile;
}
return selectedFile;
}
/*!
* \brief extracts the
* \param s
* \param stdOut output parameter
* \param stdErr output parameter
* \return a copy of s truncated to the first occurrence of an output redirection
*/
QString BuildManager::extractOutputRedirection(const QString &commandLine, QString &stdOut, QString &stdErr)
{
QStringList args = ::extractOutputRedirection(tokenizeCommandLine(commandLine), stdOut, stdErr);
if (stdOut.isEmpty() && stdErr.isEmpty()) {
return commandLine;
} else {
return args.join(" ");
}
}
QString addPathDelimeter(const QString &a)
{
return ((a.endsWith("/") || a.endsWith("\\")) ? a : (a + QDir::separator()));
}
QString BuildManager::findFileInPath(QString fileName)
{
foreach (QString path, getEnvironmentPathList()) {
path = addPathDelimeter(path);
if (QFileInfo::exists(path + fileName)) return (path + fileName);
}
return "";
}
#ifdef Q_OS_WIN32
typedef BOOL (__stdcall *AssocQueryStringAFunc)(DWORD, DWORD, const char *, const char *, char *, DWORD *);
QString W32_FileAssociation(QString ext)
{
if (ext == "") return "";
if (ext[0] != QChar('.')) ext = '.' + ext;
QString result = "";
QByteArray ba = ext.toLocal8Bit();
HMODULE mod = LoadLibraryA("shlwapi.dll");
AssocQueryStringAFunc assoc = (AssocQueryStringAFunc)(GetProcAddress(mod, "AssocQueryStringA"));
if (assoc) {
const DWORD ASSOCSTR_COMMAND = 1;
char buf[1024];
DWORD buflen = 1023;
if (assoc(0, ASSOCSTR_COMMAND, ba.data(), "open", &buf[0], &buflen) == S_OK) {
buf[buflen] = 0;
result = QString::fromLatin1(buf);
result.replace("%1", "?am" + ext);
//QMessageBox::information(0,result,result,0);
}
}
FreeLibrary(mod);
return result;
}
QStringList getProgramFilesPaths()
{
QStringList res;
QString a = getenv("PROGRAMFILES");
if (!a.isEmpty()) res << addPathDelimeter(a);
a = getenv("PROGRAMFILES(X86)");
if (!a.isEmpty()) res << addPathDelimeter(a);
if (a != "C:/Program Files" && QDir("C:/Program Files").exists()) res << "C:/Program Files/";
if (a != "C:/Program Files (x86)" && QDir("C:/Program Files (x86)").exists()) res << "C:/Program Files (x86)/";
if (a + " (x86)" != "C:/Program Files (x86)" && QDir(a + " (x86)").exists()) res << (a + " (x86)");
return res;
}
/*!
* \return the Uninstall string of the program from the registry
*
* Note: This won't get the path of 64bit installations when TXS running as a 32bit app due to wow6432 regristry redirection
* http://www.qtcentre.org/threads/36966-QSettings-on-64bit-Machine
* http://stackoverflow.com/questions/25392251/qsettings-registry-and-redirect-on-regedit-64bit-wow6432
* No workaround known, except falling back to the native Windows API. For the moment we'll rely on alternative detection methods.
*/
QString getUninstallString(const QString &program) {
foreach (const QString &baseKey, QStringList() << "HKEY_LOCAL_MACHINE" << "HKEY_CURRENT_USER") {
QSettings base(baseKey, QSettings::NativeFormat);
QString s = base.value("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + program + "\\UninstallString").toString();
if (!s.isEmpty())
return s;
}
return QString();
}
/*!
* \return an existing subdir of the from path\subDirFilter\subSubDir.
*
* Example:
* QStringList searchPaths = QStringList() << "C:\\" << "D:\\"
* findSubdir(searchPaths, "*miktex*", "miktex\\bin\\")
* will work for "C:\\MikTeX\\miktex\\bin\\" or "D:\\MikTeX 2.9\\miktex\\bin"
*/
QString findSubDir(const QStringList &searchPaths, const QString &subDirFilter, const QString &subSubDir) {
qDebug() << searchPaths;
foreach (const QString &path, searchPaths) {
foreach (const QString &dir, QDir(path).entryList(QStringList(subDirFilter), QDir::AllDirs, QDir::Time)) {
QDir fullPath(addPathDelimeter(path) + addPathDelimeter(dir) + subSubDir);
if (fullPath.exists())
return fullPath.absolutePath();
}
}
return QString();
}
/*!
* Returns the MikTeX bin path.
* This should not be called directly but only through getMiKTeXBinPath() to prevent multiple searches.
*/
QString getMiKTeXBinPathInternal()
{
// search the registry
QString mikPath = getUninstallString("MiKTeX 2.9");
// Note: this does currently not work for MikTeX 64bit because of registry redirection (also we would have to parse the
// uninstall string there for the directory). For the moment we'll fall back to other detection methods.
if (!mikPath.isEmpty() && QDir(addPathDelimeter(mikPath) + "miktex\\bin\\").exists()) {
mikPath = addPathDelimeter(mikPath) + "miktex\\bin\\";
}
// search the PATH
if (mikPath.isEmpty()) {
foreach (QString path, getEnvironmentPathList()) {
path = addPathDelimeter(path);
if ((path.endsWith("\\miktex\\bin\\x64\\") || path.endsWith("\\miktex\\bin\\")) && QDir(path).exists())
return path;
}
}
// search all program file paths
if (mikPath.isEmpty()) {
mikPath = QDir::toNativeSeparators(findSubDir(getProgramFilesPaths(), "*miktex*", "miktex\\bin\\"));
}
// search a fixed list of additional locations
if (mikPath.isEmpty()) {
static const QStringList candidates = QStringList() << "C:\\miktex\\miktex\\bin"
<< "C:\\tex\\texmf\\miktex\\bin"
<< "C:\\miktex\\bin"
<< QString(qgetenv("LOCALAPPDATA")) + "\\Programs\\MiKTeX 2.9\\miktex\\bin";
foreach (const QString &path, candidates)
if (QDir(path).exists()) {
mikPath = path;
break;
}
}
if(!mikPath.endsWith("\\")){
mikPath.append("\\");
}
// post-process to detect 64bit installation
if (!mikPath.isEmpty()) {
if (QDir(mikPath + "x64\\").exists())
return mikPath + "x64\\";
else
return mikPath;
}
return "";
}
static QString miktexBinPath = "<search>";
/*!
* \return the MikTeX bin path. This uses caching so that the search is only performed once per session.
*/
QString getMiKTeXBinPath()
{
if (miktexBinPath == "<search>") miktexBinPath = getMiKTeXBinPathInternal();
return miktexBinPath;
}
/*!
* Returns the TeXlive bin path.
* This should not be called directly but only through getTeXLiveWinBinPath() to prevent multiple searches.
*/
QString getTeXLiveWinBinPathInternal()
{
//check for uninstall entry
foreach (const QString &baseKey, QStringList() << "HKEY_CURRENT_USER" << "HKEY_LOCAL_MACHINE") {
QSettings reg(baseKey + "\\Software", QSettings::NativeFormat);
QString uninstall;
QDate date = QDate::currentDate();
for (int v = date.year(); v > 2008; v--) {
uninstall = reg.value(QString("microsoft/windows/currentversion/uninstall/TeXLive%1/UninstallString").arg(v), "").toString();
if (!uninstall.isEmpty()) {
int p = uninstall.indexOf("\\tlpkg\\", 0, Qt::CaseInsensitive);
QString path = p > 0 ? uninstall.left(p) : "";
if (QDir(path + "\\bin\\win32").exists())
return path + "\\bin\\win32\\";
}
}
}
//check for path
QString pdftex = BuildManager::findFileInPath("pdftex.exe");
int p = pdftex.indexOf("\\bin\\", 0, Qt::CaseInsensitive);
if (p <= 0) return "";
QString path = pdftex.left(p);
if (!QFileInfo(path + "\\release-texlive.txt").exists()) return "";
return path + "\\bin\\win32\\";
}
static QString texliveWinBinPath = "<search>";
/*!
* \return the TeXlive bin path on windows. This uses caching so that the search is only performed once per session.
*/
QString getTeXLiveWinBinPath()
{
if (texliveWinBinPath == "<search>") texliveWinBinPath = getTeXLiveWinBinPathInternal();
return texliveWinBinPath;
}
QString findGhostscriptDLL() //called dll, may also find an exe
{
//registry
foreach (QString program, QStringList() << "GPL Ghostscript" << "AFPL Ghostscript")
foreach(QString hkeyBase, QStringList() << "HKEY_CURRENT_USER" << "HKEY_LOCAL_MACHINE") {
QSettings reg(hkeyBase + "\\Software\\" + program, QSettings::NativeFormat);
QStringList version = reg.childGroups();
if (version.empty()) continue;
version.sort();
for (int i = version.size() - 1; i >= 0; i--) {
QString dll = reg.value(version[i] + "/GS_DLL", "").toString();
if (!dll.isEmpty()) return dll;
}
}
//environment
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
if (env.contains("GS_DLL")) {
return env.value("GS_DLL");
}
//file search
foreach (const QString &p, getProgramFilesPaths())
if (QDir(p + "gs").exists()) {
foreach (const QString &gsv, QDir(p + "gs").entryList(QStringList() << "gs*.*", QDir::Dirs, QDir::Time)) {
QString x = p + "gs/" + gsv + "/bin/gswin32c.exe";
if (QFile::exists(x)) return x;
}
}
return "";
}
#endif
QString searchBaseCommand(const QString &cmd, QString options, QString texPath)
{
foreach(QString command, cmd.split(";")) {
QString fileName = command + onWin_Nix(".exe","");
if (!options.startsWith(" ")) options = " " + options;
if (!texPath.isEmpty() && QFileInfo::exists(addPathDelimeter(texPath) + fileName)) {
return addPathDelimeter(texPath)+fileName+options; // found in texpath
}
if (!BuildManager::findFileInPath(fileName).isEmpty())
return fileName + options; //found in path
// additonal search path
QStringList addPaths=BuildManager::resolvePaths(BuildManager::additionalSearchPaths).split(";");
foreach(const QString& path, addPaths){
if (QFileInfo::exists(addPathDelimeter(path) + fileName)) {
return addPathDelimeter(path)+fileName+options; // found in texpath
}
}
//platform dependent mess
#ifdef Q_OS_WIN32
//Windows MikTex
QString mikPath = getMiKTeXBinPath();
if (!mikPath.isEmpty() && QFileInfo(mikPath + fileName).exists())
return "\"" + mikPath + fileName + "\" " + options; //found
//Windows TeX Live
QString livePath = getTeXLiveWinBinPath();
if (!livePath.isEmpty() && QFileInfo(livePath + fileName).exists())
return "\"" + livePath + fileName + "\" " + options; //found
#endif
#ifdef Q_OS_MAC
QStringList paths;
paths << "/usr/bin/texbin/" << "/usr/local/bin/" << "/usr/texbin/" << "/Library/TeX/texbin/" << "/Library/TeX/local/bin/" ;
paths << "/usr/local/teTeX/bin/i386-apple-darwin-current/" << "/usr/local/teTeX/bin/powerpc-apple-darwin-current/" << "/usr/local/teTeX/bin/x86_64-apple-darwin-current/";
QDate date = QDate::currentDate();
for (int i = date.year(); i > 2008; i--) {
//paths << QString("/usr/texbin MACTEX/TEXLIVE%1").arg(i); from texmaker comment
paths << QString("/usr/local/texlive/%1/bin/x86_64-darwin/").arg(i);
paths << QString("/usr/local/texlive/%1/bin/i386-darwin/").arg(i);
paths << QString("/usr/local/texlive/%1/bin/powerpc-darwin/").arg(i);
}
foreach (const QString &p, paths)
if (QFileInfo(p + fileName).exists()) {
if (cmd == "makeglossaries") {
// workaround: makeglossaries calls makeindex or xindy and therefore has to be run in an environment that has these commands on the path
return QString("sh -c \"PATH=$PATH:%1; %2%3\"").arg(p).arg(fileName).arg(options);
} else {
return p + fileName + options;
}
}
#endif
}
return "";
}
ExpandedCommands BuildManager::expandCommandLine(const QString &str, ExpandingOptions &options)
{
QRegExp re(QRegExp::escape(TXS_CMD_PREFIX) + "([^/ [{]+)(/?)((\\[[^\\]*]+\\]|\\{[^}]*\\})*) ?(.*)");
options.nestingDeep++;
if (options.canceled) return ExpandedCommands();
if (options.nestingDeep > maxExpandingNestingDeep) {
if (!UtilsUi::txsConfirmWarning(tr("The command has been expanded to %1 levels. Do you want to continue expanding \"%2\"?").arg(options.nestingDeep).arg(str))) {
options.canceled = true;
return ExpandedCommands();
}
}
ExpandedCommands res;
QStringList splitted = str.split("|");
foreach (const QString &split, splitted) { //todo: ignore | in strings
QString subcmd = split.trimmed();
if (!subcmd.startsWith(TXS_CMD_PREFIX)) {
RunCommandFlags flags = getSingleCommandFlags(subcmd);
if (options.override.removeAll)
subcmd = CommandInfo::getProgramName(subcmd);
if (!options.override.append.isEmpty())
subcmd += " " + options.override.append.join(" "); //todo: simplify spaces???
//Regexp matching parameters
//Unescaped: .*(-abc(=([^ ]*|"([^"]|\"([^"])*\")*"))?).*
//Doesn't support nesting deeper than \"
const QString parameterMatching = "(=([^ \"]+|\"([^\"]|\\\"([^\"])*\\\")*\"))?";
for (int i = 0; i < options.override.remove.size(); i++) {
const QString &rem = options.override.remove[i];
QRegularExpression removalRegex(" (-?" + QRegularExpression::escape(rem) + (rem.contains("=") ? "" : parameterMatching) + ")");
subcmd.replace(removalRegex, " ");
}
for (int i = 0; i < options.override.replace.size(); i++) {
const QString &rem = options.override.replace[i].first;
QRegExp replaceRegex(" (-?" + QRegExp::escape(rem) + parameterMatching + ")");
int pos = replaceRegex.indexIn(subcmd);
QString rep = " " + rem + options.override.replace[i].second;
if (pos < 0) subcmd.insert(CommandInfo::getProgramName(subcmd).length(), rep);
else {
subcmd.replace(pos, replaceRegex.matchedLength(), rep);
pos += rep.length();
int newpos;
while ( (newpos = replaceRegex.indexIn(subcmd, pos)) >= 0)
subcmd.replace(newpos, replaceRegex.matchedLength(), " ");
}
}
foreach (const QString &c, parseExtendedCommandLine(subcmd, options.mainFile, options.currentFile, options.currentLine)) {
CommandToRun temp(c);
temp.flags = flags;
res.commands << temp;
}
} else if (re.exactMatch(subcmd)) {
const QString &cmdName = re.cap(1);
const QString &slash = re.cap(2);
QString modifiers = re.cap(3);
QString parameters = re.cap(5);
if (slash != "/" && !modifiers.isEmpty()) {
UtilsUi::txsInformation(tr("You have used txs:///command[... or txs:///command{... modifiers, but we only support modifiers of the form txs:///command/[... or txs:///command/{... with an slash suffix to keep the syntax purer."));
modifiers.clear();
}
if (options.override.removeAll) {
parameters.clear();
modifiers.clear();