~larryprice/acolyterm/release-0.1

« back to all changes in this revision

Viewing changes to src/plugin/konsole/Session.cpp

  • Committer: Larry Price
  • Date: 2016-06-15 14:47:59 UTC
  • Revision ID: larry.price@canonical.com-20160615144759-6wopn0gxwgta3x1n
Updating QMLTermWidget and removing unnecessary konsole codebase

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
    This file is part of Konsole
3
 
 
4
 
    Copyright (C) 2006-2007 by Robert Knight <robertknight@gmail.com>
5
 
    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
6
 
 
7
 
    Rewritten for QT4     by e_k      <e_k at users.sourceforge.net>, Copyright (C) 2008
8
 
    Rewritten for QT5/QML by Dmitry Zagnoyko   <hiroshidi@gmail.com>, Copyright (C) 2013
9
 
 
10
 
    This program is free software; you can redistribute it and/or modify
11
 
    it under the terms of the GNU General Public License as published by
12
 
    the Free Software Foundation; either version 2 of the License, or
13
 
    (at your option) any later version.
14
 
 
15
 
    This program is distributed in the hope that it will be useful,
16
 
    but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 
    GNU General Public License for more details.
19
 
 
20
 
    You should have received a copy of the GNU General Public License
21
 
    along with this program; if not, write to the Free Software
22
 
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
23
 
    02110-1301  USA.
24
 
*/
25
 
 
26
 
// Own
27
 
#include "Session.h"
28
 
 
29
 
// Standard
30
 
#include <assert.h>
31
 
#include <stdlib.h>
32
 
 
33
 
// Qt
34
 
#include <QGuiApplication>
35
 
#include <QtGui/QWindow>
36
 
 
37
 
#include <QtCore/QByteRef>
38
 
#include <QtCore/QDir>
39
 
#include <QtCore/QFile>
40
 
#include <QtCore/QRegExp>
41
 
#include <QtCore/QStringList>
42
 
#include <QtCore/QFile>
43
 
#include <QtCore>
44
 
 
45
 
#include "Pty.h" // REUSE THIS
46
 
//#include "kptyprocess.h"
47
 
#include "TerminalDisplay.h"
48
 
#include "ShellCommand.h" // REUSE THIS
49
 
#include "Vt102Emulation.h" // REUSE THIS
50
 
 
51
 
 
52
 
int Session::lastSessionId = 0;
53
 
 
54
 
Session::Session() :
55
 
        _shellProcess(0)
56
 
        , _emulation(0)
57
 
        , _monitorActivity(false)
58
 
        , _monitorSilence(false)
59
 
        , _notifiedActivity(false)
60
 
        , _autoClose(true)
61
 
        , _wantedClose(false)
62
 
        , _silenceSeconds(10)
63
 
        , _addToUtmp(false)  // disabled by default because of a bug encountered on certain systems
64
 
        // which caused Konsole to hang when closing a tab and then opening a new
65
 
        // one.  A 'QProcess destroyed while still running' warning was being
66
 
        // printed to the terminal.  Likely a problem in KPty::logout()
67
 
        // or KPty::login() which uses a QProcess to start /usr/bin/utempter
68
 
        , _flowControl(true)
69
 
        , _fullScripting(false)
70
 
        , _sessionId(0)
71
 
//   , _zmodemBusy(false)
72
 
//   , _zmodemProc(0)
73
 
//   , _zmodemProgress(0)
74
 
        , _hasDarkBackground(false)
75
 
{
76
 
    //prepare DBus communication
77
 
//    new SessionAdaptor(this);
78
 
    _sessionId = ++lastSessionId;
79
 
//    QDBusConnection::sessionBus().registerObject(QLatin1String("/Sessions/")+QString::number(_sessionId), this);
80
 
 
81
 
    //create teletype for I/O with shell process
82
 
    _shellProcess = new Pty();
83
 
 
84
 
    //create emulation backend
85
 
    _emulation = new Vt102Emulation();
86
 
 
87
 
    connect( _emulation, SIGNAL( titleChanged( int, const QString & ) ),
88
 
             this, SLOT( setUserTitle( int, const QString & ) ) );
89
 
    connect( _emulation, SIGNAL( stateSet(int) ),
90
 
             this, SLOT( activityStateSet(int) ) );
91
 
//    connect( _emulation, SIGNAL( zmodemDetected() ), this ,
92
 
//            SLOT( fireZModemDetected() ) );
93
 
    connect( _emulation, SIGNAL( changeTabTextColorRequest( int ) ),
94
 
             this, SIGNAL( changeTabTextColorRequest( int ) ) );
95
 
    connect( _emulation, SIGNAL(profileChangeCommandReceived(const QString &)),
96
 
             this, SIGNAL( profileChangeCommandReceived(const QString &)) );
97
 
    // TODO
98
 
    // connect( _emulation,SIGNAL(imageSizeChanged(int,int)) , this ,
99
 
    //        SLOT(onEmulationSizeChange(int,int)) );
100
 
 
101
 
    //connect teletype to emulation backend
102
 
    _shellProcess->setUtf8Mode(_emulation->utf8());
103
 
 
104
 
    connect( _shellProcess,SIGNAL(receivedData(const char *,int)),this,
105
 
             SLOT(onReceiveBlock(const char *,int)) );
106
 
    connect( _emulation,SIGNAL(sendData(const char *,int)),_shellProcess,
107
 
             SLOT(sendData(const char *,int)) );
108
 
    connect( _emulation,SIGNAL(lockPtyRequest(bool)),_shellProcess,SLOT(lockPty(bool)) );
109
 
    connect( _emulation,SIGNAL(useUtf8Request(bool)),_shellProcess,SLOT(setUtf8Mode(bool)) );
110
 
 
111
 
    connect( _shellProcess,SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(done(int)) );
112
 
    // not in kprocess anymore connect( _shellProcess,SIGNAL(done(int)), this, SLOT(done(int)) );
113
 
 
114
 
    //setup timer for monitoring session activity
115
 
    _monitorTimer = new QTimer(this);
116
 
    _monitorTimer->setSingleShot(true);
117
 
    connect(_monitorTimer, SIGNAL(timeout()), this, SLOT(monitorTimerDone()));
118
 
}
119
 
 
120
 
