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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
|
/*
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.
*/
/*
The line input widget with chat enhanced functions
begin: Tue Mar 5 2002
copyright: (C) 2002 by Dario Abatianni
email: eisfuchs@tigress.com
*/
#include "ircinput.h"
#include "konversationapplication.h"
#include "multilineedit.h"
#include "chatwindow.h"
#include "ircview.h"
#include <tqrichtext_p.h>
#include <tqclipboard.h>
#include <tqregexp.h>
#include <tqdom.h>
#include <tqevent.h>
#include <tqobject.h>
#include <tqwhatsthis.h>
#include <tqpopupmenu.h>
#include <kapplication.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kcompletionbox.h>
#define MAXHISTORY 100
#define RICHTEXT 0
IRCInput::IRCInput(TQWidget* tqparent) : KTextEdit(tqparent)
{
m_lastHeight=document()->height();
//I am not terribly interested in finding out where this value comes from
//nor in compensating for it if my guess is incorrect. so, cache it.
m_qtBoxPadding=m_lastHeight-fontMetrics().lineSpacing();
connect(KApplication::kApplication(), TQT_SIGNAL(appearanceChanged()), this, TQT_SLOT(updateAppearance()));
m_multiRow = Preferences::useMultiRowInputBox();
m_useSelection = false;
// connect history signal
connect(this,TQT_SIGNAL (history(bool)) ,this,TQT_SLOT (getHistory(bool)) );
// add one empty line to the history (will be overwritten with newest entry)
historyList.prepend(TQString());
// reset history line counter
lineNum=0;
// reset completion mode
setCompletionMode('\0');
completionBox = new KCompletionBox(this);
connect(completionBox, TQT_SIGNAL(activated(const TQString&)), this, TQT_SLOT(insertCompletion(const TQString&)));
// widget may not be resized vertically
tqsetSizePolicy(TQSizePolicy(TQSizePolicy::MinimumExpanding,TQSizePolicy::Fixed));
//NoWrap coupled with the size policy constrains the line edit to be one row high
setWordWrap(m_multiRow ? WidgetWidth : NoWrap);
setHScrollBarMode(AlwaysOff);
setVScrollBarMode(AlwaysOff);
#if RICHTEXT == 1
setAutoFormatting(TQTextEdit::AutoNone);
setTextFormat(RichText);
#else
setTextFormat(PlainText);
#endif
TQWhatsThis::add(this, i18n("<qt>The input line is where you type messages to be sent the channel, query, or server. A message sent to a channel is seen by everyone on the channel, whereas a message in a query is sent only to the person in the query with you.<p>To automatically complete the nickname you began typing, press Tab. If you have not begun typing, the last successfully completed nickname will be used.<p>You can also send special commands:<br><table><tr><th>/me <i>action</i></th><td>shows up as an action in the channel or query. For example: <em>/me sings a song</em> will show up in the channel as 'Nick sings a song'.</td></tr><tr><th>/whois <i>nickname</i></th><td>shows information about this person, including what channels they are in.</td></tr></table><p>For more commands, see the Konversation Handbook.<p>A message cannot contain multiple lines.</qt>"));
m_disableSpellCheckTimer = new TQTimer(this);
connect(m_disableSpellCheckTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(disableSpellChecking()));
}
IRCInput::~IRCInput()
{
}
void IRCInput::showEvent(TQShowEvent* /* e */)
{
m_disableSpellCheckTimer->stop();
setCheckSpellingEnabled(Preferences::spellChecking());
}
void IRCInput::hideEvent(TQHideEvent* /* event */)
{
Preferences::setSpellChecking(checkSpellingEnabled());
// If we disable spell-checking here immediately, tab switching will
// be very slow. If we delay it by five seconds, a user would have to
// need more than five seconds to switch between all his tabs before
// the slowdown starts to occur (show event stops the timer, i.e. wrap-
// around is not an issue). Unless he has unlikely amounts of channels,
// needing more than five seconds indicates very slow switching speed,
// which makes the delay a non-issue to begin with. Hence this fixes
// the problem on the surface. In the KDE 4 version, we want to look
// into having only one spell-checker instance instead of starting and
// stopping at all.
m_disableSpellCheckTimer->start(5000, true);
}
void IRCInput::disableSpellChecking()
{
setCheckSpellingEnabled(false);
}
void IRCInput::slotSpellCheckDone(const TQString& s)
{
// NOTE: kdelibs 3.5's KSpell stupidly adds newlines to its
// buffer at some point for god-knows-what-reason, and for-
// gets to remove them again before handing the result back.
// There's a FIXME to the effect in KSpell::check. This is
// a workaround.
if (s == text() || s == (text() + '\n'+'\n'))
return;
setText(s.simplifyWhiteSpace());
}
void IRCInput::updateAppearance()
{
m_multiRow = Preferences::useMultiRowInputBox();
setWordWrap(m_multiRow ? WidgetWidth : NoWrap);
m_lastHeight=heightForWidth(tqsizeHint().width());
ensureCursorVisible(); //appears to trigger updateGeometry
}
void IRCInput::resizeContents( int w, int h )
{
if (document()->height() != m_lastHeight) {
m_lastHeight=document()->height();
updateGeometry();
}
KTextEdit::resizeContents(w,h);
}
// widget must be only one line high - luckily QT will enforce this via wrappping policy
TQSize IRCInput::tqsizeHint() const
{
constPolish();
int ObscurePadding = 4;
int f=2*frameWidth();
int w=12 * (kMax(fontMetrics().lineSpacing(),14) + f + ObscurePadding);
int h=m_lastHeight - m_qtBoxPadding + f + ObscurePadding;
return TQSize(w,h);
}
TQPopupMenu *IRCInput::createPopupMenu( const TQPoint &pos )
{
TQPopupMenu *menu=KTextEdit::createPopupMenu(pos);
menu->removeItemAt(menu->count()-1);
menu->removeItemAt(menu->count()-1);
return menu;
}
TQString IRCInput::text() const
{
#if RICHTEXT == 1
TQString content=KTextEdit::text();
TQDomDocument document;
document.setContent(content,false);
TQDomNodeList nodes=document.elementsByTagName("p");
if(nodes.count())
{
TQDomElement node=nodes.item(0).toElement();
return node.text();
}
return TQString();
#else
return KTextEdit::text();
#endif
}
void IRCInput::setText(const TQString& text)
{
// reimplemented to set cursor at the end of the new text
KTextEdit::setText(text);
setCursorPosition(0,text.length()+1);
}
// FIXME - find a better way to do this. eventfilters introduce nebulous behaviour
//take text events from IRCView and TopicLabel
bool IRCInput::eventFilter(TQObject *object,TQEvent *event)
{
if (object->isA("IRCView") || object->isA("Konversation::TopicLabel"))
{
if (event->type() == TQEvent::KeyPress)
{
TQKeyEvent* ke = TQT_TQKEYEVENT(event);
// Allow tab to be handled naturally by the widget.
// Once it runs out of links it goes to the next control.
if (ke->key() == Key_Tab && (ke->state() == 0 || ke->state() == TQt::ShiftButton))
return false;
if (!ke->text().isEmpty() && ((ke->state() & (TQt::ShiftButton|TQt::Keypad)) || ke->state() == 0))
{
setFocus();
KonversationApplication::sendEvent(this,event);
return true;
}
}
}
return KTextEdit::eventFilter(object,event);
}
// Take care of Tab, Cursor and so on
void IRCInput::keyPressEvent(TQKeyEvent* e)
{
switch(e->key())
{
case Key_Tab:
emit nickCompletion();
return;
break;
case Key_Up:
if (m_multiRow && (e->state() != (TQt::ShiftButton|TQt::ControlButton)))
break;
emit history(true);
return;
break;
case Key_Down:
if (m_multiRow && (e->state() != (TQt::ShiftButton|TQt::ControlButton)))
break;
emit history(false);
return;
break;
case Key_Enter:
case Key_Return:
{
if(text().length()) addHistory(text());
if(completionBox->isHidden())
{
// Reset completion mode
setCompletionMode('\0');
// Ctrl+Enter is a special case in which commands should be send as normal messages
if ( e->state() & ControlButton )
{
emit envelopeCommand();
}
else
{
setText(static_cast<KonversationApplication*>(kapp)->doAutoreplace(text(),true));
emit submit();
}
}
else
{
insertCompletion(completionBox->currentText());
completionBox->hide();
}
// prevent widget from adding lines
return;
}
break;
default:
// Check if the keystroke actually produced text. If not it was just a qualifier.
if(!e->text().isEmpty() || ((e->key() >= TQt::Key_Home) && (e->key() <= TQt::Key_Down)))
{
if(getCompletionMode()!='\0')
{
setCompletionMode('\0');
emit endCompletion();
}
completionBox->hide();
}
// support ASCII BEL
if(e->ascii() == 7)
insert("%G");
// support ^U (delete text in input box)
else if(e->ascii() == 21)
setText("");
}
KTextEdit::keyPressEvent(e);
}
void IRCInput::addHistory(const TQString& line)
{
// Only add line if it's not the same as the last was
if(historyList[1]!=line)
{
// Replace empty first entry with line
historyList[0]=line;
// Add new empty entry to history
historyList.prepend(TQString());
// Remove oldest line in history, if the list grows beyond MAXHISTORY
if(historyList.count()>MAXHISTORY) historyList.remove(historyList.last());
}
// Reset history counter
lineNum=0;
}
void IRCInput::getHistory(bool up)
{
// preserve text
historyList[lineNum]=text();
// Did the user press cursor up?
if(up)
{
// increment the line counter
lineNum++;
// if we are past the end of the list, go to the last entry
if(lineNum==historyList.count()) lineNum--;
}
// no, it was cursor down
else
{
// If we are at the top of the lest, arrow-down shall add the text to the history and clear the field for new input
if(lineNum==0)
{
if(text().length()) addHistory(text());
setText("");
}
// If we aren't at the top of the list, decrement the line counter
else
{
lineNum--;
}
}
// replace the text in the input field with history
setText(historyList[lineNum]);
}
/**
* Work around the fact that while TQTextEdit::paste() is virtual, whether we are
* pasting from middle button or control-V is PRIVATE and NO ACCESSOR is given.
*/
void IRCInput::contentsMouseReleaseEvent( TQMouseEvent *ev)
{
if (ev->button() == Qt::MidButton)
{
m_useSelection=true;
}
// Reset completion
setCompletionMode('\0');
emit endCompletion();
KTextEdit::contentsMouseReleaseEvent(ev);
m_useSelection=false;
}
void IRCInput::paste(bool useSelection)
{
m_useSelection = useSelection;
paste();
m_useSelection = false;
}
void IRCInput::paste()
{
TQClipboard *cb = KApplication::kApplication()->tqclipboard();
setFocus();
// Copy text from the clipboard (paste)
TQString pasteText;
if(m_useSelection)
{
pasteText = cb->text( TQClipboard::Selection);
}
else
{
pasteText = cb->text( TQClipboard::Clipboard);
}
// is there any text in the clipboard?
if(!pasteText.isEmpty())
{
//End completion on paste
setCompletionMode('\0');
emit endCompletion();
bool signal=false;
// replace \r with \n to make xterm pastes happy
pasteText.replace("\r","\n");
// remove blank lines
while(pasteText.contains("\n\n"))
pasteText.replace("\n\n","\n");
TQRegExp reTopSpace("^ *\n");
while(pasteText.contains(reTopSpace))
pasteText.remove(reTopSpace);
TQRegExp reBottomSpace("\n *$");
while(pasteText.contains(reBottomSpace))
pasteText.remove(reBottomSpace);
// Escape % when var expansion is enabled
if (!Preferences::disableExpansion())
{
pasteText.replace ('%', "%%");
}
// does the text contain at least one newline character?
if(pasteText.find('\n')!=-1)
{
// make comparisons easier (avoid signed / unsigned warnings)
unsigned int pos=pasteText.find('\n');
unsigned int rpos=pasteText.findRev('\n');
// emit the signal if there's a line break in the middle of the text
if(pos>0 && pos!=(pasteText.length()-1))
signal=true;
// emit the signal if there's more than one line break in the text
if(pos!=rpos)
signal=true;
// Remove the \n from end of the line if there's only one \n
if(!signal)
pasteText.remove('\n');
}
else
{
insert(pasteText);
return;
}
// should we signal the application due to newlines in the paste?
if(signal)
{
// if there is text in the input line
if(!text().isEmpty())
{
// prepend text to the paste
pasteText=text()+'\n'+pasteText;
}
// ask the user on long pastes
if(checkPaste(pasteText))
{
// signal pasted text
emit textPasted(pasteText);
// remember old line, in case the user does not paste eventually
addHistory(pasteText);
// delete input text
setText("");
}
}
// otherwise let the KLineEdit handle the pasting
else KTextEdit::paste();
}
}
bool IRCInput::checkPaste(TQString& text)
{
int doPaste=KMessageBox::Yes;
//text is now preconditioned when you get here
int lines=text.contains('\n');
if(text.length()>256 || lines)
{
doPaste=KMessageBox::warningYesNoCancel
(this,
i18n("<qt>You are attempting to paste a large portion of text (%1 bytes or %2 lines) into "
"the chat. This can cause connection resets or flood kills. "
"Do you really want to continue?</qt>").tqarg(text.length()).tqarg(lines+1),
i18n("Large Paste Warning"),
i18n("Paste"),
i18n("&Edit..."),
"LargePaste",
KMessageBox::Dangerous);
}
if (doPaste==KMessageBox::No)
{
TQString ret(MultilineEdit::edit(this,text));
if (ret.isEmpty())
return false;
text=ret;
return true;
}
return (doPaste==KMessageBox::Yes);
}
void IRCInput::showCompletionList(const TQStringList& nicks)
{
completionBox->setItems(nicks);
completionBox->popup();
}
void IRCInput::insertCompletion(const TQString& nick)
{
int pos; // = cursorPosition();
int oldPos; // = cursorPosition();
getCursorPosition(&oldPos,&pos);
oldPos=pos;
TQString line = text();
while(pos && line[pos-1] != ' ') pos--;
line.remove(pos, oldPos - pos);
// did we find the nick in the middle of the line?
if(pos)
{
TQString addMiddle(Preferences::nickCompleteSuffixMiddle());
line.insert(pos, nick + addMiddle);
pos += nick.length() + addMiddle.length();
}
// no, it was at the beginning
else
{
setLastCompletion(nick);
TQString addStart(Preferences::nickCompleteSuffixStart());
line.insert(pos, nick + addStart);
pos += nick.length() + addStart.length();
}
setText(line);
setCursorPosition(0,pos);
}
void IRCInput::setLastCompletion(const TQString& completion)
{
m_lastCompletion = completion;
}
// Accessor methods
void IRCInput::setCompletionMode(char mode) { completionMode=mode; }
char IRCInput::getCompletionMode() { return completionMode; }
void IRCInput::setOldCursorPosition(int pos) { oldPos=pos; }
int IRCInput::getOldCursorPosition() { return oldPos; }
#include "ircinput.moc"
|