summaryrefslogtreecommitdiffstats
path: root/konversation/src/dccchat.cpp
blob: 588bf1be4d0c81aa3004cf23b1581d44d8afa7b0 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
*/

/*
  Copyright (C) 2002 Dario Abatianni <eisfuchs@tigress.com>
  Copyright (C) 2006 Eike Hein <hein@kde.org>
  Copyright (C) 2004,2007 Shintaro Matsuoka <shin@shoegazed.org>
*/

#include "dccchat.h"
#include "dcccommon.h"
#include "konversationapplication.h"
#include "konversationmainwindow.h"
#include "irccharsets.h"
#include "ircview.h"
#include "ircviewbox.h"
#include "ircinput.h"
#include "topiclabel.h"
#include "server.h"
#include "channel.h"

#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>

#include <tqvbox.h>
#include <tqhostaddress.h>
#include <tqtextcodec.h>
#include <tqsplitter.h>
#include <tqpopupmenu.h>

#include <klineedit.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <kserversocket.h>
#include <ksocketaddress.h>
#include <kstreamsocket.h>
#include <kaction.h>

#define DCCCHAT_BUFFER_SIZE 1024


DccChat::DccChat(TQWidget* tqparent, bool listen, Server* server, const TQString& ownNick, const TQString& partnerNick, const TQString& partnerHost, int partnerPort)
    : ChatWindow(tqparent)
{
    kdDebug() << "DccChat::DccChat() [BEGIN]" << endl;

    m_dccSocket = 0;
    m_listenSocket = 0;

    m_ownNick = ownNick;

    m_partnerNick = partnerNick;
    m_partnerHost = partnerHost;
    m_partnerPort = partnerPort;

    setType(ChatWindow::DccChat);
    setChannelEncodingSupported(true);

    m_headerSplitter = new TQSplitter(Qt::Vertical, this);

    m_sourceLine = new Konversation::TopicLabel(m_headerSplitter);

    IRCViewBox* ircViewBox = new IRCViewBox(m_headerSplitter, NULL);
    setTextView(ircViewBox->ircView());

    m_dccChatInput = new IRCInput(this);
    getTextView()->installEventFilter(m_dccChatInput);
    m_dccChatInput->setEnabled( false );

    ChatWindow::setName( '-' + m_partnerNick + '-' );
    ChatWindow::setLogfileName( '-' + m_partnerNick + '-' );

    TQPopupMenu* popup = textView->getPopup();

    if (popup)
    {
        KAction* action = KonversationApplication::instance()->getMainWindow()->actionCollection()->action("open_logfile");

        if (action)
        {
            popup->insertSeparator();
            action->plug(popup);
        }
    }

    // connect the signals and slots
    connect( m_dccChatInput, TQT_SIGNAL( submit() ), this, TQT_SLOT( dccChatTextEntered() ) );
    connect( m_dccChatInput, TQT_SIGNAL( textPasted( const TQString& ) ), this, TQT_SLOT( textPasted( const TQString& ) ) );

    connect( getTextView(), TQT_SIGNAL( textPasted(bool) ), m_dccChatInput, TQT_SLOT( paste(bool) ) );
    connect( getTextView(), TQT_SIGNAL( gotFocus() ), m_dccChatInput, TQT_SLOT( setFocus() ) );
    connect( getTextView(), TQT_SIGNAL( autoText(const TQString&) ), this, TQT_SLOT( sendDccChatText( const TQString& ) ) );

    if (listen)
    {
        listenForPartner();
        TQString ownNumericalIp = DccCommon::textIpToNumericalIp( DccCommon::getOwnIp( server ) );
        server->requestDccChat( m_partnerNick, ownNumericalIp, TQString::number( m_ownPort ) );
    }
    else
    {
        connectToPartner();
    }

    kdDebug() << "DccChat::DccChat() [END]" << endl;

    updateAppearance();
}

DccChat::~DccChat()
{
    kdDebug() << "DccChat::~DccChat()" << endl;
    if(m_dccSocket)
        m_dccSocket->close();
    if(m_listenSocket)
        m_listenSocket->close();
}

