mainwindow.cpp 27.7 KB
Newer Older
jhammen's avatar
jhammen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * This file is part of Bipscript-IDE.
 *
 * Bipscript-IDE 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.
 *
 * Bipscript-IDE 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 Bipscript-IDE.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "mainwindow.h"

#include "editorwidget.h"
#include "projectsdialog.h"
21
22
#include "scriptrun.h"
#include "ui_mainwindow.h"
jhammen's avatar
jhammen committed
23
24
25
#include "version.h"

#include <QDebug>
26
27
#include <QDesktopServices>
#include <QDir>
jhammen's avatar
jhammen committed
28
29
30
#include <QFileDialog>
#include <QInputDialog>
#include <QLabel>
31
#include <QTime>
jhammen's avatar
jhammen committed
32

33
MainWindow::MainWindow(QWidget *parent)
34
35
36
    : QMainWindow(parent), projectList(ProjectList::instance()),
      audioEngine(AudioEngine::instance()), transportPosition(0), ui(new Ui::MainWindow),
      timeWidget(this), bbtWidget(this) {
jhammen's avatar
jhammen committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    ui->setupUi(this);

    // time in MM:SS + BBT + engine config
    QString labelStyle("QLabel {font-family: monospace; color: green }");
    timeWidget.setFrameStyle(QFrame::Panel | QFrame::Sunken);
    timeWidget.setStyleSheet(labelStyle);
    timeWidget.setText("00:00.000");
    ui->transportToolBar->addWidget(&timeWidget);
    bbtWidget.setFrameStyle(QFrame::Panel | QFrame::Sunken);
    bbtWidget.setStyleSheet(labelStyle);
    bbtWidget.setText("--|--|----");
    ui->transportToolBar->addWidget(&bbtWidget);
    engineWidget.setFrameStyle(QFrame::Panel | QFrame::Sunken);
    engineWidget.setStyleSheet("QLabel {font-family: monospace; color: blue }");
    engineWidget.setText("----- Hz");
    ui->transportToolBar->addWidget(&engineWidget);

jhammen's avatar
jhammen committed
54
55
56
    // output doc starts hidden
    ui->outputDockWidget->setHidden(true);

jhammen's avatar
jhammen committed
57
    ui->folderTree->setColumnCount(1);
jhammen's avatar
jhammen committed
58
59
60
61
    //
    searchWidget = new SearchWidget();
    ui->leftTabWidget->addTab(searchWidget, "Search");
    connect(searchWidget, SIGNAL(searchCurrent(QString)), this, SLOT(searchCurrent(QString)));
jhammen's avatar
jhammen committed
62
    connect(searchWidget, SIGNAL(searchNext(QString)), this, SLOT(searchNext(QString)));
jhammen's avatar
jhammen committed
63
    connect(searchWidget, SIGNAL(searchProject(QString)), this, SLOT(searchProject(QString)));
jhammen's avatar
jhammen committed
64
65
    connect(searchWidget, SIGNAL(replaceNext(QString, QString)), this,
            SLOT(replaceNext(QString, QString)));
jhammen's avatar
jhammen committed
66
    connect(searchWidget, SIGNAL(clearSearch()), this, SLOT(clearSearch()));
jhammen's avatar
jhammen committed
67
68
    connect(searchWidget, SIGNAL(navigateResult(EditorLocation &)), this,
            SLOT(handleLink(EditorLocation &)));
jhammen's avatar
jhammen committed
69
70

    projectList.load();
71
    if (projectList.currentExists()) {
jhammen's avatar
jhammen committed
72
73
74
75
76
77
78
79
        loadProject();
    } else {
        on_actionOpenProject_triggered();
    }

    connect(ui->folderTree, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this,
            SLOT(folderTreeClicked(QTreeWidgetItem *, int)));

80
    connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChanged(int)));
jhammen's avatar
jhammen committed
81

82
83
    connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeEditorTab(int)));
    connect(ui->outputTabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeOutputTab(int)));
jhammen's avatar
jhammen committed
84
85
}

86
MainWindow::~MainWindow() { delete ui; }
jhammen's avatar
jhammen committed
87
88
89

// ------------ superclass methods

90
void MainWindow::closeEvent(QCloseEvent *event) {
jhammen's avatar
jhammen committed
91
    // save settings
92
    projectList.save();
jhammen's avatar
jhammen committed
93
    // close tabs
94
    if (!saveAllTabs()) {
jhammen's avatar
jhammen committed
95
96
97
        event->ignore();
    }
    // kill running scripts
98
    if (!killAllScripts()) {
jhammen's avatar
jhammen committed
99
100
101
102
103
104
        event->ignore();
    }
}

