summaryrefslogtreecommitdiff
path: root/src/tikzit.cpp
blob: 856981747022eaa59a3b15eaea956a78811f0c65 (plain)
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
/*
    TikZiT - a GUI diagram editor for TikZ
    Copyright (C) 2018 Aleks Kissinger

    This program 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 3 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, see <https://www.gnu.org/licenses/>.
*/

#include "tikzit.h"
#include "tikzassembler.h"
#include "tikzstyles.h"
#include "previewwindow.h"
#include "latexprocess.h"

#include <QFile>
#include <QFileDialog>
#include <QSettings>
#include <QDebug>
#include <QMessageBox>
#include <QRegularExpression>
#include <QVersionNumber>
#include <QNetworkAccessManager>
#include <QColorDialog>

// application-level instance of Tikzit
Tikzit *tikzit;

// font to use for node labels
QFont Tikzit::LABEL_FONT("Courrier", 9);

Tikzit::Tikzit() : _styleFile("[no styles]"), _activeWindow(nullptr)
{
}

void Tikzit::init()
{
    QSettings settings("tikzit", "tikzit");

	initColors();

    _mainMenu = new MainMenu();
    QMainWindow *dummy = new QMainWindow();

    _toolPalette = new ToolPalette(dummy);
    _propertyPalette = new PropertyPalette(dummy);
    //_stylePalette = new StylePalette(dummy);
    _styles = new TikzStyles(this);

    _styleEditor = new StyleEditor();

    //_stylePalette->show();
    _windows << new MainWindow();
    _windows[0]->show();

    _styleFile = "";
    _styleFilePath = "";
    QString styleFile = settings.value("previous-tikzstyles-file").toString();
    if (!styleFile.isEmpty()) loadStyles(styleFile);

    QVariant check = settings.value("check-for-updates");
    if (check.isNull()) {
        int resp = QMessageBox::question(nullptr,
          tr("Check for updates"),
          tr("Would you like TikZiT to check for updates automatically?"
             " (You can always change this later in the Help menu.)"),
          QMessageBox::Yes | QMessageBox::Default,
          QMessageBox::No,
          QMessageBox::NoButton);
        check.setValue(resp == QMessageBox::Yes);
    }

    setCheckForUpdates(check.toBool());

    if (check.toBool()) {
        checkForUpdates(false);
    }

    _preview = new PreviewWindow();
    _latex = nullptr;
}

//QMenuBar *Tikzit::mainMenu() const
//{
//    return _mainMenu;
//}

QColor Tikzit::colorByIndex(int i)
{
    return _cols[i];
}

QColor Tikzit::colorByName(QString name)
{
    for (int i = 0; i < _colNames.length(); ++i) {
        if (_colNames[i] == name) return _cols[i];
    }

    QRegExp re(
      "rgb\\s*,\\s*255\\s*:\\s*"
      "red\\s*,\\s*([0-9]+)\\s*;\\s*"
      "green\\s*,\\s*([0-9]+)\\s*;\\s*"
      "blue\\s*,\\s*([0-9]+)\\s*"
    );

    if (re.exactMatch(name)) {
        QStringList cap = re.capturedTexts();
        //qDebug() << cap;
        return QColor(
                cap[1].toInt(),
                cap[2].toInt(),
                cap[3].toInt());
    }

    return QColor();
}

QString Tikzit::nameForColor(QColor col)
{
    for (int i = 0; i < _colNames.length(); ++i) {
        if (_cols[i] == col) return _colNames[i];
    }

    // if the color is not recognised, return it in tikz-readable RBG format
    return "rgb,255: red,"+ QString::number(col.red()) +
            "; green," + QString::number(col.green()) +
            "; blue," + QString::number(col.blue());
}

