aboutsummaryrefslogtreecommitdiffstats
path: root/gui/mainwindow.cc
blob: a6e6cbdacfca413c10e8fb9b909ac276a82b515e (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
#include "mainwindow.h"
#include <functional>
#include <iostream>
#include <string>
#include "emb.h"
#include "pybindings.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(Design *_design, QWidget *parent)
        : QMainWindow(parent), ui(new Ui::MainWindow), design(_design)
{
    ui->setupUi(this);
    PyImport_ImportModule("emb");

    write = [this](std::string s) {
        // ui->plainTextEdit->moveCursor(QTextCursor::End);
        // ui->plainTextEdit->insertPlainText(s.c_str());
        // ui->plainTextEdit->moveCursor(QTextCursor::End);
        ui->plainTextEdit->appendPlainText(s.c_str());
    };
    emb::set_stdout(write);
    std::string title = "nextpnr-ice40 - " + design->chip.getChipName();
    setWindowTitle(title.c_str());
}

MainWindow::~MainWindow() { delete ui; }

void handle_system_exit() { exit(-1); }

int MainWindow::executePython(std::string command)
{
    PyObject *m, *d, *v;
    m = PyImport_AddModule("__main__");
    if (m == NULL)
        return -1;
    d = PyModule_GetDict(m);
    v = PyRun_StringFlags(command.c_str(),
                          (command.empty() ? Py_file_input : Py_single_input),
                          d, d, NULL);
    if (v == NULL) {
        PyObject *exception, *v, *tb;

        if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
            handle_system_exit();
        }
        PyErr_Fetch(&exception, &v, &tb);
        if (exception == NULL)
            return 0;
        PyErr_NormalizeException(&exception, &v, &tb);
        if (tb == NULL) {
            tb = Py_None;
            Py_INCREF(tb);
        }
        PyException_SetTraceback(v, tb);
        if (exception == NULL)
            return 0;
        PyErr_Clear();

        PyObject *objectsRepresentation = PyObject_Str(v);
        const char *errorStr = PyUnicode_AsUTF8(objectsRepresentation);
        ui->plainTextEdit->appendPlainText(errorStr);
        Py_DECREF(objectsRepresentation);
        Py_XDECREF(exception);
        Py_XDECREF(v);
        Py_XDECREF(tb);
        return -1;
    }
    Py_DECREF(v);
    return 0;
}

void MainWindow::on_lineEdit_returnPressed()
{
    std::string input = ui->lineEdit->text().toStdString();
    ui->plainTextEdit->appendPlainText(std::string(">>> " + input).c_str());
    ui->plainTextEdit->update();
    ui->lineEdit->clear();
    int error = executePython(input);
}