// ------------ slots

105
void MainWindow::changeProject() {
jhammen's avatar
jhammen committed
106
107
108
    ui->folderTree->clear();
    loadProject();
    // close all edit tabs not still applicable
109
    for (int i = ui->tabWidget->count() - 1; i >= 0; i--) {
jhammen's avatar
jhammen committed
110
        QWidget *widget = ui->tabWidget->widget(i);
111
112
        EditorWidget *editor = static_cast<EditorWidget *>(widget);
        if (findTreeItem(editor->path()) == nullptr) {
jhammen's avatar
jhammen committed
113
114
115
116
117
118
            ui->tabWidget->removeTab(i);
        }
    }
    selectedFolder = nullptr;
}

119
120
121
void MainWindow::closeEditorTab(int index) {
    EditorWidget *editor = qobject_cast<EditorWidget *>(ui->tabWidget->widget(index));
    if (saveOrAbandon(editor)) {
122
        projectList.currentProject().closeFile(editor->path());
jhammen's avatar
jhammen committed
123
124
125
126
        delete editor;
    }
}

127
128
void MainWindow::closeOutputTab(int index) {
    OutputWidget *output = qobject_cast<OutputWidget *>(ui->outputTabWidget->widget(index));
jhammen's avatar
jhammen committed
129
    QString name = ui->outputTabWidget->tabText(index);
130
    if (killOrDetach(output, name)) {
jhammen's avatar
jhammen committed
131
132
133
134
        delete output;
    }
}

135
void MainWindow::codeError(const QString &path, int line) {
jhammen's avatar
jhammen committed
136
    EditorWidget *editor = findEditor(path);
137
    if (editor) {
jhammen's avatar
jhammen committed
138
139
140
        editor->addError(line);
    }
}
141
void MainWindow::engineDisconnect() {
jhammen's avatar
jhammen committed
142
143
144
145
146
147
148
149
150
    ui->actionStartStopTransport->setChecked(false);
    enableTransportControls(false);
    audioEngine.disconnect();
    timeWidget.setText("00:00.000");
    bbtWidget.setText("--|--|----");
    ui->actionJackConnect->setChecked(false);
    ui->actionJackConnect->setEnabled(true);
}

151
bool MainWindow::createOrOpenEditor(NamedFile &file) {
jhammen's avatar
jhammen committed
152
153
154
155
156
157
    EditorWidget *editor = findEditor(file.path);
    if (editor) {
        ui->tabWidget->setCurrentWidget(editor);
    } else {
        // new editor for this file
        editor = new EditorWidget(file);
158
159
160
161
162
163
164
165
166
167
168
        if (editor->load()) {
            ui->tabWidget->addTab(editor, file.name);
            ui->tabWidget->setCurrentWidget(editor);
            connect(editor->document(), SIGNAL(modificationChanged(bool)), this,
                    SLOT(markDirty(bool)));
            connect(editor, SIGNAL(undoAvailable(bool)), ui->actionUndo, SLOT(setEnabled(bool)));
            connect(editor, SIGNAL(redoAvailable(bool)), ui->actionRedo, SLOT(setEnabled(bool)));
            connect(editor, SIGNAL(copyAvailable(bool)), ui->actionCut, SLOT(setEnabled(bool)));
            connect(editor, SIGNAL(copyAvailable(bool)), ui->actionCopy, SLOT(setEnabled(bool)));
            // add to project list as open file
            projectList.currentProject().openFile(file.path);
169
170
        } else {
            return false;
171
        }
jhammen's avatar
jhammen committed
172
173
174
    }
    selectedFolder = nullptr;
    enableFileActions(editor);
175
    return true;
jhammen's avatar
jhammen committed
176
177
}

178
bool MainWindow::createOrOpenEditor(const QString &path) {
jhammen's avatar
jhammen committed
179
180
    QFileInfo fileInfo(path);
    NamedFile file(fileInfo.fileName(), fileInfo.filePath());
181
    return createOrOpenEditor(file);
jhammen's avatar
jhammen committed
182
183
}

184
185
EditorWidget *MainWindow::currentEditor() {
    return static_cast<EditorWidget *>(ui->tabWidget->currentWidget());
jhammen's avatar
jhammen committed
186
187
}

188
189
void MainWindow::folderTreeClicked(QTreeWidgetItem *item, int) {
    NamedFile &file = static_cast<FolderTreeItem *>(item)->file();
jhammen's avatar
jhammen committed
190
    QFileInfo fileInfo(file.path);
191
    if (fileInfo.isDir()) {
jhammen's avatar
jhammen committed
192
193
        selectedFolder = &(file.path);
        enableFileActions(nullptr);
194
    } else if (fileInfo.isFile()) {
jhammen's avatar
jhammen committed
195
        createOrOpenEditor(file);
196
197
    } else {
        QMessageBox::information(this, "Unknown Entry", file.path);
jhammen's avatar
jhammen committed
198
199
200
    }
}

