File: wxterminal.cpp

package info (click to toggle)
codelite 6.1.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 48,992 kB
  • ctags: 43,502
  • sloc: cpp: 334,263; ansic: 18,441; xml: 4,713; yacc: 2,653; lex: 2,449; python: 1,188; sh: 385; makefile: 40
file content (377 lines) | stat: -rw-r--r-- 11,033 bytes parent folder | download
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
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2014 The CodeLite Team
// file name            : wxterminal.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    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.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

#include "wxterminal.h"
#include "asyncprocess.h"
#include <wx/filename.h>
#include <wx/app.h>
#include "processreaderthread.h"
#include "drawingutils.h"

#define OUTPUT_BUFFER_MAX_SIZE 1024*1024 /* 1MB of buffer */

#ifdef __WXMSW__
#include "windows.h"
#define SHELL_PREFIX  wxT("cmd /c ")
#define SHELL_WRAPPER wxT("\"")
#else

#if defined(__WXMAC__) || defined(__FreeBSD__)
#include <sys/wait.h>
#else
#include <wait.h>
#endif

#include <signal.h>
#define SHELL_PREFIX  wxT("/bin/sh -c ")
#define SHELL_WRAPPER wxT("'")
#endif

#if defined(__WXGTK__)
#ifdef __FreeBSD__
#    include <sys/ioctl.h>
#    include <termios.h>
#    include <libutil.h>
#else
#    include <pty.h>
#endif
#    include "unixprocess_impl.h"
#elif defined(__WXMAC__)
#    include <util.h>
#    include "unixprocess_impl.h"
#endif

static wxString WrapInShell(const wxString &cmd)
{
    wxString shellCommand;
    shellCommand << SHELL_PREFIX << SHELL_WRAPPER << cmd << SHELL_WRAPPER;
    return shellCommand;
}

//-------------------------------------------------------------
BEGIN_EVENT_TABLE(wxTerminal, wxTerminalBase)
    EVT_COMMAND(wxID_ANY, wxEVT_PROC_DATA_READ,  wxTerminal::OnReadProcessOutput)
    EVT_COMMAND(wxID_ANY, wxEVT_PROC_TERMINATED, wxTerminal::OnProcessEnd       )
    EVT_IDLE(wxTerminal::OnIdle)
END_EVENT_TABLE()

wxTerminal::wxTerminal( wxWindow* parent )
    : wxTerminalBase  ( parent )
    , m_process(NULL)
    , m_exitWhenProcessDies(false)
    , m_exitOnKey(false)
    , m_inferiorEnd(0)
#if defined(__WXMAC__) || defined(__WXGTK__)
    , m_dummyProcess(NULL)
#endif
    , m_interactive(false)
{
    m_defaultStyle.SetFont            ( m_textCtrl->GetFont() );
    m_defaultStyle.SetTextColour      ( DrawingUtils::GetOutputPaneFgColour() );
    m_defaultStyle.SetBackgroundColour( DrawingUtils::GetOutputPaneBgColour());

    m_textCtrl->SetForegroundColour   ( DrawingUtils::GetOutputPaneFgColour() );
    m_textCtrl->SetBackgroundColour   ( DrawingUtils::GetOutputPaneBgColour() );
    m_textCtrl->SetDefaultStyle       ( m_defaultStyle );
    
    wxTheApp->Connect(wxID_CUT,       wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(wxTerminal::OnEdit), NULL, this);
    wxTheApp->Connect(wxID_COPY,      wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(wxTerminal::OnEdit), NULL, this);
    wxTheApp->Connect(wxID_SELECTALL, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(wxTerminal::OnEdit), NULL, this);
}

wxTerminal::~wxTerminal()
{
#if defined(__WXMAC__) || defined(__WXGTK__)
    StopTTY();
#endif

    wxTheApp->Disconnect(wxID_CUT,       wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(wxTerminal::OnEdit), NULL, this);
    wxTheApp->Disconnect(wxID_COPY,      wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(wxTerminal::OnEdit), NULL, this);
    wxTheApp->Disconnect(wxID_SELECTALL, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(wxTerminal::OnEdit), NULL, this);
}