WId Session::windowId() const
121
 
{
122
 
    // Returns a window ID for this session which is used
123
 
    // to set the WINDOWID environment variable in the shell
124
 
    // process.
125
 
    //
126
 
    // Sessions can have multiple views or no views, which means
127
 
    // that a single ID is not always going to be accurate.
128
 
    //
129
 
    // If there are no views, the window ID is just 0.  If
130
 
    // there are multiple views, then the window ID for the
131
 
    // top-level window which contains the first view is
132
 
    // returned
133
 
 
134
 
    if ( _views.count() == 0 ) {
135
 
        return 0;
136
 
    } else {
137
 
//        QQuickItem * window = _views.first();
138
 
 
139
 
//        Q_ASSERT( window );
140
 
 
141
 
//        while ( window->parentWidget() != 0 ) {
142
 
//            window = window->parentWidget();
143
 
//        }
144
 
 
145
 
        return QGuiApplication::focusWindow()->winId();
146
 
    }
147
 
}
148
 
 
149
 
void Session::setDarkBackground(bool darkBackground)
150
 
{
151
 
    _hasDarkBackground = darkBackground;
152
 
}
153
 
bool Session::hasDarkBackground() const
154
 
{
155
 
    return _hasDarkBackground;
156
 
}
157
 
bool Session::isRunning() const
158
 
{
159
 
    return _shellProcess->state() == QProcess::Running;
160
 
}
161
 
 
162
 
void Session::setCodec(QTextCodec * codec)
163
 
{
164
 
    emulation()->setCodec(codec);
165
 
}
166
 
 
167
 
void Session::setProgram(const QString & program)
168
 
{
169
 
    _program = ShellCommand::expand(program);
170
 
}
171
 
void Session::setInitialWorkingDirectory(const QString & dir)
172
 
{
173
 
    _initialWorkingDir = ShellCommand::expand(dir);
174
 
}
175
 
void Session::setArguments(const QStringList & arguments)
176
 
{
177
 
    _arguments = ShellCommand::expand(arguments);
178
 
}
179
 
 
180
 
QList<KTerminalDisplay *> Session::views() const
181
 
{
182
 
    return _views;
183
 
}
184
 
 
185
 
void Session::addView(KTerminalDisplay * widget)
186
 
{
187
 
    Q_ASSERT( !_views.contains(widget) );
188
 
 
189
 
    _views.append(widget);
190
 
 
191
 
    if ( _emulation != 0 ) {
192
 
        // connect emulation - view signals and slots
193
 
        connect( widget , SIGNAL(keyPressedSignal(QKeyEvent *)) , _emulation ,
194
 
                 SLOT(sendKeyEvent(QKeyEvent *)) );
195
 
//        connect( widget , SIGNAL(mouseSignal(int,int,int,int)) , _emulation ,
196
 
//                 SLOT(sendMouseEvent(int,int,int,int)) );
197
 
//        connect( widget , SIGNAL(sendStringToEmu(const char *)) , _emulation ,
198
 
//                 SLOT(sendString(const char *)) );
199
 
 
200
 
        // allow emulation to notify view when the foreground process
201
 
        // indicates whether or not it is interested in mouse signals
202
 
//        connect( _emulation , SIGNAL(programUsesMouseChanged(bool)) , widget ,
203
 
//                 SLOT(setUsesMouse(bool)) );
204
 
 
205
 
        //widget->setUsesMouse( _emulation->programUsesMouse() );
206
 
 
207
 
        widget->setScreenWindow(_emulation->createWindow());
208
 
    }
209
 
 
210
 
    //connect view signals and slots
211
 
    QObject::connect( widget ,SIGNAL(changedContentSizeSignal(int,int)),this,
212
 
                      SLOT(onViewSizeChange(int,int)));
213
 
 
214
 
    QObject::connect( widget ,SIGNAL(destroyed(QObject *)) , this ,
215
 
                      SLOT(viewDestroyed(QObject *)) );
216
 
//slot for close
217
 
    //QObject::connect(this, SIGNAL(finished()), widget, SLOT(close()));
218
 
 
219
 
}
220
 
 
221
 
void Session::viewDestroyed(QObject * view)
222
 