201
void MainWindow::handleLink(const QUrl &url) {
jhammen's avatar
jhammen committed
202
203
    QString path(url.path());
    createOrOpenEditor(path);
204
    if (url.hasQuery()) {
jhammen's avatar
jhammen committed
205
206
207
208
209
210
211
        int column = QString(url.query()).toInt();
        currentEditor()->focusLine(url.port(), column);
    } else {
        currentEditor()->focusLine(url.port());
    }
}

jhammen's avatar
jhammen committed
212
213
214
215
216
void MainWindow::handleLink(EditorLocation &loc) {
    createOrOpenEditor(loc.file().path);
    currentEditor()->focusLocation(loc);
}

217
void MainWindow::markDirty(bool value) {
jhammen's avatar
jhammen committed
218
    QString tabText(currentEditor()->name());
219
220
221
    if (value) {
        tabText.append("*");
    }
jhammen's avatar
jhammen committed
222
223
224
225
226
227
    int index = ui->tabWidget->currentIndex();
    ui->tabWidget->setTabText(index, tabText);
    ui->actionSaveFile->setEnabled(value);
    setWindowModified(value);
}

jhammen's avatar
jhammen committed
228
229
230
void MainWindow::searchCurrent(const QString &term) {
    EditorWidget *editor = currentEditor();
    if (editor) {
jhammen's avatar
jhammen committed
231
        searchWidget->addResults(editor->name(), editor->findAll(term, true), true);
jhammen's avatar
jhammen committed
232
233
234
    }
}

jhammen's avatar
jhammen committed
235
236
237
238
239
240
void MainWindow::searchNext(const QString &term) {
    if (currentEditor()) {
        currentEditor()->findNext(term);
    }
}

jhammen's avatar
jhammen committed
241
242
243
244
245
246
void MainWindow::replaceNext(const QString &term, const QString &replace) {
    if (currentEditor()) {
        currentEditor()->replaceNext(term, replace);
    }
}

jhammen's avatar
jhammen committed
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
void MainWindow::searchFolder(const QString &term, NamedFile &folder) {
    QDir dir(folder.path);
    dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);

    foreach (QFileInfo fileInfo, dir.entryInfoList()) {
        if (fileInfo.isFile()) {
            EditorWidget *editor = findEditor(fileInfo.filePath());
            if (editor) {
                QList<EditorLink> results = editor->findAll(term, false);
                if (results.size()) {
                    searchWidget->addResults(editor->name(), results, true);
                }
            } else {
                QList<EditorLink> results = searchFile(term, fileInfo.filePath());
                if (results.size()) {
                    searchWidget->addResults(fileInfo.fileName(), results, false);
                }
            }
        } else if (fileInfo.isDir()) {
            NamedFile childFolder(fileInfo.baseName(), fileInfo.filePath());
            searchFolder(term, childFolder);
        }
    }
}

void MainWindow::searchProject(const QString &term) {
    Project &project = projectList.currentProject();
    for (int i = 0; i < project.folderCount(); ++i) {
        NamedFile &folder = project.folder(i);
        searchFolder(term, folder);
    }
}

void MainWindow::clearSearch() {
    for (int i = 0; i < ui->tabWidget->count(); i++) {
        EditorWidget *editor = qobject_cast<EditorWidget *>(ui->tabWidget->widget(i));
        QList<QTextEdit::ExtraSelection> empty;
        editor->setExtraSelections(empty);
    }
}
jhammen's avatar
jhammen committed
287

288
void MainWindow::showTime(Position pos) {
jhammen's avatar
jhammen committed
289
290
291
    QTime qtime(0, 0, 0);
    qtime = qtime.addMSecs(pos.msec);
    timeWidget.setText(qtime.toString("mm:ss.zzz"));
292
    bbtWidget.setText(QString("%1|%2|%3").arg(pos.bar, 2).arg(pos.beat, 2).arg(pos.tick, 4));
jhammen's avatar
jhammen committed
293
294
295
    transportPosition = pos.frame;
}