void wxTerminal::OnText( wxCommandEvent& event )
{
    event.Skip();
}

void wxTerminal::OnEnter( wxCommandEvent& event )
{
    event.Skip();
    if ( m_interactive ) {
        wxString lineText = m_textCtrl->GetRange(m_inferiorEnd, m_textCtrl->GetInsertionPoint());
        lineText.Trim().Trim(false);
        DoProcessCommand(lineText);
    }
}

void wxTerminal::OnURL( wxTextUrlEvent& event )
{
    event.Skip();
}

void wxTerminal::OnKey(wxKeyEvent& event)
{
    // We don't want to allow much editing in the textctrl, but it's nice to let the DEL key delete the selection
    if ((event.GetKeyCode() == WXK_DELETE) && (m_textCtrl->HasSelection())) {
            m_textCtrl->Cut(); // which is close enough for our purposes
            return;
    }

    long curPos = m_textCtrl->GetInsertionPoint();
    if(curPos < m_inferiorEnd) {
        int keyCode = event.GetKeyCode();
        // Dont allow any key down when
        switch(keyCode) {
        case WXK_UP:
        case WXK_DOWN:
        case WXK_LEFT:
        case WXK_RIGHT:
        case WXK_NUMPAD_UP:
        case WXK_NUMPAD_DOWN:
        case WXK_NUMPAD_LEFT:
        case WXK_NUMPAD_RIGHT:
            event.Skip();
            break;

        case WXK_RETURN:
        case WXK_NUMPAD_ENTER:
            event.Skip();
            break;

        default:
            break;
        }

        return;
    }


#ifndef __WXMSW__
    if(m_dummyProcess) {
        switch(event.GetKeyCode()) {
        case WXK_NUMPAD_ENTER:
        case WXK_RETURN: {
            // get last line and pass it to the caller
            wxString lineText = m_textCtrl->GetRange(m_inferiorEnd, curPos);
            lineText.Trim().Trim(false);
            m_dummyProcess->Write(lineText);
            break;
        }
        }
    }
#endif
    event.Skip();
}

void wxTerminal::OnEdit(wxCommandEvent& event)
{
    if (wxWindow::FindFocus() != m_textCtrl) {
        event.Skip();
        return;
    }

    switch (event.GetId()) {
        case wxID_COPY:
            m_textCtrl->Copy();
            break;
        case wxID_CUT:
            m_textCtrl->Cut();
            break;
        case wxID_SELECTALL:
            m_textCtrl->SelectAll();
            break;
        default:
            event.Skip();
    }
}

void wxTerminal::OnProcessEnd(wxCommandEvent& event)
{
    ProcessEventData *ped = (ProcessEventData *)event.GetClientData();
    delete ped;
    wxDELETE(m_process);
    
    // Make sure we flush everything
    DoFlushOutputBuffer();

    if(m_exitWhenProcessDies) {
        m_textCtrl->SetInsertionPointEnd();
        m_textCtrl->AppendText(wxString(wxT("\n")) +_("Press any key to continue..."));
        m_exitOnKey = true;
    }
}

void wxTerminal::OnReadProcessOutput(wxCommandEvent& event)
{
    ProcessEventData *ped = (ProcessEventData *)event.GetClientData();
    m_outputBuffer << ped->GetData();
    wxDELETE(ped);
    
    // Incase we hit the limit of the output buffer, flush it now
    // if ( m_outputBuffer.length() > OUTPUT_BUFFER_MAX_SIZE ) {
    //     DoFlushOutputBuffer();
    // }
}

void wxTerminal::DoCtrlC()
{
    if(!m_process)
        return;

#ifdef __WXMSW__
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD) m_process->GetPid());
    if(hProcess) {
        TerminateProcess(hProcess, 0);
        CloseHandle(  hProcess );
    }