void Tikzit::newTikzStyles()
{
    QSettings settings("tikzit", "tikzit");
    QFileDialog dialog;
    dialog.setDefaultSuffix("tikzstyles");
    dialog.setWindowTitle(tr("Create TikZ Style File"));
    dialog.setAcceptMode(QFileDialog::AcceptSave);
    dialog.setLabelText(QFileDialog::Accept, "Create");
    dialog.setNameFilter(tr("TiKZ Style File (*.tikzstyles)"));
    dialog.setFileMode(QFileDialog::AnyFile);
    dialog.setDirectory(settings.value("previous-file-path").toString());
    dialog.setOption(QFileDialog::DontUseNativeDialog);

    if (dialog.exec() && !dialog.selectedFiles().isEmpty()) {
        QString fileName = dialog.selectedFiles()[0];
        TikzStyles *st = new TikzStyles(this);

        if (st->saveStyles(fileName)) {
            QFileInfo fi(fileName);
            _styleFile = fi.fileName();
            _styleFilePath = fi.absoluteFilePath();
            settings.setValue("previous-tikzstyles-file", fileName);
            settings.setValue("previous-tikzstyles-path", fi.absolutePath());
            _styles->deleteLater();
            _styles = st;

            foreach (MainWindow *w, _windows) {
                w->tikzScene()->reloadStyles();
            }
        } else {
            QMessageBox::warning(nullptr,
                "Could not write to style file.",
                "Could not write to: '" + fileName + "'. Check file permissions or choose a new location.");
        }
    }
}

ToolPalette *Tikzit::toolPalette() const
{
    return _toolPalette;
}

PropertyPalette *Tikzit::propertyPalette() const
{
    return _propertyPalette;
}

void Tikzit::newDoc()
{
    MainWindow *w = new MainWindow();
    w->show();
    _windows << w;
}

MainWindow *Tikzit::activeWindow() const
{
    return _activeWindow;
}

void Tikzit::setActiveWindow(MainWindow *activeWindow)
{
    _activeWindow = activeWindow;
}

void Tikzit::removeWindow(MainWindow *w)
{
    _windows.removeAll(w);
    if (_activeWindow == w) {
        if (_windows.isEmpty()) {
            _activeWindow = nullptr;
            // TODO: check if we should quit when last window closed
            quit();
        } else _activeWindow = _windows[0];
    }
}

void Tikzit::open()
{
    QSettings settings("tikzit", "tikzit");
    QString fileName = QFileDialog::getOpenFileName(nullptr,
                tr("Open File"),
                settings.value("previous-file-path").toString(),
                tr("TiKZ Files (*.tikz)"),
                nullptr,
                QFileDialog::DontUseNativeDialog);

	open(fileName);
}

void Tikzit::open(QString fileName)
{
	if (!fileName.isEmpty()) {
		if (_windows.size() == 1 &&
			_windows[0]->tikzDocument()->isClean() &&
            _windows[0]->tikzDocument()->shortName().isEmpty())
        {
			_windows[0]->open(fileName);
			_windows[0]->show();
        }
        else
        {
            bool found = false;
            foreach (MainWindow *w, _windows) {
                if (w->tikzDocument()->fileName() == fileName) {
                    w->raise();
                    w->activateWindow();
                    found = true;
                }
            }

            if (!found) {
                MainWindow *w = new MainWindow();
                _windows << w;
                w->show();
                w->open(fileName);
            }
		}
	}
}

void Tikzit::openTikzStyles() {
    QSettings settings("tikzit", "tikzit");
    QString fileName = QFileDialog::getOpenFileName(nullptr,
                tr("Open File"),
                settings.value("previous-tikzstyles-path").toString(),
                tr("TiKZ Style Files (*.tikzstyles)"),
                nullptr,
                QFileDialog::DontUseNativeDialog);

    if (!fileName.isEmpty()) {
        QFileInfo fi(fileName);
        if (fi.exists() && loadStyles(fileName)) {
            QSettings settings("tikzit", "tikzit");
            settings.setValue("previous-tikzstyles-path", fi.absolutePath());
            settings.setValue("previous-tikzstyles-file", fileName);
        }
    }
}

