controller.cpp 9.73 KB
Newer Older
1
#include "controller.h"
2
3
4
5
6
#include "compiler.h"
#include "errornotifier.h"
#include "system_error_handler.h"
#include <QDebug>
#include <QProcess>
7
8
9
10
#include <mutex>

namespace Modules {

Leander Schulten's avatar
Leander Schulten committed
11
Controller::Controller():run_(false)
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
void Controller::setSpotify(Spotify::Spotify *spotify){
    if(spotify==this->spotify)
        return;
    for(const auto & c : spotifyConnections){
        QObject::disconnect(c);
    }
    spotifyConnections.clear();
    this->spotify = spotify;
    spotifyState.enabled = spotify != nullptr;
    if(spotify&&spotify->getCurrentPlayingObject()){
        spotifyState.enabled = true;
        spotifyConnections.push_back(QObject::connect(spotify,&Spotify::Spotify::currentTrackChanged,[&,spotify](){
            if(spotify->getCurrentAudioFeatures()&&spotify->getCurrentPlayingObject()&&spotify->getCurrentPlayingObject()->item){
                spotifyState.currentTrack.~TrackObject();
                new (&spotifyState.currentTrack) TrackObject(*spotify->getCurrentAudioFeatures(),*spotify->getCurrentPlayingObject()->item);
                spotifyState.newTrack = true;
            }else{
                spotifyState.currentTrack.~TrackObject();
                new (&spotifyState.currentTrack) TrackObject();
            }
        }));
        spotifyConnections.push_back(QObject::connect(spotify,&QObject::destroyed,[this](){
            this->setSpotify(nullptr);
        }));
        spotifyConnections.push_back(QObject::connect(spotify,&Spotify::Spotify::audioFeaturesChanged,[&,spotify](){
            if(spotify->getCurrentAudioFeatures()&&spotify->getCurrentPlayingObject()&&spotify->getCurrentPlayingObject()->item){
                spotifyState.currentTrack.~TrackObject();
                new (&spotifyState.currentTrack) TrackObject(*spotify->getCurrentAudioFeatures(),*spotify->getCurrentPlayingObject()->item);
                spotifyState.newTrack = true;
            }else{
                spotifyState.currentTrack.~TrackObject();
                new (&spotifyState.currentTrack) TrackObject();
            }
        }));
    }
}

bool Controller::haveAnalysis()const{
    return spotify&&spotify->getCurrentAudioAnalysis()&&spotify->getCurrentPlayingObject()&&spotify->getCurrentPlayingObject()->item;
}

void Controller::updateSpotifyState(){
    if(haveAnalysis()){
        spotifyState.enabled = true;
        spotifyState.currentTrack.progress_ms = spotify->getCurrentPlayingObject()->getProgressInMs();
        spotifyState.isPlaying = spotify->getCurrentPlayingObject()->is_playing;        
#define UPDATE_OBJECT(type,Type,Object) \
    if(int newIndex = spotify->getCurrentAudioAnalysis()->getIndexIn ## Type ## sForTime(spotifyState.currentTrack.progress_ms);newIndex != lastIndexOfCurrent ## Type){ \
        lastIndexOfCurrent ## Type = newIndex; \
        spotifyState.current ## Type .~ Object(); \
        if(newIndex>=0){ \
67
            new (&spotifyState.current ## Type) Object(spotify->getCurrentAudioAnalysis()->type ## s[static_cast<unsigned>(newIndex)]); \
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
            spotifyState.new ## Type = true; \
        } else {\
            new (&spotifyState.current ## Type) Object(); \
            spotifyState.new ## Type = true; \
        } \
    }else{ \
        spotifyState.new##Type = false;\
    }
        if(spotifyState.isPlaying){
            UPDATE_OBJECT(bar,Bar,TimeIntervalObject)
            UPDATE_OBJECT(tatum,Tatum,TimeIntervalObject)
            UPDATE_OBJECT(beat,Beat,TimeIntervalObject)
            UPDATE_OBJECT(section,Section,SectionObject)
            UPDATE_OBJECT(segment,Segment,SegmentObject)
#undef UPDATE_OBJECT
        }
    }else{
#define UPDATE_OBJECT(Type,Object) \
        spotifyState.current ## Type .~ Object(); \
        new (&spotifyState.current ## Type) Object(); \
        spotifyState.new ## Type = false;

        UPDATE_OBJECT(Bar, TimeIntervalObject)
        UPDATE_OBJECT(Beat, TimeIntervalObject)
        UPDATE_OBJECT(Tatum, TimeIntervalObject)
        UPDATE_OBJECT(Section, SectionObject)
        UPDATE_OBJECT(Segment, SegmentObject)
        UPDATE_OBJECT(Track, TrackObject)
#undef UPDATE_OBJECT
        spotifyState.haveCurrentTrack = false;
        spotifyState.isPlaying = false;
        spotifyState.enabled = false;
    }

}

104
105
106
void Controller::run() noexcept{
    while (run_) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
107
108
109
        if (!run_) {
            break;
        }
Leander Schulten's avatar
Leander Schulten committed
110
        std::unique_lock<std::mutex> l(vectorLock);
111
        updateSpotifyState();
Leander Schulten's avatar
Leander Schulten committed
112
        for(auto pb = runningProgramms.begin() ; pb != runningProgramms.end();){
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
            try {
                if ((*pb)->doStep(1)) {
                    deletingProgramBlock = (*pb).get();
                    (**pb).stop();
                    deletingProgramBlock = nullptr;
                    pb = runningProgramms.erase(pb);
                } else {
                    ++pb;
                }
            } catch (const error::crash_error &e) {
                QString msg(e.what());
                for (const auto &frame : e.getStacktrace()) {
                    const auto asString = boost::stacktrace::to_string(frame);
                    if (asString.find("____") != std::string::npos) {
                        QString filename;
                        int lineNumber = -1;
                        QProcess p;
                        QString cmd = Compiler::compilerCmd;
#ifdef Q_OS_WIN
                        if (!cmd.endsWith(QLatin1String("g++.exe"))) {
                            qDebug() << "Error in " << __FILE__ << " line " << __LINE__ << ": Can not build command to translate address to line. g++.exe not found in Compiler::cmd";
                        } else {
                            cmd.replace(QLatin1String("g++.exe"), QLatin1String("addr2line.exe"));
136
137
138
139
140
141
142
143
144
145
146
147
148

                            auto pos = asString.find(" in ");
                            if (pos == std::string::npos) {
                                pos = asString.find(" at ");
                                if (pos == std::string::npos) {
                                    pos = 0;
                                } else {
                                    pos += 4;
                                }
                            } else {
                                pos += 4;
                            }
                            p.start(cmd, QStringList() << QStringLiteral("-e") << QString::fromStdString(asString).mid(pos) << QString::number(reinterpret_cast<std::size_t>(frame.address()), 16));
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
                            p.waitForFinished();
                            QByteArray output = p.readAllStandardOutput();
                            int seperator = output.lastIndexOf(':');
                            filename = output.left(seperator);
                            lineNumber = output.mid(seperator + 1).trimmed().toInt();
                        }
#else
#warning OS not supported
#endif
                        if (lineNumber >= 0) {
                            QFile file(filename);
                            if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
                                break;
                            }
                            msg += " in line " + QString::number(lineNumber) + " in file " + filename.mid(filename.lastIndexOf('/') + 1) + "\n";
                            int currentLineNumber = 0;
                            while (!file.atEnd() && currentLineNumber < lineNumber + 2) {
                                ++currentLineNumber;
                                QByteArray line = file.readLine();
                                if (currentLineNumber == lineNumber) {
                                    msg += "->" + line;
                                } else if (currentLineNumber == lineNumber - 1 || currentLineNumber == lineNumber + 1) {
                                    msg += "     " + line;
                                }
                            }
                            file.close();
                        }
                        break;
                    }
                }
                ErrorNotifier::showError(QStringLiteral("Error while executing ") + (**pb).getName() + ":\n" + msg);
                // if it was in a doStep call
                if (deletingProgramBlock == nullptr) {
                    try {
                        deletingProgramBlock = (*pb).get();
                        (**pb).stop();
                    } catch (...) {
                        // we ignore the error (the module is completly broken)
                    }
                }
                // maybe inside the stop call
190
                deletingProgramBlock = nullptr;
191
                // we remove the programm from the running list
Leander Schulten's avatar
Leander Schulten committed
192
193
194
                pb = runningProgramms.erase(pb);
            }
        }
195
        spotifyState.newTrack = false;
196
        controlPoint.positionChanged = false;
197
198
199
    }
}

Leander Schulten's avatar
Leander Schulten committed
200
201
void Controller::runProgramm(std::shared_ptr<ProgramBlock> pb){
    std::unique_lock<std::mutex> l(vectorLock);
202
    runningProgramms.push_back(pb);  
Leander Schulten's avatar
Leander Schulten committed
203
204
205
}

void Controller::stopProgramm(std::shared_ptr<ProgramBlock> pb){
206
207
208
    // preventing deadlocks, this method is called when call stop on a ProgramBlock, wich is called in function run
    if(deletingProgramBlock == pb.get())
        return;
Leander Schulten's avatar
Leander Schulten committed
209
    std::unique_lock<std::mutex> l(vectorLock);
210
    runningProgramms.erase(std::remove(runningProgramms.begin(),runningProgramms.end(),pb),runningProgramms.end());    
211
}
Leander Schulten's avatar
Leander Schulten committed
212
213
void Controller::stopProgramm(ProgramBlock* pb){
    std::unique_lock<std::mutex> l(vectorLock);
214
    runningProgramms.erase(std::remove_if(runningProgramms.begin(),runningProgramms.end(),[&](const auto &v){return v.get()==pb;}),runningProgramms.end());    
Leander Schulten's avatar
Leander Schulten committed
215
}
216
217
218
219

bool Controller::isProgramRunning(ProgramBlock * pb){
    std::unique_lock<std::mutex> l(vectorLock);
    return std::any_of(runningProgramms.cbegin(),runningProgramms.cend(),[=](const auto & p){return p.get()==pb;});
Leander Schulten's avatar
Leander Schulten committed
220
221
}

222
}