#else
    //int status(0); Commented out as 'Unused variable'
    wxKill(m_process->GetPid(), wxSIGKILL, NULL, wxKILL_CHILDREN);
#endif
}

void wxTerminal::Execute(const wxString& command, bool exitWhenDone, const wxString &workingDir)
{
    if(m_process)
        return;

    m_textCtrl->Clear();

    // restore default style
    m_textCtrl->SetDefaultStyle( m_defaultStyle );
    m_textCtrl->SetFocus();

    m_exitWhenProcessDies = exitWhenDone;
    m_workingDir          = workingDir;
    DoProcessCommand(command);
}

void wxTerminal::DoProcessCommand(const wxString& command)
{
    wxString cmd ( command );
    cmd.Trim().Trim(false);
    wxString path;
    // Add the shell prefix
    wxString cmdShell = WrapInShell(cmd);
    // real command
    IProcess *cmdPrc = CreateAsyncProcess(this, cmdShell, IProcessCreateWithHiddenConsole, m_workingDir);
    if( cmdPrc ) {
        m_process = cmdPrc;

    } else {
        m_process = NULL;
        m_textCtrl->SetInsertionPointEnd();
        m_textCtrl->AppendText(wxString::Format(_("Failed to execute command: %s\nWorking Directory: %s\n"), cmdShell.c_str(), m_workingDir.c_str()));

        if(m_exitWhenProcessDies) {
            m_textCtrl->SetInsertionPointEnd();
            m_textCtrl->AppendText(wxString(wxT("\n")) +_("Press any key to continue..."));
            m_exitOnKey = true;
        }
    }
}

void wxTerminal::KillInferior()
{
    DoCtrlC();
}

bool wxTerminal::IsRunning()
{
    return m_process != NULL;
}

void wxTerminal::Clear()
{
    m_textCtrl->Clear();
}

#if defined(__WXGTK__)||defined(__WXMAC__)
wxString wxTerminal::StartTTY()
{
    m_process = NULL;
    // Open the master side of a pseudo terminal
    int master = ::posix_openpt (O_RDWR|O_NOCTTY);
    if (master < 0) {
        return "";
    }

    // Grant access to the slave pseudo terminal
    if (::grantpt (master) < 0) {
        ::close(master);
        return "";
    }

    // Clear the lock flag on the slave pseudo terminal
    if (::unlockpt (master) < 0) {
        ::close(master);
        return "";
    }
    
    m_tty = ::ptsname(master);
    
    // disable ECHO
    struct termios termio;
    tcgetattr(master, &termio);
    termio.c_lflag = ICANON;
    termio.c_oflag = ONOCR | ONLRET;
    tcsetattr(master, TCSANOW, &termio);

    // Start a listener on the tty
    m_dummyProcess = new UnixProcessImpl(this);
    static_cast<UnixProcessImpl*>(m_dummyProcess)->SetReadHandle  (master);
    static_cast<UnixProcessImpl*>(m_dummyProcess)->SetWriteHandler(master);
    static_cast<UnixProcessImpl*>(m_dummyProcess)->SetPid(wxNOT_FOUND);
    static_cast<UnixProcessImpl*>(m_dummyProcess)->StartReaderThread();
    return m_tty;
}

void wxTerminal::StopTTY()
{
    wxDELETE(m_dummyProcess);
    m_tty.Clear();
    // close(m_slave);
    // m_slave = -1;
}

#endif

void wxTerminal::OnIdle(wxIdleEvent& event)
{
    event.Skip();
    DoFlushOutputBuffer();
}

void wxTerminal::DoFlushOutputBuffer()
{
    if ( !m_outputBuffer.IsEmpty() ) {
        m_textCtrl->SetInsertionPointEnd();
        m_textCtrl->AppendText( m_outputBuffer );
        m_textCtrl->SetSelection(m_textCtrl->GetLastPosition(), m_textCtrl->GetLastPosition());
        m_inferiorEnd = m_textCtrl->GetLastPosition();
        m_outputBuffer.Clear();
    }
}