controller.cpp 9.26 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));
Leander Schulten's avatar
Leander Schulten committed
107
        std::unique_lock<std::mutex> l(vectorLock);
108
        updateSpotifyState();
Leander Schulten's avatar
Leander Schulten committed
109
        for(auto pb = runningProgramms.begin() ; pb != runningProgramms.end();){
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
            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"));
                            const int length = std::strlen("0x00007FFA4E5CA299 in ");
                            p.start(cmd, QStringList() << QStringLiteral("-e") << QString::fromStdString(asString).mid(length) << QString::number(reinterpret_cast<std::size_t>(frame.address()), 16));
                            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
176
                deletingProgramBlock = nullptr;
177
                // we remove the programm from the running list
Leander Schulten's avatar
Leander Schulten committed
178
179
180
                pb = runningProgramms.erase(pb);
            }
        }
181
        spotifyState.newTrack = false;
182
        controlPoint.positionChanged = false;
183
184
185
    }
}

Leander Schulten's avatar
Leander Schulten committed
186
187
void Controller::runProgramm(std::shared_ptr<ProgramBlock> pb){
    std::unique_lock<std::mutex> l(vectorLock);
188
    runningProgramms.push_back(pb);  
Leander Schulten's avatar
Leander Schulten committed
189
190
191
}

void Controller::stopProgramm(std::shared_ptr<ProgramBlock> pb){
192
193
194
    // 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
195
    std::unique_lock<std::mutex> l(vectorLock);
196
    runningProgramms.erase(std::remove(runningProgramms.begin(),runningProgramms.end(),pb),runningProgramms.end());    
197
}
Leander Schulten's avatar
Leander Schulten committed
198
199
void Controller::stopProgramm(ProgramBlock* pb){
    std::unique_lock<std::mutex> l(vectorLock);
200
    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
201
}
202
203
204
205

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
206
207
}

208
}