aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/cli/main.cpp
blob: 0f984c1d29f0757a9f83b765ec8ef1e9ed95fbb6 (plain) (blame)
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
/***************************************************************************
* Copyright (C) 2014 by Renaud Guezennec                                   *
* http://www.rolisteam.org/contact                      *
*                                                                          *
*  This file is part of DiceParser                                         *
*                                                                          *
* DiceParser is free software; you can redistribute it and/or modify       *
* it under the terms of the GNU General Public License as published by     *
* the Free Software Foundation; either version 2 of the License, or        *
* (at your option) any later version.                                      *
*                                                                          *
* This program is distributed in the hope that it will be useful,          *
* but WITHOUT ANY WARRANTY; without even the implied warranty of           *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the             *
* GNU General Public License for more details.                             *
*                                                                          *
* You should have received a copy of the GNU General Public License        *
* along with this program; if not, write to the                            *
* Free Software Foundation, Inc.,                                          *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.                 *
***************************************************************************/

#include <QStringList>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QTextStream>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QFile>

#ifdef PAINTER_OP
#include <QGuiApplication>
#else
#include <QCoreApplication>
#endif

#include "displaytoolbox.h"
#include "diceparser.h"
#include "highlightdice.h"

/**
 * @page Dice
 * The cli for DiceParser the new dice system from rolisteam.
 * @section Build and install
 * To build this program, type these command:
 * - mkdir build
 * - cd build
 * - cmake ../
 * - make
 * - make install
 * @return
 */

QTextStream out(stdout, QIODevice::WriteOnly);
QTextStream err(stderr, QIODevice::WriteOnly);
bool markdown = false;
#ifdef PAINTER_OP
enum EXPORTFORMAT {TERMINAL, SVG, IMAGE, MARKDOWN, JSON, BOT};
#else
enum EXPORTFORMAT {TERMINAL, SVG, MARKDOWN, JSON, BOT};
#endif
int returnValue = 0;