bool Tikzit::loadStyles(QString fileName)
{
    QFileInfo fi(fileName);
    if (fi.exists()) {
        TikzStyles *st = new TikzStyles(this);
        if (st->loadStyles(fileName)) {
            _styleFile = fi.fileName();
            _styleFilePath = fi.absoluteFilePath();
            _styles->deleteLater();
            _styles = st;

            foreach (MainWindow *w, _windows) {
                w->tikzScene()->reloadStyles();
            }
            return true;
        } else {
            QMessageBox::warning(nullptr,
                "Bad style file.",
                "Bad style file: '" + fileName + "'. Check the file is properly formatted and try to load it again.");
            return false;
        }

    } else {
        //settings.setValue("previous-tikzstyles-file", "");
        QMessageBox::warning(nullptr,
            "Style file not found.", "Could not open style file: '" + fileName + "'.");
        return false;
    }
}

void Tikzit::showStyleEditor()
{
    _styleEditor->open();
}

QString Tikzit::styleFile() const
{
    return _styleFile;
}

QString Tikzit::styleFilePath() const
{
    return _styleFilePath;
}

void Tikzit::updateRecentFiles()
{
    foreach (MainWindow *w, _windows) {
        w->menu()->updateRecentFiles();
    }
}

void Tikzit::clearRecentFiles()
{
    QSettings settings("tikzit", "tikzit");
    settings.setValue("recent-files", QStringList());
    updateRecentFiles();
}

void Tikzit::setCheckForUpdates(bool check)
{
    QSettings settings("tikzit", "tikzit");
    settings.setValue("check-for-updates", check);
    foreach (MainWindow *w, _windows) {
        w->menu()->updatesAction()->blockSignals(true);
        w->menu()->updatesAction()->setChecked(check);
        w->menu()->updatesAction()->blockSignals(false);
    }
}

void Tikzit::checkForUpdates(bool manual)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    if (manual) {
        connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(updateManual(QNetworkReply*)));
    } else {
        connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(updateAuto(QNetworkReply*)));
    }

    manager->get(QNetworkRequest(QUrl("https://tikzit.github.io/latest-version.txt")));
}

void Tikzit::updateAuto(QNetworkReply *reply)
{
    updateReply(reply, false);
}

void Tikzit::updateManual(QNetworkReply *reply)
{
    updateReply(reply, true);
}

void Tikzit::updateReply(QNetworkReply *reply, bool manual)
{
    if (!reply->isReadable()) return;

    QByteArray data = reply->read(200);
    QString strLatest = QString::fromUtf8(data).simplified();

    // check for valid version string and capture optional RC suffix
    QRegularExpression re("^[1-9]+(\\.[0-9]+)*(-[rR][cC]([0-9]+))?$");
    QRegularExpressionMatch m;
    m = re.match(TIKZIT_VERSION);

    // any non-RC versions are considered later than RC versions.
    int rcCurrent = (!m.captured(3).isEmpty()) ? m.captured(3).toInt() : 1000;

    m = re.match(strLatest);

    if (m.hasMatch()) {
        QVersionNumber current = QVersionNumber::fromString(TIKZIT_VERSION).normalized();
        QVersionNumber latest = QVersionNumber::fromString(strLatest).normalized();

        int rcLatest = (!m.captured(3).isEmpty()) ? m.captured(3).toInt() : 1000;

        if (latest > current || (latest == current && rcLatest > rcCurrent)) {
            // give the version string in standard format
            strLatest = QString::number(latest.majorVersion()) + "." +
                QString::number(latest.minorVersion()) + "." +
                QString::number(latest.microVersion());
            if (rcLatest != 1000) strLatest += "-rc" + QString::number(rcLatest);
            QMessageBox::information(nullptr,
              tr("Update available"),
              "<p><b>A new version of TikZiT is available!</b></p>"
              "<p><i>current version: " TIKZIT_VERSION "<br />"
              "latest version: " + strLatest + "</i></p>"
              "<p>Download it now from: "
              "<a href=\"https://tikzit.github.io\">tikzit.github.io</a>.</p>");
        }
    } else {
        // don't complain of invalid response for auto update check
        if (manual) {
            QMessageBox::warning(nullptr,
              tr("Invalid response"),
              "<p>Got invalid version response from "
              "<a href=\"https://tikzit.github.io\">tikzit.github.io</a>.</p>");
        }
    }
}