void DccChat::listenForPartner()
{
    kdDebug() << "DccChat::listenForPartner() [BEGIN]" << endl;

    // Set up server socket
    TQString failedReason;
    if ( Preferences::dccSpecificChatPorts() )
        m_listenSocket = DccCommon::createServerSocketAndListen( TQT_TQOBJECT(this), &failedReason, Preferences::dccChatPortsFirst(), Preferences::dccChatPortsLast() );
    else
        m_listenSocket = DccCommon::createServerSocketAndListen( TQT_TQOBJECT(this), &failedReason );
    if ( !m_listenSocket )
    {
        getTextView()->appendServerMessage( i18n( "DCC" ), i18n( "Could not open a socket for listening: %1" ).tqarg( failedReason ) );
        return;
    }

    connect( m_listenSocket, TQT_SIGNAL(readyAccept()), this, TQT_SLOT(heardPartner()) );

    // Get our own port number
    m_ownPort = DccCommon::getServerSocketPort( m_listenSocket );
    kdDebug() << "DccChat::listenForPartner(): using port " << m_ownPort << endl;

    getTextView()->appendServerMessage( i18n("DCC"), i18n("Offering DCC Chat connection to %1 on port %2...").tqarg( m_partnerNick ).tqarg( m_ownPort ) );
    m_sourceLine->setText(i18n( "DCC chat with %1 on port %2." ).tqarg( m_partnerNick ).tqarg( m_ownPort ) );
    kdDebug() << "DccChat::listenForPartner() [END]" << endl;
}

void DccChat::connectToPartner()
{
    TQHostAddress ip;

    ip.setAddress(m_partnerHost.toUInt());
    m_partnerHost=ip.toString();

    getTextView()->appendServerMessage( i18n( "DCC" ), i18n( "%1 = nickname, %2 = IP, %3 = port",
        "Establishing DCC Chat connection to %1 (%2:%3)..." ).tqarg( m_partnerNick ).tqarg( m_partnerHost ).tqarg( m_partnerPort ) );

    m_sourceLine->setText( i18n( "%1 = nickname, %2 = IP, %3 = port", "DCC chat with %1 on %2:%3." ).tqarg( m_partnerNick ).tqarg( host ).tqarg( m_partnerPort ) );

    m_dccSocket = new KNetwork::KStreamSocket( m_partnerHost, TQString::number( m_partnerPort ), TQT_TQOBJECT(this) );

    m_dccSocket->setBlocking(false);
    m_dccSocket->setFamily(KNetwork::KResolver::InetFamily);
    m_dccSocket->enableRead(false);
    m_dccSocket->enableWrite(false);
    m_dccSocket->setTimeout(10000);
    m_dccSocket->blockSignals(false);

    connect( m_dccSocket, TQT_SIGNAL( hostFound() ),                        this, TQT_SLOT( lookupFinished() )           );
    connect( m_dccSocket, TQT_SIGNAL( connected( const KResolverEntry& ) ), this, TQT_SLOT( dccChatConnectionSuccess() ) );
    connect( m_dccSocket, TQT_SIGNAL( gotError( int ) ),                    this, TQT_SLOT( dccChatBroken( int ) )       );
    connect( m_dccSocket, TQT_SIGNAL( readyRead() ),                        this, TQT_SLOT( readData() )                 );
    connect( m_dccSocket, TQT_SIGNAL( closed() ),                           this, TQT_SLOT( socketClosed() )             );

    m_dccSocket->connect();
    
#if 0
    //getTextView()->appendServerMessage(i18n("DCC"),i18n("Looking for host %1...").tqarg(host));
#endif

}

void DccChat::lookupFinished()
{
	
#if 0
	//getTextView()->appendServerMessage(i18n("DCC"),i18n("Host found, connecting..."));
#endif

}

void DccChat::dccChatConnectionSuccess()
{
    getTextView()->appendServerMessage( i18n( "DCC" ), i18n( "Established DCC Chat connection to %1." ).tqarg( m_partnerNick ) );
    m_dccSocket->enableRead(true);
    m_dccChatInput->setEnabled(true);
}