QString diceToMarkdown(QJsonArray array,bool withColor,bool allSameColor,bool allSameFaceCount )
{
    if(allSameFaceCount)
    {
        QStringList result;
        for(auto item : array)
        {
            auto obj = item.toObject();
            auto values= obj["values"].toArray();
            for(auto val : values)
            {
                result.append(val.toString());
            }
        }
        return result.join(',');
    }
    else
    {
        QStringList result;
        for(auto item : array)
        {
            QStringList subResult;
            auto obj = item.toObject();
            auto values= obj["values"].toArray();
            for(auto val : values)
            {
                subResult.append(val.toString());
            }
            result.append(QStringLiteral("d%1:(").arg(obj["face"].toString()));
            result.append(subResult.join(','));
            result.append(QStringLiteral(")"));

        }
        return result.join(' ');
    }
}
#ifdef PAINTER_OP
void displayImage(QString scalarText, QString resultStr,QJsonArray array, bool withColor, QString cmd, QString comment, bool allSameFaceCount,bool allSameColor)
{
    out << DisplayToolBox::makeImage( scalarText,  resultStr, array,  withColor,  cmd,  comment,  allSameFaceCount, allSameColor);
}
#endif
void displayJSon(QString scalarText, QString resultStr,QJsonArray array, bool withColor, QString cmd, QString error, QString warning, QString comment, bool allSameFaceCount,bool allSameColor)
{
    Q_UNUSED(withColor);
    QJsonDocument doc;
    QJsonObject obj;
    obj["values"]=array;
    obj["comment"]=comment;
    obj["error"]=error;
    obj["scalar"]=scalarText;
    obj["string"]=resultStr;
    obj["allSameFace"]=allSameFaceCount;
    obj["allSameColor"]=allSameColor;
    obj["warning"]=warning;
    obj["command"]=cmd;
    doc.setObject(obj);
    out << doc.toJson() << "\n";
}
void displayMarkdown(QString scalarText, QString resultStr,QJsonArray array, bool withColor, QString cmd, QString error, QString warning, QString comment, bool allSameFaceCount,bool allSameColor)
{
    Q_UNUSED(withColor);
    QString str("```Markdown\n");
    if(!error.isEmpty())
    {
        str.append(QStringLiteral("Error: %1\n").arg(error));
    }
    else
    {
        if(!warning.isEmpty())
            str.append(QStringLiteral("Warning: %1\n").arg(warning));

        if(!comment.isEmpty())
        {
            str.prepend(QStringLiteral("%1\n").arg(comment));
        }
        auto diceList = DisplayToolBox::diceToText(array,false,allSameFaceCount,allSameColor);
        if(resultStr.isEmpty())
        {
           str.append(QStringLiteral("# %1\nDetails:[%3 (%2)]\n").arg(scalarText).arg(diceList).arg(cmd));
        }
        else if(!resultStr.isEmpty())
        {
            resultStr.replace("%2",diceList.trimmed());
            str.append(QStringLiteral("%1\n").arg(resultStr));
        }
    }
    str.append(QStringLiteral("```"));
    out << str;
}
void displaySVG(QString scalarText, QString resultStr,QJsonArray array, bool withColor, QString cmd, QString error, QString warning, QString comment, bool allSameFaceCount,bool allSameColor)
{
    QString str("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg version=\"1.1\"  xmlns=\"http://www.w3.org/2000/svg\" "
                                  "xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n");
    if(!error.isEmpty())
    {
        str.append(QStringLiteral("<text font-size=\"16\" x=\"0\" y=\"20\"><tspan fill=\"red\">%1</tspan></text>").arg(error));
    }
    else
    {
        if(!warning.isEmpty())
            str.append(QStringLiteral("<text font-size=\"16\" x=\"0\" y=\"20\"><tspan fill=\"orange\">%1</tspan></text>").arg(warning));

        int y = 20;
        if(!comment.isEmpty())
        {
            str.append(QStringLiteral("<text font-size=\"16\" x=\"0\" y=\"%2\"><tspan fill=\"blue\">%1</tspan></text>").arg(comment).arg(y));
            y+=20;
        }
        auto diceList = DisplayToolBox::diceToSvg(array,withColor,allSameColor,allSameFaceCount);
        if(resultStr.isEmpty())
        {
            if(withColor)
                str.append(QStringLiteral("<text font-size=\"16\" x=\"0\" y=\"%4\"><tspan fill=\"red\">%1</tspan> details:[%3 (%2)]</text>").arg(scalarText).arg(diceList).arg(cmd).arg(y));
            else
                str.append(QStringLiteral("<text font-size=\"16\" x=\"0\" y=\"%4\"><tspan>%1</tspan> details:[%3 (%2)]</text>").arg(scalarText).arg(diceList).arg(cmd).arg(y));
        }
        else if(!resultStr.isEmpty())
        {
            resultStr.replace("%2",diceList.trimmed());
            str.append(QStringLiteral("<text font-size=\"16\" x=\"0\" y=\"%2\">%1</text>").arg(resultStr).arg(y));
        }
    }
    str.append(QStringLiteral("</svg>\n"));
    out << str << "\n";
}

void displayCommandResult(QString scalarText, QString resultStr,QJsonArray array, bool withColor, QString cmd, QString error, QString warning, QString comment, bool allSameFaceCount,bool allSameColor)
{
    // TODO display warning
    if(!error.isEmpty())
    {
        err << "Error" << error << "\n";
        return;
    }

    if(!warning.isEmpty())
        err << "Warning: "<< warning << "\n";

    QString str;

    auto diceList = DisplayToolBox::diceToText(array,withColor,allSameFaceCount,allSameColor);

    if(withColor)
        str = QString("Result: \e[0;31m%1\e[0m - details:[%3 (%2)]").arg(scalarText).arg(diceList).arg(cmd);
    else
        str = QString("Result: %1 - details:[%3 (%2)]").arg(scalarText).arg(diceList).arg(cmd);

    if(!resultStr.isEmpty())
    {
        resultStr.replace("%2",diceList.trimmed());
        str = resultStr;
    }

    if(!comment.isEmpty())
    {
        out << "\033[1m" << comment << "\033[0m\n";
    }
    out << str << "\n";
}

