2 Copyright (c) 2006 Paolo Capriotti <p.capriotti@gmail.com>
3 (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
11 #include "connection.h"
16 #include <QTextStream>
18 #include <QTextStream>
26 Connection::Connection()
29 , m_initialized(false) {
31 if (!logFileName
.isEmpty()) {
32 logFile
= new QFile(logFileName
);
33 logFile
->open(QIODevice::WriteOnly
);
34 logStream
= 0; //= new QTextStream(logFile);
40 Connection::~Connection() {
47 KProcess
* p
= qobject_cast
<KProcess
*>(m_device
);
54 void Connection::establish(const char* host
, quint16 port
,
55 const QString
& helper
, const QString
& helper_cmd
) {
57 KProcess
* p
= qobject_cast
<KProcess
*>(m_device
);
63 strncpy(m_host
, host
, 256);
66 m_helper_cmd
= helper_cmd
;
68 if (helper
.isEmpty()) {
69 QTcpSocket
*s
= new QTcpSocket(this);
70 s
->setObjectName("IcsSocket");
72 connect(s
, SIGNAL(hostFound()), this, SIGNAL(hostFound()));
73 connect(s
, SIGNAL(connected()), this, SIGNAL(established()));
76 s
->connectToHost(m_host
, m_port
);
82 m_device
= new KProcess(this);
83 m_device
->setObjectName("IcsHelper");
85 if (m_helper_cmd
.contains("$(HOST_IP)")) {
86 QHostInfo::lookupHost(m_host
, this, SLOT(lookedUp(const QHostInfo
)));
89 lookedUp(QHostInfo());
93 connect(m_device
, SIGNAL(readyRead()), this, SLOT(processLine()));
96 void Connection::lookedUp(const QHostInfo
&hi
) {
97 KProcess
* p
= m_device
? qobject_cast
<KProcess
*>(m_device
) : NULL
;
99 QString args
= m_helper_cmd
;
100 args
.replace("$(HOST_NAME)", QString(m_host
) );
101 args
.replace("$(HOST_IP)", hi
.addresses().isEmpty() ? QString() :
102 hi
.addresses().first().toString () );
103 args
.replace("$(PORT)", QString::number(m_port
));
104 p
->setOutputChannelMode(KProcess::OnlyStdoutChannel
);
105 p
->setProgram(m_helper
, args
.split(' '));
109 if(!m_unsent_text
.isEmpty()) {
110 QTextStream
os(m_device
);
114 (*logStream
) << "> " << m_unsent_text
;
115 m_unsent_text
= QString();
120 void Connection::processLine() {
122 ERROR("No m_device");
126 while (m_device
->canReadLine()) {
127 QString line
= m_device
->readLine();
128 line
= buffer
+ line
.replace("\r", "");
129 receivedLine(line
, buffer
.length());
131 (*logStream
) << "< " << line
<< "\n";
136 if ((size
= m_device
->bytesAvailable()) > 0) {
137 char* data
= new char[size
+ 1];
138 m_device
->read(data
, size
);
140 int offset
= buffer
.length();
141 buffer
+= QString(data
).replace("\r", "");
144 receivedText(buffer
, offset
);
148 void Connection::sendText(const QString
& text
) {
150 m_unsent_text
+= text
+ "\n";
155 ERROR("No m_device");
160 QTextStream
os(m_device
);
164 (*logStream
) << "> " << text
<< "\n";