void DccChat::dccChatBroken(int error)
{
    getTextView()->appendServerMessage(i18n("Error"),i18n("Connection broken, error code %1.").tqarg(error));
    m_dccSocket->enableRead(false);
    m_dccSocket->blockSignals(true);
    m_dccSocket->close();
}

void DccChat::readData()
{
    kdDebug() << k_funcinfo << ( m_listenSocket == 0 ) << " BEGIN" << endl;
    int available=0;
    int actual=0;
    char* buffer=0;
    TQString line;
    TQTextCodec* codec = Konversation::IRCCharsets::self()->codecForName(m_encoding.isEmpty() ? Konversation::IRCCharsets::self()->encodingForLocale() : m_encoding);

    available = m_dccSocket->bytesAvailable();
    if( available > 0 )
    {
        buffer = new char[ available + 1 ];
        actual = m_dccSocket->readBlock( buffer, available );
        buffer[ actual ] = 0;
        line.append( codec->toUnicode( buffer ) );
        delete[] buffer;

        TQStringList lines = TQStringList::split( '\n', line );

        for( TQStringList::iterator itLine = lines.begin() ; itLine != lines.end() ; itLine++ )
        {
            if( (*itLine).startsWith( "\x01" ) )
            {
                // cut out the CTCP command
                TQString ctcp = (*itLine).mid( 1, (*itLine).find( 1, 1 ) - 1 );

                TQString ctcpCommand = ctcp.section( " ", 0, 0 );
                TQString ctcpArgument = ctcp.section( " ", 1 );

                if( ctcpCommand.lower() == "action" )
                    appendAction( m_partnerNick, ctcpArgument );
                else
                    getTextView()->appendServerMessage( i18n( "CTCP" ), i18n( "Received unknown CTCP-%1 request from %2" ).tqarg( ctcp ).tqarg( m_partnerNick ) );
            }
            else getTextView()->append( m_partnerNick, *itLine );
        }                                         // endfor
    } else {
        dccChatBroken(m_dccSocket->error());
    }

    kdDebug() << k_funcinfo << " END" << endl;
}

void DccChat::dccChatTextEntered()
{
    TQString line = m_dccChatInput->text();
    m_dccChatInput->setText("");
    if ( line.lower() == Preferences::commandChar()+"clear" )
    {
        textView->clear();
    }
    else if ( !line.isEmpty() )
    {
        sendDccChatText(line);
    }
}

void DccChat::sendDccChatText(const TQString& sendLine)
{
    kdDebug() << k_funcinfo << " BEGIN" << endl;
    // create a work copy
    TQString output(sendLine);
    TQString cc=Preferences::commandChar();

    if(!output.isEmpty())
    {
        TQStringList lines = TQStringList::split('\n',output);
        // wrap socket into a stream
        TQTextStream stream(m_dccSocket);
        // init stream props
        stream.setCodec(Konversation::IRCCharsets::self()->codecForName(m_encoding.isEmpty() ? Konversation::IRCCharsets::self()->encodingForLocale() : m_encoding));

        for( TQStringList::iterator itLine = lines.begin() ; itLine != lines.end() ; itLine++ )
        {
            TQString line( *itLine );

            // replace aliases and wildcards
            //  if(filter.replaceAliases(line)) line=server->parseWildcards(line,nick,getName(),TQString(),TQString(),TQString());

            //  line=filter.parse(nick,line,getName());

            // convert /me actions
            TQString cmd=line.section(' ', 0,0).lower();
            if (cmd == cc+"me")
            {
                appendAction( m_ownNick, line.section( " ", 1 ) );
                line=TQString("\x01%1 %2\x01").tqarg("ACTION").tqarg(line.section(" ",1));
            }
            else if (cmd == cc+"close")
            {
                closeYourself(false);
                return;
            }
            else
                getTextView()->append( m_ownNick, line );

            stream << line << endl;
        }                                         // endfor

        // detach stream
        stream.unsetDevice();
    }
    kdDebug() << k_funcinfo << " END" << endl;
}