296
297
void MainWindow::tabChanged(int i) {
    EditorWidget *editor = qobject_cast<EditorWidget *>(ui->tabWidget->widget(i));
298
    Project &project = projectList.currentProject();
299
    if (editor == nullptr) { // all tabs closed
jhammen's avatar
jhammen committed
300
301
302
        ui->folderTree->clearSelection();
        setWindowTitle(QCoreApplication::applicationName());
        enableFileActions(nullptr);
303
        project.activeFile(nullptr);
jhammen's avatar
jhammen committed
304
305
    } else {
        QTreeWidgetItem *item = findTreeItem(editor->path());
306
        if (item) {
jhammen's avatar
jhammen committed
307
308
309
310
311
312
313
            ui->folderTree->setCurrentItem(item);
        } else {
            ui->folderTree->clearSelection();
        }
        setWindowTitle(QString("%1[*]").arg(editor->name()));
        setWindowModified(editor->isDirty());
        enableFileActions(editor);
314
        project.activeFile(editor->path());
jhammen's avatar
jhammen committed
315
316
317
    }
}

318
319
void MainWindow::closeOtherEditors() {
    if (QAction *action = qobject_cast<QAction *>(sender())) {
320
        int index = action->data().toInt();
321
322
323
324
        for (int i = ui->tabWidget->count() - 1; i >= 0; i--) {
            if (i != index) {
                closeEditorTab(i);
            }
325
326
327
328
        }
    }
}

jhammen's avatar
jhammen committed
329
330
// ------------ auto slots

331
void MainWindow::on_actionAbout_triggered() {
jhammen's avatar
jhammen committed
332
    QString lang = QLocale::languageToString(QLocale().language());
333
334
    QString message =
        tr("Bipscript IDE %1\n%2\nQT %3").arg(BIPSCRIPT_IDE_VERSION).arg(lang).arg(QT_VERSION_STR);
jhammen's avatar
jhammen committed
335
336
337
    QMessageBox::about(this, "Bipscript-IDE", message);
}

338
void MainWindow::on_actionAPIDocumentation_triggered() {
jhammen's avatar
jhammen committed
339
340
    QStringList supported = {"en", "es"};
    QString lang = QLocale().name().left(2);
341
342
343
    if (supported.contains(lang)) {
        lang = supported[0];
    }
jhammen's avatar
jhammen committed
344
345
346
347
    QString link = QString("http://www.bipscript.org/%1/api/").arg(lang);
    QDesktopServices::openUrl(QUrl(link));
}

348
void MainWindow::on_actionCloseFile_triggered() { closeEditorTab(ui->tabWidget->currentIndex()); }
jhammen's avatar
jhammen committed
349

350
void MainWindow::on_actionComment_triggered() { currentEditor()->commentSelection(); }
jhammen's avatar
jhammen committed
351

352
void MainWindow::on_actionCopy_triggered() { currentEditor()->copy(); }
jhammen's avatar
jhammen committed
353

354
void MainWindow::on_actionCut_triggered() { currentEditor()->cut(); }
jhammen's avatar
jhammen committed
355

356
void MainWindow::on_actionNewFile_triggered() {
jhammen's avatar
jhammen committed
357
358
359
360
    QString message("New file in ");
    message.append(*selectedFolder);
    bool ok;
    QString name = QInputDialog::getText(this, "New File", message, QLineEdit::Normal, "", &ok);
361
    if (name.length() > 0) {
jhammen's avatar
jhammen committed
362
363
364
365
        // create file
        QFileInfo fileInfo(*selectedFolder + "/" + name);
        QString path(fileInfo.filePath());
        QFile file(path);
366
        if (file.exists()) {
jhammen's avatar
jhammen committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
            QMessageBox::warning(this, "File Exists", path + " already exists");
        } else {
            file.open(QIODevice::WriteOnly);
            file.close();
            // open in tree
            ui->folderTree->clear();
            loadProject();
        }
        QTreeWidgetItem *item = findTreeItem(path);
        ui->folderTree->setCurrentItem(item);
        createOrOpenEditor(path);
    }
}

381
void MainWindow::on_actionDeleteFile_triggered() {
jhammen's avatar
jhammen committed
382
383
384
385
386
387
388
    QMessageBox msgBox;
    QString path(currentEditor()->path());
    msgBox.setText("Delete " + path);
    msgBox.setInformativeText("Do you want to delete " + currentEditor()->name() + "?");
    msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Cancel);
    int choice = msgBox.exec();
389
    if (choice == QMessageBox::Ok) {
jhammen's avatar
jhammen committed
390
        // remove from tree
391
        FolderTreeItem *item = static_cast<FolderTreeItem *>(findTreeItem(path));
jhammen's avatar
jhammen committed
392
        item->parent()->removeChild(item);
393
394
        // remove from project
        projectList.currentProject().closeFile(path);
jhammen's avatar
jhammen committed
395
396
397
398
399
400
401
        // remove editor if any
        delete findEditor(path);
        // remove file from filesystem
        QFile::remove(path);
    }
}