{
223
 
    KTerminalDisplay * display = (KTerminalDisplay *)view;
224
 
 
225
 
    Q_ASSERT( _views.contains(display) );
226
 
 
227
 
    removeView(display);
228
 
}
229
 
 
230
 
void Session::removeView(KTerminalDisplay * widget)
231
 
{
232
 
    _views.removeAll(widget);
233
 
 
234
 
    disconnect(widget,0,this,0);
235
 
 
236
 
    if ( _emulation != 0 ) {
237
 
        // disconnect
238
 
        //  - key presses signals from widget
239
 
        //  - mouse activity signals from widget
240
 
        //  - string sending signals from widget
241
 
        //
242
 
        //  ... and any other signals connected in addView()
243
 
        disconnect( widget, 0, _emulation, 0);
244
 
 
245
 
        // disconnect state change signals emitted by emulation
246
 
        disconnect( _emulation , 0 , widget , 0);
247
 
    }
248
 
 
249
 
    // close the session automatically when the last view is removed
250
 
    if ( _views.count() == 0 ) {
251
 
        close();
252
 
    }
253
 
}
254
 
 
255
 
void Session::run()
256
 
{
257
 
    //check that everything is in place to run the session
258
 
//    if (_program.isEmpty()) {
259
 
//        qDebug() << "Session::run() - program to run not set.";
260
 
//    }
261
 
//    else {
262
 
//        qDebug() << "Session::run() - program:" << _program;
263
 
//    }
264
 
 
265
 
//    if (_arguments.isEmpty()) {
266
 
//        qDebug() << "Session::run() - no command line arguments specified.";
267
 
//    }
268
 
//    else {
269
 
//        qDebug() << "Session::run() - arguments:" << _arguments;
270
 
//    }
271
 
 
272
 
    // Upon a KPty error, there is no description on what that error was...
273
 
    // Check to see if the given program is executable.
274
 
 
275
 
 
276
 
    /* ok iam not exactly sure where _program comes from - however it was set to /bin/bash on my system
277
 
     * Thats bad for BSD as its /usr/local/bin/bash there - its also bad for arch as its /usr/bin/bash there too!
278
 
     * So i added a check to see if /bin/bash exists - if no then we use $SHELL - if that does not exist either, we fall back to /bin/sh
279
 
     * As far as i know /bin/sh exists on every unix system.. You could also just put some ifdef __FREEBSD__ here but i think these 2 filechecks are worth
280
 
     * their computing time on any system - especially with the problem on arch linux beeing there too.
281
 
     */
282
 
    QString exec = QFile::encodeName(_program);
283
 
    // if 'exec' is not specified, fall back to default shell.  if that
284
 
    // is not set then fall back to /bin/sh
285
 
 
286
 
    // here we expect full path. If there is no fullpath let's expect it's
287
 
    // a custom shell (eg. python, etc.) available in the PATH.
288
 
    if (exec.startsWith("/"))
289
 
    {
290
 
        QFile excheck(exec);
291
 
        if ( exec.isEmpty() || !excheck.exists() ) {
292
 
            exec = getenv("SHELL");
293
 
        }
294
 
        excheck.setFileName(exec);
295
 
 
296
 
        if ( exec.isEmpty() || !excheck.exists() ) {
297
 
            exec = "/bin/sh";
298
 
        }
299
 
    }
300
 
 
301
 
    // _arguments sometimes contain ("") so isEmpty()
302
 
    // or count() does not work as expected...
303
 
    QString argsTmp(_arguments.join(" ").trimmed());
304
 
    QStringList arguments;
305
 
    arguments << exec;
306
 
    if (argsTmp.length())
307
 
        arguments << _arguments;
308
 
 
309
 
    QString cwd = QDir::currentPath();
310
 
    if (!_initialWorkingDir.isEmpty()) {
311
 
        _shellProcess->setWorkingDirectory(_initialWorkingDir);
312
 
    } else {
313
 
        _shellProcess->setWorkingDirectory(cwd);
314
 
    }
315
 
 
316
 
    _shellProcess->setFlowControlEnabled(_flowControl);
317
 
    _shellProcess->setErase(_emulation->eraseChar());
318
 
 
319
 
    // this is not strictly accurate use of the COLORFGBG variable.  This does not
320
 
    // tell the terminal exactly which colors are being used, but instead approximates
321
 
    // the color scheme as "black on white" or "white on black" depending on whether
322
 
    // the background color is deemed dark or not
323
 
    QString backgroundColorHint = _hasDarkBackground ? "COLORFGBG=15;0" : "COLORFGBG=0;15";
324
 
 
325
 
    /* if we do all the checking if this shell exists then we use it ;)
326
 
     * Dont know about the arguments though.. maybe youll need some more checking im not sure
327
 
     * However this works on Arch and FreeBSD now.
328
 
     */
329
 
    int result = _shellProcess->start(exec,
330
 
                                      arguments,
331
 
                                      _environment << backgroundColorHint,
332
 
                                      windowId(),
333
 
                                      _addToUtmp);
334
 
 
335
 
    if (result < 0) {
336
 
        qDebug() << "CRASHED! result: " << result;
337
 
        return;
338
 
    }
339
 
 
340
 
    _shellProcess->setWriteable(false);  // We are reachable via kwrited.
341
 
    //qDebug() << "started!";
342
 
    emit started();
343
 
}
344
 
 
345
 
