aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/cli/main.cpp
blob: efc7890abd65f47d2a09bd6c8451ec07dd4a124b (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
/***************************************************************************
* 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 <QGuiApplication>

#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);
bool markdown = false;
enum EXPORTFORMAT {TERMINAL, SVG, IMAGE, MARKDOWN, JSON, BOT};
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(' ');
    }
}

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);
}
void displayJSon(QString scalarText, QString resultStr,QJsonArray array, bool withColor, QString cmd, QString error, 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["command"]=cmd;
    doc.setObject(obj);
    out << doc.toJson() << "\n";
}
void displayMarkdown(QString scalarText, QString resultStr,QJsonArray array, bool withColor, QString cmd, QString error, 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(!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 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
    {
        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 comment, bool allSameFaceCount,bool allSameColor)
{
    if(!error.isEmpty())
    {
        out << "Error" << error << "\n";
        return;
    }
    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)
{
    DiceParser parser;
    parser.insertAlias(new DiceAlias("L5R5R",QStringLiteral("L[-,⨀,⨀⬢,❂⬢,❁,❁⬢]")),0);
    parser.insertAlias(new DiceAlias("L5R5S",QStringLiteral("L[-,-,⨀,⨀,⨀❁,⨀⬢,⨀⬢,❂,❂⬢,❁,❁,❁]")),1);
    int rt=0;
    for(QString cmd : cmds)
    {
        if(parser.parseLine(cmd))
        {
            parser.start();
            QList<ExportedDiceResult> list;
            bool homogeneous = true;
            parser.getLastDiceResult(list,homogeneous);
            bool allSameFaceCount, allSameColor;
            auto array =  DisplayToolBox::diceToJson(list,allSameFaceCount,allSameColor);
            QString resultStr;
            QString scalarText;
            QString comment = parser.getComment();
            QString error = parser.humanReadableError();

            if(parser.hasIntegerResultNotInFirst())
            {
                auto values = parser.getLastIntegerResults();
                QStringList strLst;
                for(auto val : values )
                {
                    strLst << QString::number(val);
                }
                scalarText = QString("%1").arg(strLst.join(','));
            }
            else if(!list.isEmpty())
            {
                auto values = parser.getSumOfDiceResult();
                QStringList strLst;
                for(auto val : values )
                {
                    strLst << QString::number(val);
                }
                scalarText = QString("%1").arg(strLst.join(','));
            }

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

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

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

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

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

    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();

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