402
void MainWindow::on_actionExamples_triggered() {
jhammen's avatar
jhammen committed
403
404
    QRegExp versionExp = QRegExp("v([0-9\\.]+)");
    QString versionString = QString(BIPSCRIPT_IDE_VERSION);
405
    if (versionExp.indexIn(versionString) == 0) {
jhammen's avatar
jhammen committed
406
407
408
409
410
411
412
413
414
415
        QString version = versionExp.cap(1);
        QString link("https://github.com/bipscript/examples/releases/tag/v");
        link.append(version);
        QDesktopServices::openUrl(QUrl(link));
    } else {
        QString message = tr("No examples for version %1").arg(versionString);
        QMessageBox::warning(this, tr("Unknown Version"), message, QMessageBox::Ok);
    }
}

416
void MainWindow::on_actionExit_triggered() { QApplication::closeAllWindows(); }
jhammen's avatar
jhammen committed
417

418
void MainWindow::on_actionFastForward_triggered() {
jhammen's avatar
jhammen committed
419
420
421
422
    transportPosition = transportPosition + audioConfig.framesPerSecond;
    audioEngine.reposition(transportPosition);
}

jhammen's avatar
jhammen committed
423
424
425
426
427
void MainWindow::on_actionFind_in_Project_triggered() {
    searchWidget->newProjectSearch();
    ui->leftTabWidget->setCurrentWidget(searchWidget);
}

jhammen's avatar
jhammen committed
428
429
430
431
432
/**
 * @brief MainWindow::on_actionRun_triggered
 *
 * action to run script
 */
433
void MainWindow::on_actionRun_triggered() {
jhammen's avatar
jhammen committed
434
    // check if possible
435
    if (!ScriptRun::possible()) {
jhammen's avatar
jhammen committed
436
437
438
439
440
441
442
443
444
445
446
447
        QMessageBox::warning(this, "Executable", "Cannot launch bipscript executable");
        return;
    }
    ScriptRun *run = new ScriptRun(currentEditor()->path());
    // add output widget for this run
    OutputWidget *out = new OutputWidget();
    ui->outputTabWidget->addTab(out, currentEditor()->name());
    ui->outputTabWidget->setCurrentWidget(out);
    connect(run, SIGNAL(started(int)), out, SLOT(running(int)));
    connect(run, SIGNAL(readStdout(QString)), out, SLOT(write(QString)));
    connect(run, SIGNAL(readStderr(QString)), out, SLOT(writeError(QString)));
    connect(run, SIGNAL(error(QString)), out, SLOT(writeError(QString)));
448
449
450
451
    connect(run, SIGNAL(exited(int)), out, SLOT(completed(int)));
    connect(out, SIGNAL(codeError(const QString &, int)), this,
            SLOT(codeError(const QString &, int)));
    connect(out, SIGNAL(linkClicked(const QUrl &)), this, SLOT(handleLink(const QUrl &)));
jhammen's avatar
jhammen committed
452
453
454
455
456
    // show output area if hidden
    ui->outputDockWidget->show();
    run->start();
}

457
void MainWindow::enableTransportControls(bool enabled) {
jhammen's avatar
jhammen committed
458
459
460
461
462
463
    ui->actionStartStopTransport->setEnabled(enabled);
    ui->actionRewind->setEnabled(enabled);
    ui->actionRestart->setEnabled(enabled);
    ui->actionFastForward->setEnabled(enabled);
}

464
465
void MainWindow::on_actionJackConnect_toggled(bool connected) {
    if (connected) {
jhammen's avatar
jhammen committed
466
467
468
        audioConfig = audioEngine.connect();
        atimer = audioEngine.timerService();
        connect(atimer, SIGNAL(transport(Position)), this, SLOT(showTime(Position)));
469
470
        connect(atimer, SIGNAL(rolling(bool)), ui->actionStartStopTransport,
                SLOT(setChecked(bool)));
jhammen's avatar
jhammen committed
471
472
473
474
475
476
477
478
479
480
        connect(atimer, SIGNAL(finished()), this, SLOT(engineDisconnect()));
        engineWidget.setText(QString("%1 Hz").arg(audioConfig.framesPerSecond));
    } else {
        ui->actionJackConnect->setEnabled(false);
        atimer->stop();
        engineWidget.setText("----- Hz");
    }
    enableTransportControls(connected && !ui->actionTransportLock->isChecked());
}

481
void MainWindow::on_actionOpenFile_triggered() {
jhammen's avatar
jhammen committed
482
483
484
    QFileDialog fileDialog(this);
    fileDialog.setFileMode(QFileDialog::AnyFile);
    fileDialog.setDirectory(projectList.commonRoot());
485
    if (fileDialog.exec()) {
jhammen's avatar
jhammen committed
486
487
488
489
490
        QString path = fileDialog.selectedFiles()[0];
        createOrOpenEditor(path);
    }
}