void Session::setUserTitle( int what, const QString & caption )
346
 
{
347
 
    //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle )
348
 
    bool modified = false;
349
 
 
350
 
    // (btw: what=0 changes _userTitle and icon, what=1 only icon, what=2 only _nameTitle
351
 
    if ((what == 0) || (what == 2)) {
352
 
        if ( _userTitle != caption ) {
353
 
            _userTitle = caption;
354
 
            modified = true;
355
 
        }
356
 
    }
357
 
 
358
 
    if ((what == 0) || (what == 1)) {
359
 
        if ( _iconText != caption ) {
360
 
            _iconText = caption;
361
 
            modified = true;
362
 
        }
363
 
    }
364
 
 
365
 
    if (what == 11) {
366
 
        QString colorString = caption.section(';',0,0);
367
 
        qDebug() << __FILE__ << __LINE__ << ": setting background colour to " << colorString;
368
 
        QColor backColor = QColor(colorString);
369
 
        if (backColor.isValid()) { // change color via \033]11;Color\007
370
 
            if (backColor != _modifiedBackground) {
371
 
                _modifiedBackground = backColor;
372
 
 
373
 
                // bail out here until the code to connect the terminal display
374
 
                // to the changeBackgroundColor() signal has been written
375
 
                // and tested - just so we don't forget to do this.
376
 
                Q_ASSERT( 0 );
377
 
 
378
 
                emit changeBackgroundColorRequest(backColor);
379
 
            }
380
 
        }
381
 
    }
382
 
 
383
 
    if (what == 30) {
384
 
        if ( _nameTitle != caption ) {
385
 
            setTitle(Session::NameRole,caption);
386
 
            return;
387
 
        }
388
 
    }
389
 
 
390
 
    if (what == 31) {
391
 
        QString cwd=caption;
392
 
        cwd=cwd.replace( QRegExp("^~"), QDir::homePath() );
393
 
        emit openUrlRequest(cwd);
394
 
    }
395
 
 
396
 
    // change icon via \033]32;Icon\007
397
 
    if (what == 32) {
398
 
        if ( _iconName != caption ) {
399
 
            _iconName = caption;
400
 
 
401
 
            modified = true;
402
 
        }
403
 
    }
404
 
 
405
 
    if (what == 50) {
406
 
        emit profileChangeCommandReceived(caption);
407
 
        return;
408
 
    }
409
 
 
410
 
    if ( modified ) {
411
 
        emit titleChanged();
412
 
    }
413
 
}
414
 
 
415
 
QString Session::userTitle() const
416
 
{
417
 
    return _userTitle;
418
 
}
419
 
void Session::setTabTitleFormat(TabTitleContext context , const QString & format)
420
 
{
421
 
    if ( context == LocalTabTitle ) {
422
 
        _localTabTitleFormat = format;
423
 
    } else if ( context == RemoteTabTitle ) {
424
 
        _remoteTabTitleFormat = format;
425
 
    }
426
 
}
427
 
QString Session::tabTitleFormat(TabTitleContext context) const
428
 
{
429
 
    if ( context == LocalTabTitle ) {
430
 
        return _localTabTitleFormat;
431
 
    } else if ( context == RemoteTabTitle ) {
432
 
        return _remoteTabTitleFormat;
433
 
    }
434
 
 
435
 
    return QString();
436
 
}
437
 
 
438
 
void Session::monitorTimerDone()
439
 
{
440
 
    //FIXME: The idea here is that the notification popup will appear to tell the user than output from
441
 
    //the terminal has stopped and the popup will disappear when the user activates the session.
442
 
    //
443
 
    //This breaks with the addition of multiple views of a session.  The popup should disappear
444
 
    //when any of the views of the session becomes active
445
 
 
446
 
 
447
 
    //FIXME: Make message text for this notification and the activity notification more descriptive.
448
 
    if (_monitorSilence) {
449
 
//    KNotification::event("Silence", ("Silence in session '%1'", _nameTitle), QPixmap(),
450
 
//                    QApplication::activeWindow(),
451
 
//                    KNotification::CloseWhenWidgetActivated);
452
 
        emit stateChanged(NOTIFYSILENCE);
453
 
    } else {
454
 
        emit stateChanged(NOTIFYNORMAL);
455
 
    }
456
 
 
457
 
    _notifiedActivity=false;
458
 
}
459
 
 
460
 
void Session::activityStateSet(int state)
461
 
{
462
 
    if (state==NOTIFYBELL) {
463
 
        QString s;
464
 
        s.sprintf("Bell in session '%s'",_nameTitle.toLatin1().data());
465
 
 
466
 
        emit bellRequest( s );
467
 
    } else if (state==NOTIFYACTIVITY) {
468
 
        if (_monitorSilence) {
469
 
            _monitorTimer->start(_silenceSeconds*1000);
470
 
        }
471
 
 
472
 
        if ( _monitorActivity ) {
473
 
            //FIXME:  See comments in Session::monitorTimerDone()
474
 
            if (!_notifiedActivity) {
475
 
//        KNotification::event("Activity", ("Activity in session '%1'", _nameTitle), QPixmap(),
476
 
//                        QApplication::activeWindow(),
477
 
//        KNotification::CloseWhenWidgetActivated);
478
 
                _notifiedActivity=true;
479
 
            }
480
 
        }
481
 
    }
482
 
 
483
 
    if ( state==NOTIFYACTIVITY && !_monitorActivity ) {
484
 
        state = NOTIFYNORMAL;
485
 
    }
486
 
    if ( state==NOTIFYSILENCE && !_monitorSilence ) {
487
 
        state = NOTIFYNORMAL;
488
 
    }
489
 
 
490
 
    emit stateChanged(state);
491
 
}
492
 
 
493
 
