+#include "xinemacontrol.h"
+
+XinemaControl::XinemaControl()
+{
+ QObject::connect(&socket, &QAbstractSocket::connected, this, &XinemaControl::connected);
+ QObject::connect(&socket, &QAbstractSocket::disconnected, this, &XinemaControl::disconnected);
+ QObject::connect(&socket, &QIODevice::readyRead, this, &XinemaControl::data_available);
+}
+
+void XinemaControl::connect(const QHostAddress &addr)
+{
+ socket.connectToHost(addr, 34588);
+}
+
+bool XinemaControl::is_connected() const
+{
+ return socket.state()==QAbstractSocket::ConnectedState;
+}
+
+void XinemaControl::list_directory(const QString &dir)
+{
+ if(!is_connected())
+ return;
+
+ send_request("list_directory "+dir);
+}
+
+void XinemaControl::play_file(const QString &fn)
+{
+ if(!is_connected())
+ return;
+
+ send_request("play_file "+fn);
+}
+
+void XinemaControl::send_request(const QString &req)
+{
+ socket.write(req.toUtf8());
+ socket.write("\n", 1);
+}
+
+void XinemaControl::data_available()
+{
+ char rbuf[1024];
+ int len = socket.read(rbuf, sizeof(rbuf));
+ if(len<0)
+ return;
+
+ buffer.append(rbuf, len);
+ unsigned start = 0;
+ while(1)
+ {
+ int newline = buffer.indexOf('\n', start);
+ if(newline<0)
+ break;
+
+ QString reply = QString::fromUtf8(buffer.mid(start, newline-start));
+ process_reply(reply);
+
+ start = newline+1;
+ }
+
+ buffer.remove(0, start);
+}
+
+void XinemaControl::process_reply(const QString &reply)
+{
+ int space = reply.indexOf(' ');
+ QString keyword = reply.mid(0, space);
+ QString args;
+ if(space>=0)
+ args = reply.mid(space+1);
+
+ if(keyword=="directory")
+ emit directory_started(args);
+ else if(keyword=="subdir")
+ emit subdirectory_added(args);
+ else if(keyword=="file")
+ emit file_added(args);
+}