491
492
void MainWindow::on_actionOpenProject_triggered() {
    if (saveAllTabs()) {
jhammen's avatar
jhammen committed
493
494
495
496
497
498
        ProjectsDialog projectsDialog(this);
        connect(&projectsDialog, SIGNAL(projectChanged()), this, SLOT(changeProject()));
        projectsDialog.exec();
    }
}

499
void MainWindow::on_actionPaste_triggered() { currentEditor()->paste(); }
jhammen's avatar
jhammen committed
500

501
void MainWindow::on_actionProjectOptions_triggered() {
502
    Project &project = projectList.currentProject();
jhammen's avatar
jhammen committed
503
504
505
506
    QString value = project.executable();
    QString message("Executable Path");
    bool ok;
    QString name = QInputDialog::getText(this, "Options", message, QLineEdit::Normal, value, &ok);
507
    if (name.length() > 0) {
jhammen's avatar
jhammen committed
508
509
510
511
512
513
        // TODO: test existance etc.
        project.executable(name);
        ScriptRun::setExecutable(project.executable());
    }
}

514
void MainWindow::on_actionRedo_triggered() { currentEditor()->redo(); }
jhammen's avatar
jhammen committed
515

516
517
void MainWindow::on_actionRenameFile_triggered() {
    if (saveOrAbandon(currentEditor())) {
jhammen's avatar
jhammen committed
518
519
520
        QString message("New name");
        QString oldPath = currentEditor()->path();
        bool ok;
521
522
523
        QString path =
            QInputDialog::getText(this, "Rename", message, QLineEdit::Normal, oldPath, &ok);
        if (path.length() > 0) {
jhammen's avatar
jhammen committed
524
            QFileInfo fileInfo(path);
525
            if (fileInfo.exists()) {
jhammen's avatar
jhammen committed
526
527
528
529
530
                QString message = QString("Cannot move file, target exists:\n%1").arg(path);
                QMessageBox::warning(this, "File exists", message);
                return;
            }
            QFile oldFile(oldPath);
531
            if (!oldFile.rename(fileInfo.filePath())) {
jhammen's avatar
jhammen committed
532
533
534
535
536
537
538
539
540
541
                QString message = QString("Error on move\n %1 ->\n %2").arg(oldPath).arg(path);
                QMessageBox::warning(this, "File Move Error", message);
                return;
            }
            // success
            NamedFile file;
            file.name = fileInfo.fileName();
            file.path = fileInfo.filePath();
            // remove old from tree
            QTreeWidgetItem *item = findTreeItem(oldPath);
542
            if (item) {
jhammen's avatar
jhammen committed
543
544
                item->parent()->removeChild(item);
            }
545
546
547
548
549
            ui->folderTree->clearSelection();
            // update project
            Project &project = projectList.currentProject();
            project.closeFile(oldPath);
            project.openFile(path);
jhammen's avatar
jhammen committed
550
551
            // add new to tree if possible
            QTreeWidgetItem *parent = findTreeItem(fileInfo.path());
552
553
554
            if (parent) {
                FolderTreeItem *newItem =
                    new FolderTreeItem(parent, fileInfo.fileName(), fileInfo.filePath());
jhammen's avatar
jhammen committed
555
556
557
558
559
560
                ui->folderTree->setCurrentItem(newItem);
            }
            // update editor + tab
            currentEditor()->moveFile(file);
            int index = ui->tabWidget->currentIndex();
            QString tabText(currentEditor()->name());
561
562
563
            if (currentEditor()->isDirty()) {
                tabText.append("*");
            }
jhammen's avatar
jhammen committed
564
565
566
567
568
569
570
            ui->tabWidget->setTabText(index, tabText);
            // update main window title
            setWindowTitle(QString("%1[*]").arg(file.name));
        }
    }
}

571
void MainWindow::on_actionRestart_triggered() { audioEngine.reposition(0); }
jhammen's avatar
jhammen committed
572

573
void MainWindow::on_actionRewind_triggered() {
jhammen's avatar
jhammen committed
574
575
576
577
578
    int newpos = static_cast<int>(transportPosition - audioConfig.framesPerSecond);
    transportPosition = static_cast<uint>(qMax(newpos, 0));
    audioEngine.reposition(transportPosition);
}

579
void MainWindow::on_actionSaveFile_triggered() { currentEditor()->save(); }
jhammen's avatar
jhammen committed
580