void Session::onViewSizeChange(int /*height*/, int /*width*/)
494
 
{
495
 
    updateTerminalSize();
496
 
}
497
 
void Session::onEmulationSizeChange(int lines , int columns)
498
 
{
499
 
    setSize( QSize(lines,columns) );
500
 
}
501
 
 
502
 
void Session::updateTerminalSize()
503
 
{
504
 
    QListIterator<KTerminalDisplay *> viewIter(_views);
505
 
 
506
 
    int minLines = -1;
507
 
    int minColumns = -1;
508
 
 
509
 
    // minimum number of lines and columns that views require for
510
 
    // their size to be taken into consideration ( to avoid problems
511
 
    // with new view widgets which haven't yet been set to their correct size )
512
 
    const int VIEW_LINES_THRESHOLD = 2;
513
 
    const int VIEW_COLUMNS_THRESHOLD = 2;
514
 
 
515
 
    //select largest number of lines and columns that will fit in all visible views
516
 
    while ( viewIter.hasNext() ) {
517
 
        KTerminalDisplay * view = viewIter.next();
518
 
        if ( view->lines() >= VIEW_LINES_THRESHOLD &&
519
 
                view->columns() >= VIEW_COLUMNS_THRESHOLD ) {
520
 
            minLines = (minLines == -1) ? view->lines() : qMin( minLines , view->lines() );
521
 
            minColumns = (minColumns == -1) ? view->columns() : qMin( minColumns , view->columns() );
522
 
        }
523
 
    }
524
 
 
525
 
    // backend emulation must have a _terminal of at least 1 column x 1 line in size
526
 
    if ( minLines > 0 && minColumns > 0 ) {
527
 
        _emulation->setImageSize( minLines , minColumns );
528
 
        _shellProcess->setWindowSize( minLines , minColumns );
529
 
    }
530
 
}
531
 
 
532
 
void Session::refresh()
533
 
{
534
 
    // attempt to get the shell process to redraw the display
535
 
    //
536
 
    // this requires the program running in the shell
537
 
    // to cooperate by sending an update in response to
538
 
    // a window size change
539
 
    //
540
 
    // the window size is changed twice, first made slightly larger and then
541
 
    // resized back to its normal size so that there is actually a change
542
 
    // in the window size (some shells do nothing if the
543
 
    // new and old sizes are the same)
544
 
    //
545
 
    // if there is a more 'correct' way to do this, please
546
 
    // send an email with method or patches to konsole-devel@kde.org
547
 
 
548
 
    const QSize existingSize = _shellProcess->windowSize();
549
 
    _shellProcess->setWindowSize(existingSize.height(),existingSize.width()+1);
550
 
    _shellProcess->setWindowSize(existingSize.height(),existingSize.width());
551
 
}
552
 
 
553
 
bool Session::sendSignal(int signal)
554
 
{
555
 
    int result = ::kill(_shellProcess->pid(),signal);
556
 
 
557
 
     if ( result == 0 )
558
 
     {
559
 
         _shellProcess->waitForFinished();
560
 
         return true;
561
 
     }
562
 
     else
563
 
         return false;
564
 
}
565
 
 
566
 
void Session::close()
567
 
{
568
 
    _autoClose = true;
569
 
    _wantedClose = true;
570
 
    if (!_shellProcess->isRunning() || !sendSignal(SIGHUP)) {
571
 
        // Forced close.
572
 
        QTimer::singleShot(1, this, SIGNAL(finished()));
573
 
    }
574
 
}
575
 
 
576
 
void Session::sendText(const QString &text) const
577
 
{
578
 
    _emulation->sendText(text);
579
 
}
580
 
 
581
 
void Session::sendKey(QKeyEvent *key)
582
 
{
583
 
    _emulation->sendKeyEvent(key);
584
 
}
585
 
 
586
 
Session::~Session()
587
 
{
588
 
    delete _emulation;
589
 
    delete _shellProcess;
590
 
//  delete _zmodemProc;
591
 
}
592
 
 
593
 
void Session::setProfileKey(const QString & key)
594
 
{
595
 
    _profileKey = key;
596
 
    emit profileChanged(key);
597
 
}
598
 
QString Session::profileKey() const
599
 
{
600
 
    return _profileKey;
601
 
}
602
 
 
603
 
void Session::done(int exitStatus)
604
 