int startDiceParsing(QStringList& cmds,QString& treeFile,bool withColor, EXPORTFORMAT format, QJsonArray array)
{
    DiceParser parser;
    parser.insertAlias(new DiceAlias("L5R5R",QStringLiteral("L[-,⨀,⨀⬢,❂⬢,❁,❁⬢]")),0);
    parser.insertAlias(new DiceAlias("L5R5S",QStringLiteral("L[-,-,⨀,⨀,⨀❁,⨀⬢,⨀⬢,❂,❂⬢,❁,❁,❁]")),1);
    int i = 2;
    for(auto alias : array)
    {
        auto objAlias = alias.toObject();
        auto dice = new DiceAlias(objAlias["pattern"].toString(),objAlias["cmd"].toString(),!objAlias["regexp"].toBool());
        dice->setComment(objAlias["comment"].toString());
        parser.insertAlias(dice,i++);
    }

    int rt=0;
    for(QString cmd : cmds)
    {
        if(parser.parseLine(cmd))
        {
            parser.start();
            QList<ExportedDiceResult> list;
            QList<ExportedDiceResult> listFull;
            bool homogeneous = true;
            parser.getLastDiceResult(list,homogeneous);
            parser.getDiceResultFromAllInstruction(listFull);
            bool allSameFaceCount, allSameColor;
            auto array =  DisplayToolBox::diceToJson(list,allSameFaceCount,allSameColor);
            QString resultStr;
            QString scalarText;
            QString lastScalarText;
            QString comment = parser.getComment();
            QString error = parser.humanReadableError();
            QString warnings = parser.humanReadableWarning();
            QStringList strLst;
            QStringList listOfDiceResult;

            if(parser.hasIntegerResultNotInFirst())
            {
                auto values = parser.getLastIntegerResults();
                for(auto val : values )
                {
                    strLst << QString::number(val);
                }
                scalarText = QString("%1").arg(strLst.join(','));
                lastScalarText = strLst.last();
            }
            else if(!list.isEmpty())
            {
                auto values = parser.getSumOfDiceResult();
                for(auto val : values )
                {
                    strLst << QString::number(val);
                }
                scalarText = QString("%1").arg(strLst.join(','));
            }
            if(!list.isEmpty())
            {
                for(auto map : list)
                {
                    for(auto key : map.keys())
                    {
                        auto dice = map[key];
                        QString stringVal;
                        for(auto val : dice)
                        {
                            qint64 total=0;
                            QStringList dicelist;
                            for(auto score: val.getResult())
                            {
                                  total += score;
                                  dicelist << QString::number(score);
                            }
                            if(val.getResult().size() > 1)
                            {
                                stringVal=QString("%1 [%2]").arg(total).arg(dicelist.join(','));
                                listOfDiceResult << stringVal;
                            }
                            else 
                            {
                                listOfDiceResult << QString::number(total);
                            }
                        }
                    }
                }
            }

            if(parser.hasStringResult())
            {
                bool ok;
                QStringList allStringlist = parser.getAllStringResult(ok);
                QString stringResult = allStringlist.join(" ; ");
                stringResult.replace("%1",scalarText);
                stringResult.replace("%2",listOfDiceResult.join(",").trimmed());
                stringResult.replace("%3",lastScalarText);

                int i = strLst.size();
                for(auto it = strLst.rbegin(); it != strLst.rend() ; ++it)
                {
                    stringResult.replace(QStringLiteral("$%1").arg(i),(*it));
                    --i;
                }
                i = listFull.size();
                for(auto it = strLst.rbegin(); it != strLst.rend() ; ++it)
                {
                    stringResult.replace(QStringLiteral("µ%1").arg(i),(*it));
                    --i;
                }

                resultStr = stringResult;
            }
            if(format == BOT)
            {
                if(allSameColor)
                {
                    format = MARKDOWN;
                }
                else
                {
                    #ifdef PAINTER_OP
                    format = IMAGE;
                    #else
                    format = MARKDOWN;
                    #endif
                }
                if(!error.isEmpty())
                {
                    format = MARKDOWN;
                }
            }

            switch(format)
            {
                case TERMINAL:
                    displayCommandResult(scalarText, resultStr, array, withColor, cmd, error,warnings, comment, allSameFaceCount, allSameColor);
                break;
                case SVG:
                    displaySVG(scalarText, resultStr, array, withColor, cmd, error,warnings, comment, allSameFaceCount, allSameColor);
                break;
                case BOT:
                case MARKDOWN:
                    displayMarkdown(scalarText, resultStr, array, withColor, cmd, error,warnings, comment, allSameFaceCount, allSameColor);
                break;
                case JSON:
                    displayJSon(scalarText, resultStr, array, withColor, cmd, error,warnings, comment, allSameFaceCount, allSameColor);
                break;
                #ifdef PAINTER_OP
                case IMAGE:
                    displayImage(scalarText, resultStr, array, withColor, cmd, comment, allSameFaceCount, allSameColor);
                break;
                #endif
            }
            if(!treeFile.isEmpty())
            {
                parser.writeDownDotTree(treeFile);
            }

            if(!error.isEmpty())
            {
                rt = 1;
            }
        }
        else
        {
            rt = 1;
        }
    }

    return rt;
}
#include <QTextCodec>
int main(int argc, char *argv[])
{
#ifdef PAINTER_OP
    QGuiApplication a(argc, argv);
#else
    QCoreApplication a(argc, argv);
#endif

    QStringList commands;
    QString cmd;
    QString dotFileStr;
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    bool colorb=true;
    out.setCodec("UTF-8");
    EXPORTFORMAT format = TERMINAL;

    QCommandLineParser optionParser;
    QCommandLineOption color(QStringList() << "c"<< "color-off", "Disable color to highlight result");
    QCommandLineOption version(QStringList() << "v"<< "version", "Show the version and quit.");
    QCommandLineOption reset(QStringList() << "reset-settings", "Erase the settings and use the default parameters");
    QCommandLineOption alias(QStringList() << "a" << "alias", "path to alias json files: <aliasfile>","aliasfile");
    QCommandLineOption character(QStringList() << "s" << "charactersheet", "set Parameters to simulate character sheet: <sheetfile>","sheetfile");
    QCommandLineOption markdown(QStringList() << "m" <<"markdown", "The output is formatted in markdown.");
    QCommandLineOption bot(QStringList() << "b" <<"bot", "Discord bot.");
    QCommandLineOption svg(QStringList() << "g" <<"svg", "The output is formatted in svg.");
    QCommandLineOption json(QStringList() << "j" <<"json", "The output is formatted in json.");
    QCommandLineOption dotFile(QStringList() << "d"<<"dot-file", "Instead of rolling dice, generate the execution tree and write it in <dotfile>","dotfile");
    QCommandLineOption translation(QStringList() << "t"<<"translation", "path to the translation file: <translationfile>","translationfile");
    QCommandLineOption help(QStringList() << "h"<<"help", "Display this help");

    optionParser.addOption(color);
    optionParser.addOption(version);
    optionParser.addOption(reset);
    optionParser.addOption(dotFile);
    optionParser.addOption(alias);
    optionParser.addOption(character);
    optionParser.addOption(markdown);
    optionParser.addOption(bot);
    optionParser.addOption(svg);
    optionParser.addOption(json);
    optionParser.addOption(translation);
    optionParser.addOption(help);
    for(int i=0;i<argc;++i)
    {
        commands << QString::fromUtf8(argv[i]);
    }

    optionParser.process(commands);

    if(optionParser.isSet(color))
    {
        commands.removeAt(0);
        colorb = false;
    }
    else if(optionParser.isSet(version))
    {
        out << "Rolisteam DiceParser v1.0.0"<< "\n";
        out << "More Details: www.rolisteam.org"<< "\n";
        return 0;
    }
    else if(optionParser.isSet(reset))
    {
        return 0;
    }
    else if(optionParser.isSet(dotFile))
    {
        dotFileStr = optionParser.value(dotFile);
    }
    if(optionParser.isSet(markdown))
    {
        format= MARKDOWN;
    }
    else if(optionParser.isSet(bot))
    {
        format = BOT;
    }
    else if(optionParser.isSet(svg))
    {
        format = SVG;
    }
    else if(optionParser.isSet(json))
    {
        format = JSON;
    }
    if(optionParser.isSet(help))
    {
        cmd = "help";
    }
    QStringList cmdList = optionParser.positionalArguments();
   // cmdList << "8d10;\$1c[>6];\$1c[=1];\$2-\$3i:[>0]{\"%3 Success[%2]\"}{i:[<0]{\"Critical fail %3 [%2]\"}{\"Fail %3 [%2]\"}}";
    QString aliasstr;
    QJsonArray aliases;
    if(optionParser.isSet(alias))
    {
        aliasstr = optionParser.value(alias);

        QFile file(aliasstr);
    
        if(file.open(QIODevice::ReadOnly))
        {
            QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
            aliases = doc.array();
        }

    }

    returnValue = startDiceParsing(cmdList,dotFileStr,colorb,format,aliases);
    if(optionParser.isSet(help))
    {
        out << optionParser.helpText();
    }
    return returnValue;
}