jhammen's avatar
jhammen committed
581
582
583
584
585
void MainWindow::on_actionFocusFind_triggered() {
    searchWidget->newFileSearch();
    ui->leftTabWidget->setCurrentWidget(searchWidget);
}

586
587
void MainWindow::on_actionStartStopTransport_toggled(bool start) {
    if (start) {
jhammen's avatar
jhammen committed
588
589
590
591
592
593
594
        audioEngine.transportStart();
    } else {
        audioEngine.transportStop();
    }
    ui->actionJackConnect->setEnabled(!start);
}

595
void MainWindow::on_actionTransportLock_toggled(bool locked) {
jhammen's avatar
jhammen committed
596
597
598
599
600
601
602
    bool enabled = !locked && ui->actionJackConnect->isChecked();
    ui->actionStartStopTransport->setEnabled(enabled);
    ui->actionRewind->setEnabled(enabled);
    ui->actionRestart->setEnabled(enabled);
    ui->actionFastForward->setEnabled(enabled);
}

603
void MainWindow::on_actionUndo_triggered() { currentEditor()->undo(); }
jhammen's avatar
jhammen committed
604

605
void MainWindow::on_tabWidget_customContextMenuRequested(const QPoint &pos) {
606
607
608
609
610
611
612
    QMenu menu;
    QAction *action = menu.addAction(tr("Close Other Tabs"), this, SLOT(closeOtherEditors()));
    action->setData(ui->tabWidget->tabBar()->tabAt(pos));
    action->setEnabled(ui->tabWidget->count() > 1);
    menu.exec(QCursor::pos());
}

jhammen's avatar
jhammen committed
613
614
// ------------ private methods

615
void MainWindow::enableFileActions(EditorWidget *editor) {
jhammen's avatar
jhammen committed
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
    // requires file selected
    ui->actionDeleteFile->setEnabled(editor);
    ui->actionRun->setEnabled(editor);
    ui->actionPaste->setEnabled(editor);
    ui->actionCloseFile->setEnabled(editor);
    ui->actionComment->setEnabled(editor);
    ui->actionRenameFile->setEnabled(editor);
    // requires directory selected
    ui->actionNewFile->setEnabled(selectedFolder);
    // requires state from the editor
    ui->actionSaveFile->setEnabled(editor && editor->isDirty());
    ui->actionUndo->setEnabled(editor && editor->isUndoAvailable());
    ui->actionRedo->setEnabled(editor && editor->isRedoAvailable());
    ui->actionCut->setEnabled(editor && editor->hasSelection());
    ui->actionCopy->setEnabled(editor && editor->hasSelection());
}

633
634
635
636
637
638
EditorWidget *MainWindow::findEditor(const QString &path) {
    for (int i = 0; i < ui->tabWidget->count(); i++) {
        EditorWidget *editor = qobject_cast<EditorWidget *>(ui->tabWidget->widget(i));
        if (editor->path() == path) {
            return editor;
        }
jhammen's avatar
jhammen committed
639
640
641
642
    }
    return nullptr;
}

643
QTreeWidgetItem *MainWindow::findTreeItem(const QString &path) {
jhammen's avatar
jhammen committed
644
645
    QTreeWidgetItemIterator it(ui->folderTree);
    while (*it) {
646
647
648
649
        FolderTreeItem *item = static_cast<FolderTreeItem *>(*it);
        if (item->file().path == path) {
            return item;
        }
jhammen's avatar
jhammen committed
650
651
652
653
654
        ++it;
    }
    return nullptr;
}

655
void MainWindow::loadProject() {
656
    Project &project = projectList.currentProject();
jhammen's avatar
jhammen committed
657
658
659
660
661
    ScriptRun::setExecutable(project.executable());
    for (int i = 0; i < project.folderCount(); ++i) {
        NamedFile &folder = project.folder(i);
        ui->folderTree->addTopLevelItem(toTreeFolder(folder));
    }
662
663
664
665
666
    foreach (const QString &path, project.openFiles()) {
        if (!createOrOpenEditor(path)) {
            project.closeFile(path);
        }
    }
667
668
669
670
    EditorWidget *editor = findEditor(project.activeFile());
    if (editor) {
        ui->tabWidget->setCurrentWidget(editor);
    }
jhammen's avatar
jhammen committed
671
672
    searchWidget->clear();
    ui->leftTabWidget->setCurrentWidget(ui->folderTree);
jhammen's avatar
jhammen committed
673
674
}