{
605
 
    if (!_autoClose) {
606
 
        _userTitle = ("This session is done. Finished");
607
 
        emit titleChanged();
608
 
        return;
609
 
    }
610
 
 
611
 
    QString message;
612
 
    if (!_wantedClose || exitStatus != 0) {
613
 
 
614
 
        if (_shellProcess->exitStatus() == QProcess::NormalExit) {
615
 
            message.sprintf("Session '%s' exited with status %d.",
616
 
                          _nameTitle.toLatin1().data(), exitStatus);
617
 
        } else {
618
 
            message.sprintf("Session '%s' crashed.",
619
 
                          _nameTitle.toLatin1().data());
620
 
        }
621
 
    }
622
 
 
623
 
    if ( !_wantedClose && _shellProcess->exitStatus() != QProcess::NormalExit )
624
 
        message.sprintf("Session '%s' exited unexpectedly.",
625
 
                        _nameTitle.toLatin1().data());
626
 
    else
627
 
        emit finished();
628
 
 
629
 
}
630
 
 
631
 
Emulation * Session::emulation() const
632
 
{
633
 
    return _emulation;
634
 
}
635
 
 
636
 
QString Session::keyBindings() const
637
 
{
638
 
    return _emulation->keyBindings();
639
 
}
640
 
 
641
 
QStringList Session::environment() const
642
 
{
643
 
    return _environment;
644
 
}
645
 
 
646
 
void Session::setEnvironment(const QStringList & environment)
647
 
{
648
 
    _environment = environment;
649
 
}
650
 
 
651
 
int Session::sessionId() const
652
 
{
653
 
    return _sessionId;
654
 
}
655
 
 
656
 
void Session::setKeyBindings(const QString & id)
657
 
{
658
 
    _emulation->setKeyBindings(id);
659
 
}
660
 
 
661
 
void Session::setTitle(TitleRole role , const QString & newTitle)
662
 
{
663
 
    if ( title(role) != newTitle ) {
664
 
        if ( role == NameRole ) {
665
 
            _nameTitle = newTitle;
666
 
        } else if ( role == DisplayedTitleRole ) {
667
 
            _displayTitle = newTitle;
668
 
        }
669
 
 
670
 
        emit titleChanged();
671
 
    }
672
 
}
673
 
 
674
 
QString Session::title(TitleRole role) const
675
 
{
676
 
    if ( role == NameRole ) {
677
 
        return _nameTitle;
678
 
    } else if ( role == DisplayedTitleRole ) {
679
 
        return _displayTitle;
680
 
    } else {
681
 
        return QString();
682
 
    }
683
 
}
684
 
 
685
 
void Session::setIconName(const QString & iconName)
686
 
{
687
 
    if ( iconName != _iconName ) {
688
 
        _iconName = iconName;
689
 
        emit titleChanged();
690
 
    }
691
 
}
692
 
 
693
 
void Session::setIconText(const QString & iconText)
694
 
{
695
 
    _iconText = iconText;
696
 
    //kDebug(1211)<<"Session setIconText " <<  _iconText;
697
 
}
698
 
 
699
 
QString Session::iconName() const
700
 
{
701
 
    return _iconName;
702
 
}
703
 
 
704
 
QString Session::iconText() const
705
 
{
706
 
    return _iconText;
707
 
}
708
 
 
709
 
void Session::setHistoryType(const HistoryType & hType)
710
 
{
711
 
    _emulation->setHistory(hType);
712
 
}
713
 
 
714
 
const HistoryType & Session::historyType() const
715
 
{
716
 
    return _emulation->history();
717
 
}
718
 
 
719
 
void Session::clearHistory()
720
 
{
721
 
    _emulation->clearHistory();
722
 
}
723
 
 
724
 
QStringList Session::arguments() const
725
 
{
726
 
    return _arguments;
727
 
}
728
 
 
729
 
QString Session::program() const
730
 
{
731
 
    return _program;
732
 
}
733
 
 
734
 
// unused currently
735
 
bool Session::isMonitorActivity() const
736
 
{
737
 
    return _monitorActivity;
738
 
}
739
 
// unused currently
740
 
bool Session::isMonitorSilence()  const
741
 
{
742
 
    return _monitorSilence;
743
 
}
744
 
 
745
 
void Session::setMonitorActivity(bool _monitor)
746
 
{
747
 
    _monitorActivity=_monitor;
748
 
    _notifiedActivity=false;
749
 
 
750
 
    activityStateSet(NOTIFYNORMAL);
751
 
}
752
 
 
753
 
void Session::setMonitorSilence(bool _monitor)
754
 
{
755
 
    if (_monitorSilence==_monitor) {
756
 
        return;
757
 
    }
758
 
 
759
 
    _monitorSilence=_monitor;
760
 
    if (_monitorSilence) {
761
 
        _monitorTimer->start(_silenceSeconds*1000);
762
 
    } else {
763
 
        _monitorTimer->stop();
764
 
    }
765
 
 
766
 
    activityStateSet(NOTIFYNORMAL);
767
 
}
768
 
 
769
 
void Session::setMonitorSilenceSeconds(int seconds)
770
 
{
771
 
    _silenceSeconds=seconds;
772
 
    if (_monitorSilence) {
773
 
        _monitorTimer->start(_silenceSeconds*1000);
774
 
    }
775
 
}
776
 
 
777
 
void Session::setAddToUtmp(bool set)
778
 
{
779
 
    _addToUtmp = set;
780
 
}
781
 
 
782
 
void Session::setFlowControlEnabled(bool enabled)
783
 