void DccChat::heardPartner()
{
    m_dccSocket = static_cast<KNetwork::KStreamSocket*>( m_listenSocket->accept() );

    if( !m_dccSocket )
    {
        getTextView()->appendServerMessage( i18n( "Error" ),i18n( "Could not accept the client." ) );
        return;
    }

    connect( m_dccSocket, TQT_SIGNAL( readyRead() ),     this, TQT_SLOT( readData() )           );
    connect( m_dccSocket, TQT_SIGNAL( closed() ),        this, TQT_SLOT( socketClosed() )       );
    connect( m_dccSocket, TQT_SIGNAL( gotError( int ) ), this, TQT_SLOT( dccChatBroken( int ) ) );

    // the listen socket isn't needed anymore
    disconnect( m_listenSocket, 0, 0, 0 );
    m_listenSocket->close();
    m_listenSocket = 0;

    m_dccSocket->enableRead(true);
    m_dccChatInput->setEnabled(true);

    getTextView()->appendServerMessage( i18n( "DCC" ), i18n( "Established DCC Chat connection to %1." ).tqarg( m_partnerNick ) );
}

void DccChat::socketClosed()
{
    getTextView()->appendServerMessage(i18n("DCC"),"Connection closed.");
    m_dccChatInput->setEnabled(false);
    m_dccSocket = 0;
}

void DccChat::textPasted(const TQString& text)
{
    sendDccChatText(text);
}

void DccChat::childAdjustFocus()
{
    m_dccChatInput->setFocus();
}

bool DccChat::canBeFrontView()
{
    return true;
}

bool DccChat::searchView()
{
    return true;
}

int DccChat::getOwnPort()
{
    return m_ownPort;
}

TQString DccChat::getTextInLine() 
{
    return m_dccChatInput->text();
}

void DccChat::appendInputText( const TQString& s, bool fromCursor )
{
    if(!fromCursor)
    {
        m_dccChatInput->append(s);
    }
    else
    {
        int para = 0, index = 0;
        m_dccChatInput->getCursorPosition(&para, &index);
        m_dccChatInput->insertAt(s, para, index);
        m_dccChatInput->setCursorPosition(para, index + s.length());
    }
}

//FIXME uh... where is the confimation for this?
bool DccChat::closeYourself(bool)
{
    deleteLater();
    return true;
}

void DccChat::setChannelEncoding(const TQString& encoding) // virtual
{
    m_encoding = encoding;
}

TQString DccChat::getChannelEncoding() // virtual
{
    return m_encoding;
}

TQString DccChat::getChannelEncodingDefaultDesc()  // virtual
{
    return i18n("Default ( %1 )").tqarg(Konversation::IRCCharsets::self()->encodingForLocale());
}

void DccChat::showEvent(TQShowEvent* /* event */)
{
    if(m_initialShow) {
        m_initialShow = false;
        TQValueList<int> sizes;
        sizes << m_sourceLine->tqsizeHint().height() << (height() - m_sourceLine->tqsizeHint().height());
        m_headerSplitter->setSizes(sizes);
    }
}

void DccChat::updateAppearance()
{
    TQColor fg;
    TQColor bg;

    if(Preferences::inputFieldsBackgroundColor())
    {
        fg=Preferences::color(Preferences::ChannelMessage);
        bg=Preferences::color(Preferences::TextViewBackground);
    }
    else
    {
        fg=tqcolorGroup().foreground();
        bg=tqcolorGroup().base();
    }

    m_dccChatInput->unsetPalette();
    m_dccChatInput->setPaletteForegroundColor(fg);
    m_dccChatInput->setPaletteBackgroundColor(bg);

    getTextView()->unsetPalette();

    if(Preferences::showBackgroundImage())
    {
        getTextView()->setViewBackground(Preferences::color(Preferences::TextViewBackground),
        Preferences::backgroundImage());
    }
    else
    {
        getTextView()->setViewBackground(Preferences::color(Preferences::TextViewBackground),
        TQString());
    }

    if (Preferences::customTextFont())
    {
        getTextView()->setFont(Preferences::textFont());
        m_dccChatInput->setFont(Preferences::textFont());
    }
    else
    {
        getTextView()->setFont(KGlobalSettings::generalFont());
        m_dccChatInput->setFont(KGlobalSettings::generalFont());
    }

    ChatWindow::updateAppearance();
}

#include "dccchat.moc"