675
676
677
678
bool MainWindow::saveAllTabs() {
    for (int i = 0; i < ui->tabWidget->count(); i++) {
        EditorWidget *editor = static_cast<EditorWidget *>(ui->tabWidget->widget(i));
        if (editor->isDirty()) {
jhammen's avatar
jhammen committed
679
            QMessageBox::StandardButton choice = unsavedChangesDialog(editor->path());
680
            if (choice == QMessageBox::Cancel) {
jhammen's avatar
jhammen committed
681
                return false;
682
            } else if (choice == QMessageBox::Save) {
jhammen's avatar
jhammen committed
683
684
685
686
687
688
689
                editor->save();
            }
        }
    }
    return true;
}

690
691
692
693
bool MainWindow::saveOrAbandon(EditorWidget *editor) {
    if (editor->isDirty()) {
        QMessageBox::StandardButton choice = unsavedChangesDialog(editor->path());
        if (choice == QMessageBox::Cancel) {
jhammen's avatar
jhammen committed
694
            return false;
695
696
        } else if (choice == QMessageBox::Save) {
            if (!editor->save()) {
jhammen's avatar
jhammen committed
697
698
699
700
701
702
703
                return false;
            }
        }
    }
    return true;
}

jhammen's avatar
jhammen committed
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
QList<EditorLink> MainWindow::searchFile(const QString &term, const QString &path) {
    QList<EditorLink> ret;
    QFile file(path);
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        QTextStream in(&file);
        int lineindex = 0;
        while (!in.atEnd()) {
            QString line = in.readLine();
            int index = line.indexOf(term, 0, Qt::CaseInsensitive);
            while (index != -1) {
                NamedFile nfile(file.fileName(), path);
                int anchor = lineindex + index;
                // find snippet
                int space = line.indexOf(QRegExp("\\s+"), index);
                int end = (space == -1 ? line.size() : space);
                QString text = line.mid(index, end - index);
                // create and add editor link
                EditorLink link(text, nfile, anchor, anchor + term.size());
                ret.append(link);
                index = line.indexOf(term, index + 1, Qt::CaseInsensitive);
            }
            lineindex += line.length() + 1;
        }
    }
    return ret;
}

731
732
733
bool MainWindow::killAllScripts() {
    for (int i = 0; i < ui->outputTabWidget->count(); i++) {
        OutputWidget *output = qobject_cast<OutputWidget *>(ui->outputTabWidget->widget(i));
jhammen's avatar
jhammen committed
734
        QString name = ui->outputTabWidget->tabText(i);
735
        if (!killOrDetach(output, name)) {
jhammen's avatar
jhammen committed
736
737
738
739
740
741
            return false;
        }
    }
    return true;
}

742
743
bool MainWindow::killOrDetach(OutputWidget *output, const QString &name) {
    if (output->pid() != 0) {
jhammen's avatar
jhammen committed
744
745
        QString id = QString("%1 pid %2").arg(name).arg(output->pid());
        QString mesg = "%1 is still running.\nDo you wish to kill the process?";
746
747
748
749
        QMessageBox::StandardButton choice =
            QMessageBox::warning(this, tr("Running Process"), mesg.arg(id),
                                 QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
        if (choice == QMessageBox::Cancel) {
jhammen's avatar
jhammen committed
750
            return false;
751
        } else if (choice == QMessageBox::Yes) {
jhammen's avatar
jhammen committed
752
753
            output->killScript(true);
        }
754
755
    }
    return true;
jhammen's avatar
jhammen committed
756
757
}

758
FolderTreeItem *MainWindow::toTreeFolder(NamedFile &folder) {
jhammen's avatar
jhammen committed
759
760
761
762
    FolderTreeItem *folderItem = new FolderTreeItem(nullptr, folder.name, folder.path);
    QDir dir(folder.path);
    dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
    foreach (QFileInfo fileInfo, dir.entryInfoList()) {
763
764
765
766
        if (fileInfo.isFile()) {
            folderItem->addChild(
                new FolderTreeItem(folderItem, fileInfo.fileName(), fileInfo.filePath()));
        } else if (fileInfo.isDir()) {
jhammen's avatar
jhammen committed
767
768
769
770
771
772
773
            NamedFile childFolder(fileInfo.baseName(), fileInfo.filePath());
            folderItem->addChild(toTreeFolder(childFolder));
        }
    }
    return folderItem;
}

774
775
776
QMessageBox::StandardButton MainWindow::unsavedChangesDialog(const QString &path) {
    return QMessageBox::warning(this, tr("Unsaved Changes"),
                                tr("%1 has unsaved changes.\nDo you wish to save?").arg(path),
jhammen's avatar
jhammen committed
777
778
779
                                QMessageBox::Save | QMessageBox::No | QMessageBox::Cancel);
}

780
void MainWindow::on_actionWebsite_triggered() {
jhammen's avatar
jhammen committed
781
782
783
    QString link = "http://www.bipscript.org";
    QDesktopServices::openUrl(QUrl(link));
}