{
784
 
    if (_flowControl == enabled) {
785
 
        return;
786
 
    }
787
 
 
788
 
    _flowControl = enabled;
789
 
 
790
 
    if (_shellProcess) {
791
 
        _shellProcess->setFlowControlEnabled(_flowControl);
792
 
    }
793
 
 
794
 
    emit flowControlEnabledChanged(enabled);
795
 
}
796
 
bool Session::flowControlEnabled() const
797
 
{
798
 
    return _flowControl;
799
 
}
800
 
//void Session::fireZModemDetected()
801
 
//{
802
 
//  if (!_zmodemBusy)
803
 
//  {
804
 
//    QTimer::singleShot(10, this, SIGNAL(zmodemDetected()));
805
 
//    _zmodemBusy = true;
806
 
//  }
807
 
//}
808
 
 
809
 
//void Session::cancelZModem()
810
 
//{
811
 
//  _shellProcess->sendData("\030\030\030\030", 4); // Abort
812
 
//  _zmodemBusy = false;
813
 
//}
814
 
 
815
 
//void Session::startZModem(const QString &zmodem, const QString &dir, const QStringList &list)
816
 
//{
817
 
//  _zmodemBusy = true;
818
 
//  _zmodemProc = new KProcess();
819
 
//  _zmodemProc->setOutputChannelMode( KProcess::SeparateChannels );
820
 
//
821
 
//  *_zmodemProc << zmodem << "-v" << list;
822
 
//
823
 
//  if (!dir.isEmpty())
824
 
//     _zmodemProc->setWorkingDirectory(dir);
825
 
//
826
 
//  _zmodemProc->start();
827
 
//
828
 
//  connect(_zmodemProc,SIGNAL (readyReadStandardOutput()),
829
 
//          this, SLOT(zmodemReadAndSendBlock()));
830
 
//  connect(_zmodemProc,SIGNAL (readyReadStandardError()),
831
 
//          this, SLOT(zmodemReadStatus()));
832
 
//  connect(_zmodemProc,SIGNAL (finished(int,QProcess::ExitStatus)),
833
 
//          this, SLOT(zmodemFinished()));
834
 
//
835
 
//  disconnect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(onReceiveBlock(const char*,int)) );
836
 
//  connect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(zmodemRcvBlock(const char*,int)) );
837
 
//
838
 
//  _zmodemProgress = new ZModemDialog(QApplication::activeWindow(), false,
839
 
//                                    i18n("ZModem Progress"));
840
 
//
841
 
//  connect(_zmodemProgress, SIGNAL(user1Clicked()),
842
 
//          this, SLOT(zmodemDone()));
843
 
//
844
 
//  _zmodemProgress->show();
845
 
//}
846
 
 
847
 
/*void Session::zmodemReadAndSendBlock()
848
 
{
849
 
  _zmodemProc->setReadChannel( QProcess::StandardOutput );
850
 
  QByteArray data = _zmodemProc->readAll();
851
 
 
852
 
  if ( data.count() == 0 )
853
 
      return;
854
 
 
855
 
  _shellProcess->sendData(data.constData(),data.count());
856
 
}
857
 
*/
858
 
/*
859
 
void Session::zmodemReadStatus()
860
 
{
861
 
  _zmodemProc->setReadChannel( QProcess::StandardError );
862
 
  QByteArray msg = _zmodemProc->readAll();
863
 
  while(!msg.isEmpty())
864
 
  {
865
 
     int i = msg.indexOf('\015');
866
 
     int j = msg.indexOf('\012');
867
 
     QByteArray txt;
868
 
     if ((i != -1) && ((j == -1) || (i < j)))
869
 
     {
870
 
       msg = msg.mid(i+1);
871
 
     }
872
 
     else if (j != -1)
873
 
     {
874
 
       txt = msg.left(j);
875
 
       msg = msg.mid(j+1);
876
 
     }
877
 
     else
878
 
     {
879
 
       txt = msg;
880
 
       msg.truncate(0);
881
 
     }
882
 
     if (!txt.isEmpty())
883
 
       _zmodemProgress->addProgressText(QString::fromLocal8Bit(txt));
884
 
  }
885
 
}
886
 
*/
887
 
/*
888
 
void Session::zmodemRcvBlock(const char *data, int len)
889
 
{
890
 
  QByteArray ba( data, len );
891
 
 
892
 
  _zmodemProc->write( ba );
893
 
}
894
 
*/
895
 
/*
896
 
void Session::zmodemFinished()
897
 
{
898
 
  if (_zmodemProc)
899
 
  {
900
 
    delete _zmodemProc;
901
 
    _zmodemProc = 0;
902
 
    _zmodemBusy = false;
903
 
 
904
 
    disconnect( _shellProcess,SIGNAL(block_in(const char*,int)), this ,SLOT(zmodemRcvBlock(const char*,int)) );
905
 
    connect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(onReceiveBlock(const char*,int)) );
906
 
 
907
 
    _shellProcess->sendData("\030\030\030\030", 4); // Abort
908
 
    _shellProcess->sendData("\001\013\n", 3); // Try to get prompt back
909
 
    _zmodemProgress->transferDone();
910
 
  }
911
 
}
912
 
*/
913
 
void Session::onReceiveBlock( const char * buf, int len )
914
 