void Tikzit::makePreview()
{
    if (activeWindow()) {
        LatexProcess *oldProc = _latex;
        _latex = new LatexProcess(_preview, this);
        if (oldProc != nullptr) {
            oldProc->kill();
            oldProc->deleteLater();
        }

        connect(_latex, SIGNAL(previewFinished()), this, SLOT(cleanupLatex()));

        if (activeWindow()->tikzDocument()->isEmpty()) {
            _latex->makePreview("\\begin{tikzpicture}\n"
                                "  \\node [style=none] (0) at (0,0) {};\n"
                                "\\end{tikzpicture}\n");
        } else {
            _latex->makePreview(activeWindow()->tikzSource());
        }
        _preview->show();
        _preview->raise();
    }
}

void Tikzit::cleanupLatex()
{
    LatexProcess *oldProc = _latex;
    _latex = nullptr;
    if (oldProc != nullptr) {
        oldProc->deleteLater();
    }
}

void Tikzit::initColors()
{
    // 19 standard xcolor colours
    _colNames <<
		"black" <<
        "darkgray" <<
        "gray" <<
		"lightgray" <<
		"white" <<

		"red" <<
		"orange" <<
		"yellow" <<
        "green" <<
		"blue" <<
		"purple" <<

		"brown" <<
		"olive" <<
        "lime" <<
        "cyan" <<
        "teal" <<

		"magenta" <<
		"violet" <<
		"pink";

    _cols <<
        QColor::fromRgbF(0,0,0) <<
        QColor::fromRgbF(0.25,0.25,0.25) <<
        QColor::fromRgbF(0.5,0.5,0.5) <<
        QColor::fromRgbF(0.75,0.75,0.75) <<
        QColor::fromRgbF(1,1,1) <<

        QColor::fromRgbF(1,0,0) <<
        QColor::fromRgbF(1,0.5,0) <<
        QColor::fromRgbF(1,1,0) <<
        QColor::fromRgbF(0,1,0) <<
        QColor::fromRgbF(0,0,1) <<
        QColor::fromRgbF(0.75,0,0.25) <<

        QColor::fromRgbF(0.75,0.5,0.25) <<
        QColor::fromRgbF(0.5,0.5,0) <<
        QColor::fromRgbF(0.75,1,0) <<
        QColor::fromRgbF(0,1,1) <<
        QColor::fromRgbF(0,0.5,0.5) <<

        QColor::fromRgbF(1,0,1) <<
        QColor::fromRgbF(0.5,0,0.5) <<
        QColor::fromRgbF(1,0.75,0.75);

    for (int i = 0; i < 48; ++i) {
        QColorDialog::setStandardColor(i, QColor(Qt::white));
    }

    // grayscale in column 1
    int pos = 0;
    for (int i=0; i < 5; ++i) {
        QColorDialog::setStandardColor(pos, _cols[i]);
        pos += 1;
    }

    // rainbow in column 2
    pos = 6;
    for (int i=5; i < 11; ++i) {
        QColorDialog::setStandardColor(pos, _cols[i]);
        pos += 1;
    }

    // brown/green/teal spectrum in column 3
    pos = 12;
    for (int i=11; i < 16; ++i) {
        QColorDialog::setStandardColor(pos, _cols[i]);
        pos += 1;
    }

    // pinks in column 4
    pos = 18;
    for (int i=16; i < 19; ++i) {
        QColorDialog::setStandardColor(pos, _cols[i]);
        pos += 1;
    }
}

PreviewWindow *Tikzit::previewWindow() const
{
    return _preview;
}

//StylePalette *Tikzit::stylePalette() const
//{
//    return _stylePalette;
//}


TikzStyles *Tikzit::styles() const
{
    return _styles;
}

void Tikzit::quit()
{
    //_stylePalette->close();
    QApplication::quit();
}