{
915
 
    _emulation->receiveData( buf, len );
916
 
    emit receivedData( QString::fromLatin1( buf, len ) );
917
 
}
918
 
 
919
 
QSize Session::size()
920
 
{
921
 
    return _emulation->imageSize();
922
 
}
923
 
 
924
 
void Session::setSize(const QSize & size)
925
 
{
926
 
    if ((size.width() <= 1) || (size.height() <= 1)) {
927
 
        return;
928
 
    }
929
 
 
930
 
    emit resizeRequest(size);
931
 
}
932
 
int Session::foregroundProcessId() const
933
 
{
934
 
    return _shellProcess->foregroundProcessGroup();
935
 
}
936
 
int Session::processId() const
937
 
{
938
 
    return _shellProcess->pid();
939
 
}
940
 
 
941
 
SessionGroup::SessionGroup()
942
 
        : _masterMode(0)
943
 
{
944
 
}
945
 
SessionGroup::~SessionGroup()
946
 
{
947
 
    // disconnect all
948
 
    connectAll(false);
949
 
}
950
 
int SessionGroup::masterMode() const
951
 
{
952
 
    return _masterMode;
953
 
}
954
 
QList<Session *> SessionGroup::sessions() const
955
 
{
956
 
    return _sessions.keys();
957
 
}
958
 
bool SessionGroup::masterStatus(Session * session) const
959
 
{
960
 
    return _sessions[session];
961
 
}
962
 
 
963
 
void SessionGroup::addSession(Session * session)
964
 
{
965
 
    _sessions.insert(session,false);
966
 
 
967
 
    QListIterator<Session *> masterIter(masters());
968
 
 
969
 
    while ( masterIter.hasNext() ) {
970
 
        connectPair(masterIter.next(),session);
971
 
    }
972
 
}
973
 
void SessionGroup::removeSession(Session * session)
974
 
{
975
 
    setMasterStatus(session,false);
976
 
 
977
 
    QListIterator<Session *> masterIter(masters());
978
 
 
979
 
    while ( masterIter.hasNext() ) {
980
 
        disconnectPair(masterIter.next(),session);
981
 
    }
982
 
 
983
 
    _sessions.remove(session);
984
 
}
985
 
void SessionGroup::setMasterMode(int mode)
986
 
{
987
 
    _masterMode = mode;
988
 
 
989
 
    connectAll(false);
990
 
    connectAll(true);
991
 
}
992
 
QList<Session *> SessionGroup::masters() const
993
 
{
994
 
    return _sessions.keys(true);
995
 
}
996
 
void SessionGroup::connectAll(bool connect)
997
 
{
998
 
    QListIterator<Session *> masterIter(masters());
999
 
 
1000
 
    while ( masterIter.hasNext() ) {
1001
 
        Session * master = masterIter.next();
1002
 
 
1003
 
        QListIterator<Session *> otherIter(_sessions.keys());
1004
 
        while ( otherIter.hasNext() ) {
1005
 
            Session * other = otherIter.next();
1006
 
 
1007
 
            if ( other != master ) {
1008
 
                if ( connect ) {
1009
 
                    connectPair(master,other);
1010
 
                } else {
1011
 
                    disconnectPair(master,other);
1012
 
                }
1013
 
            }
1014
 
        }
1015
 
    }
1016
 
}
1017
 
void SessionGroup::setMasterStatus(Session * session, bool master)
1018
 
{
1019
 
    bool wasMaster = _sessions[session];
1020
 
    _sessions[session] = master;
1021
 
 
1022
 
    if ((!wasMaster && !master)
1023
 
            || (wasMaster && master)) {
1024
 
        return;
1025
 
    }
1026
 
 
1027
 
    QListIterator<Session *> iter(_sessions.keys());
1028
 
    while (iter.hasNext()) {
1029
 
        Session * other = iter.next();
1030
 
 
1031
 
        if (other != session) {
1032
 
            if (master) {
1033
 
                connectPair(session, other);
1034
 
            } else {
1035
 
                disconnectPair(session, other);
1036
 
            }
1037
 
        }
1038
 
    }
1039
 
}
1040
 
 
1041
 
void SessionGroup::connectPair(Session * master , Session * other)
1042
 
{
1043
 
//    qDebug() << k_funcinfo;
1044
 
 
1045
 
    if ( _masterMode & CopyInputToAll ) {
1046
 
        qDebug() << "Connection session " << master->nameTitle() << "to" << other->nameTitle();
1047
 
 
1048
 
        connect( master->emulation() , SIGNAL(sendData(const char *,int)) , other->emulation() ,
1049
 
                 SLOT(sendString(const char *,int)) );
1050
 
    }
1051
 
}
1052
 
void SessionGroup::disconnectPair(Session * master , Session * other)
1053
 
{
1054
 
//    qDebug() << k_funcinfo;
1055
 
 
1056
 
    if ( _masterMode & CopyInputToAll ) {
1057
 
        qDebug() << "Disconnecting session " << master->nameTitle() << "from" << other->nameTitle();
1058
 
 
1059
 
        disconnect( master->emulation() , SIGNAL(sendData(const char *,int)) , other->emulation() ,
1060
 
                    SLOT(sendString(const char *,int)) );
1061
 
    }
1062
 
}
1063
 
 
1064
 
//#include "moc_Session.cpp"