summaryrefslogtreecommitdiffstats
path: root/client/browser/src/mainwindow.cpp
blob: 1d89a1a88b7784e7d3541776152185c2c101a523 (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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#include "mainwindow.h"
#include <QtWebKit>
#include <QStringList>
#include <QWebView>
#include <QDockWidget>
#include <QtDebug>
#include <QWebPage>
#include <QProcess>
#include <QTextEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QDateTime>
#include <QProgressBar>
#include <QTabWidget>
#include <QLineEdit>
#include <QNetworkReply>
#include <QSslError>
#include <QTimer>
#include <libintl.h>

#include "qtermwidget.h"
#include "digitalclock.h"

#define BUFFERSIZE 2048
#define REGEXP_STRING "^\\[(\\d+)\\]"

#define CURRENT_TIME() QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss")

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),m_web(new QWebView()),m_output(new QTextEdit()),
      m_process(new QProcess(this)),
      m_logfile(0),m_logstream(0),m_numberTerminal(0)
{
    // Graphic
    showFullScreen();
    setWindowTitle(tr("OpenGnsys Browser"));
    setCentralWidget(m_web);
    readEnvironmentValues();

    // Open the log file for append
    if(m_env.contains("OGLOGFILE") && m_env["OGLOGFILE"]!="")
    {
        QFile* m_logfile=new QFile(m_env["OGLOGFILE"]);
        if(!m_logfile->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
        {
            delete m_logfile;
            print(tr(gettext("El fichero de log no ha podido ser abierto: "))+m_env["OGLOGFILE"]+".");
        }
        else
        {
            m_logstream=new QTextStream(m_logfile);
        }
    }

    // Output
    m_output->setReadOnly(true);
    m_output->setFontPointSize(16);

    // Button Dock
    QDockWidget* dock=new QDockWidget();
    dock->setAllowedAreas(Qt::BottomDockWidgetArea);
    QWidget* dummy=new QWidget();
    dummy->setMaximumHeight(0);
    dock->setTitleBarWidget(dummy);

    // TabWidget
    m_tabs=new QTabWidget(dock);
    QPushButton *button=new QPushButton(tr(gettext("&Nueva Terminal")));
    button->setFocusPolicy(Qt::TabFocus);
    m_tabs->setCornerWidget(button);
    m_tabs->setFocusPolicy(Qt::NoFocus);
    m_tabs->addTab(m_output,tr(gettext("Salida")));
    slotCreateTerminal();
    // Assign tabs to dock
    dock->setWidget(m_tabs);
    // Assign tabs dock to the mainwindow if admin mode is active
    if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true")
        addDockWidget(Qt::BottomDockWidgetArea,dock);

    // Top Dock
    dock=new QDockWidget();
    dock->setAllowedAreas(Qt::TopDockWidgetArea);
    QWidget* dummy2=new QWidget();
    dummy2->setMaximumHeight(0);
    dock->setTitleBarWidget(dummy2);
    // WebBar
    m_webBar=new QLineEdit(dock);
    // WebBar to dock
    dock->setWidget(m_webBar);
    // Assign top dock to the mainwindow if admin mode is active
    if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true")
        addDockWidget(Qt::TopDockWidgetArea,dock);

    // Status bar
    QStatusBar* st=statusBar();
    st->setSizeGripEnabled(false);
    // OpenGnsys logo (or alternate text)
    m_logo=new QLabel();
    QPixmap logo;
    if(logo.load("/opt/opengnsys/lib/pictures/oglogo.png"))
        m_logo->setPixmap(logo);
    else
        m_logo->setText("OG");
    m_logo->setToolTip(tr(gettext("Proyecto OpenGnsys"))+"\nhttps://opengnsys.es");
    // Progress bar
    m_progressBar=new QProgressBar(this);
    m_progressBar->setRange(0,100);
    // Connection speed
    QString speed=readSpeed();
    m_speedInfo=new QLabel(speed);
    m_speedInfo->setAlignment(Qt::AlignCenter);
    if(m_env.contains("DEFAULTSPEED") && m_env["DEFAULTSPEED"]!="")
        if(speed.compare(m_env["DEFAULTSPEED"])!=0)
            m_speedInfo->setStyleSheet("background-color: darkred; color: white; font-weight: bold;");
    // Clock
    m_clock=new DigitalClock(this);

    m_web->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    // Web signals
    connect(m_web,SIGNAL(linkClicked(const QUrl&)),this,
            SLOT(slotLinkHandle(const QUrl&)));
    connect(m_web,SIGNAL(loadStarted()),this,SLOT(slotWebLoadStarted()));
    connect(m_web,SIGNAL(loadFinished(bool)),this,SLOT(slotWebLoadFinished(bool)));
    connect(m_web,SIGNAL(loadProgress(int)),this,SLOT(slotWebLoadProgress(int)));
    connect(m_web,SIGNAL(urlChanged(const QUrl&)),this,SLOT(slotUrlChanged(const QUrl&)));
    // Ignore SSL errors.
    connect(m_web->page()->networkAccessManager(),
            SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> &)), this,
            SLOT(slotSslErrors(QNetworkReply*)));

    // Process signals
    connect(m_process,SIGNAL(started()),this,SLOT(slotProcessStarted()));
    connect(m_process,SIGNAL(finished(int,QProcess::ExitStatus)),
            this,SLOT(slotProcessFinished(int,QProcess::ExitStatus)));
    connect(m_process,SIGNAL(error(QProcess::ProcessError)),
            this,SLOT(slotProcessError(QProcess::ProcessError)));
    connect(m_process,SIGNAL(readyReadStandardOutput()),this,SLOT(slotProcessOutput()));
    connect(m_process,SIGNAL(readyReadStandardError()),
            this,SLOT(slotProcessErrorOutput()));

    // Dock signals
    connect(button,SIGNAL(clicked()),this,SLOT(slotCreateTerminal()));
    connect(m_webBar,SIGNAL(returnPressed()),this,SLOT(slotWebBarReturnPressed()));

    QStringList arguments=QCoreApplication::arguments();
    m_webBar->setText(arguments[1]);
    m_web->load(QUrl(arguments[1]));
}

MainWindow::~MainWindow()
{
    if(m_logfile)
    {
        m_logfile->close();
        delete m_logfile;
    }
    if(m_logstream)
        delete m_logstream;
}

void MainWindow::slotLinkHandle(const QUrl &url)
{
    // Check if it's executing another process
    if(m_process->state() != QProcess::NotRunning)
    {
        print(tr(gettext("Hay otro proceso en ejecución. Por favor espere.")));
        return;
    }
    QString urlString = url.toString();
    QString urlScheme = url.scheme();
    // Clear the output widget for a normal user
    if(! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true")
    {
        m_output->clear();
    }
    if(urlScheme == COMMAND_CONFIRM || urlScheme == COMMAND_CONFIRM_OUTPUT ||
       urlScheme == COMMAND_OUTPUT_CONFIRM || urlScheme == COMMAND_WITH_CONFIRMATION)
    {
        // For all command with confirmation links, show a popup box
        QMessageBox msgBox;
        msgBox.setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint);
        msgBox.setWindowTitle(tr(gettext("AVISO")));
        msgBox.setIcon(QMessageBox::Question);
        msgBox.setTextFormat(Qt::RichText);
        msgBox.setText(tr(gettext("La siguiente acci&oacute;n puede modificar datos o tardar varios minutos. El equipo no podr&aacute; ser utilizado durante su ejecuci&oacute;n.")));
        QPushButton *execButton = msgBox.addButton(tr(gettext("Ejecutar")), QMessageBox::ActionRole);
        msgBox.addButton(tr(gettext("Cancelar")), QMessageBox::RejectRole);
        msgBox.setDefaultButton(execButton);
        msgBox.exec();
        // Continue if user press the execution button
        if (msgBox.clickedButton() == execButton)
        {
            // For command with confirmation and output link, show an output window to non-admin user
            if((urlScheme == COMMAND_CONFIRM_OUTPUT || urlScheme == COMMAND_OUTPUT_CONFIRM) &&
               (! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true"))
            {
                int w=MainWindow::width(), h=MainWindow::height();
                m_output->setWindowFlags(Qt::Window);
                m_output->move(100, 100);
                m_output->setFixedSize(w*0.8-100, h*0.8-100);
                m_output->show();
            }
            // Execute the command
            executeCommand(urlString.remove(0, urlScheme.length()+1));
        }
    }
    else if(urlScheme == COMMAND || urlScheme == COMMAND_OUTPUT)
    {
        // For command with output link, show an output window to non-admin user
        if(urlScheme == COMMAND_OUTPUT &&
           (! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true"))
        {
            int w=MainWindow::width(), h=MainWindow::height();
            m_output->setWindowFlags(Qt::Window);
            m_output->move(100, 100);
            m_output->setFixedSize(w*0.8-100, h*0.8-100);
            m_output->show();
        }
        // Execute the command
        executeCommand(urlString.remove(0, urlScheme.length()+1));
    }
    else
    {
        // For other link, load webpage
        m_web->load(url);
    }
}

void MainWindow::slotWebLoadStarted()
{
    startProgressBar();
    m_progressBar->setFormat(gettext("%p% Cargando"));
}

void MainWindow::slotWebLoadProgress(int progress)
{
    m_progressBar->setValue(progress);
}

void MainWindow::slotWebLoadFinished(bool ok)
{
    // If any error ocurred, show a pop up
    // Sometimes when the url hasn't got a dot, i.e /var/www/pageweb,
    // the return value is always true so we check the bytes received too
    if(ok == false)
    {
        QMessageBox msgBox;
        msgBox.setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint);
        msgBox.setWindowTitle(tr(gettext("AVISO")));
        msgBox.setIcon(QMessageBox::Question);
        msgBox.setTextFormat(Qt::RichText);
        msgBox.setText(tr(gettext("La p&aacute;gina no se puede cargar.")));

        QPushButton *reloadButton = msgBox.addButton(tr(gettext("Recargar")), QMessageBox::ActionRole);
        msgBox.addButton(tr(gettext("Abortar")), QMessageBox::RejectRole);
        msgBox.exec();

        if (msgBox.clickedButton() == reloadButton)
        {
            m_web->reload();
        }
        else
        {
            close();
        }
    }
    else
    {
        finishProgressBar();
    }
}

void MainWindow::slotUrlChanged(const QUrl &url)
{
    m_webBar->setText(url.toString());
}

void MainWindow::slotSslErrors(QNetworkReply* reply)
{
    reply->ignoreSslErrors();
}

void MainWindow::slotProcessStarted()
{
    startProgressBar();
}

void MainWindow::slotProcessOutput()
{
    m_process->setReadChannel(QProcess::StandardOutput);
    char buf[BUFFERSIZE];
    while((m_process->readLine(buf,BUFFERSIZE) > 0))
    {
        QString s(buf);
        if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true")
        {
            m_output->insertPlainText(tr("Proc. stdout: "));
        }
        print(s);
        captureOutputForStatusBar(s);
    }
}

void MainWindow::slotProcessErrorOutput()
{
    m_process->setReadChannel(QProcess::StandardError);
    char buf[BUFFERSIZE];
    while((m_process->readLine(buf,BUFFERSIZE) > 0))
    {
        QString s(buf);
        if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true")
        {
            m_output->insertPlainText(tr("Proc. stderr: "));
        }
        m_output->setTextColor(QColor(Qt::darkBlue));
        print(s);
        m_output->setTextColor(QColor(Qt::black));
    }
}

void MainWindow::slotProcessFinished(int code, QProcess::ExitStatus status)
{
    if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true")
    {
        // Admin user: show process status
        if(status==QProcess::NormalExit)
        {
            if(code > 0)
            {
                m_output->setTextColor(QColor(Qt::darkRed));
            }
            print("\n"+tr(gettext("Fin del proceso. Valor de retorno: "))+QString::number(code));
        }
        else
        {
            m_output->setTextColor(QColor(Qt::darkRed));
            print("\n"+tr(gettext("El proceso ha fallado inesperadamente. Salida: ")+code));
        }
        m_output->setTextColor(QColor(Qt::black));
    }
    else
    {
        // Non-admin user: show instruction to close the popup window
        write(tr(gettext("Fin del proceso. Valor de retorno: "))+QString::number(code));
        m_output->setFontUnderline(true);
        print("\n\n"+tr(gettext("AVISO: Pulsar el botón superior derecho para cerrar"))+" [X]");
        m_output->setFontUnderline(false);
    }
    // On error, show a message box
    if(code > 0 && ! m_output->isActiveWindow())
    {
        showErrorMessage(gettext("Código de salida: ")+QString::number(code));
    }
    finishProgressBar();
}

void MainWindow::slotProcessError(QProcess::ProcessError error)
{
    QString errorMsg;
    switch(error)
    {
        case QProcess::FailedToStart:
            errorMsg=tr(gettext("Imposible lanzar el proceso."));
            break;
        case QProcess::WriteError:
            errorMsg=tr(gettext("Error de escritura en el proceso."));
            break;
        case QProcess::ReadError:
            errorMsg=tr(gettext("Error de lectura del proceso."));
            break;
        // No capturo crashed porque la pillo por finished
        case QProcess::Crashed:
        case QProcess::Timedout:
            break;
        case QProcess::UnknownError:
        default:
            errorMsg=tr(gettext("Error desconocido."));
            break;
    }
    // Print error and show message box with timeout.
    if(!errorMsg.isNull()) {
        m_output->setTextColor(QColor(Qt::darkRed));
        print(errorMsg);
        m_output->setTextColor(QColor(Qt::black));
        showErrorMessage(errorMsg);
    }
    finishProgressBar();
}

void MainWindow::slotCreateTerminal()
{
    QTermWidget* console = new QTermWidget(1,this);
    QFont font = QApplication::font();
    font.setFamily("DejaVu Sans Mono");
    font.setPointSize(12);
    
    console->setTerminalFont(font);
    console->setFocusPolicy(Qt::StrongFocus);
    console->setScrollBarPosition(QTermWidget::ScrollBarRight);

    ++m_numberTerminal;

    connect(console,SIGNAL(finished()),this,SLOT(slotDeleteTerminal()));

    QString name=tr("Term ")+QString::number(m_numberTerminal);
    m_tabs->addTab(console,name);
}

void MainWindow::slotDeleteTerminal()
{
    QWidget *widget = qobject_cast<QWidget *>(sender());
    Q_ASSERT(widget);
    m_tabs->removeTab(m_tabs->indexOf(widget));
    delete widget;
}

void MainWindow::slotWebBarReturnPressed()
{
    QUrl url(m_webBar->text());
    if(url.isValid())
        slotLinkHandle(url);
}

int MainWindow::readEnvironmentValues()
{
    // The return value
    int ret=true;

    // Get all environment variables
    QStringList environmentlist=QProcess::systemEnvironment();
    // This is the list of the important variables
    QStringList variablelist=QString(ENVIRONMENT).split(",");

    // This is an auxiliar variable
    QStringList stringlist;

    foreach (QString str,variablelist)
    {
        // Look for the variable in the environment 
        stringlist=environmentlist.filter(str+"=");

        if(stringlist.isEmpty())
        {
            m_env[str]="";
            ret=false;
        }
        else
        {
            // Get the first element and get the value part
            m_env[str]=(stringlist.first().split("="))[1];
        }
    }

    return ret;
}

// Write a string to the log file
void MainWindow::write(QString s)
{
    if(! s.endsWith("\n"))
        s+="\n";
    if(m_logstream)
    {
        *m_logstream<<CURRENT_TIME()<<": browser: "<<s;
        m_logstream->flush();
    }
}

// Print and log a string
void MainWindow::print(QString s)
{
    if(! s.endsWith("\n"))
        s+="\n";
    write(s);
    if(m_output)
        m_output->insertPlainText(s);
}

// Show message in status bar
void MainWindow::captureOutputForStatusBar(QString output)
{
    // Modify the status bar
    output=output.trimmed();
    // Get percentage (string starts with "[Number]")
    QRegExp regexp(REGEXP_STRING);
    if(regexp.indexIn(output) != -1)
    {
        int pass=regexp.cap(1).toInt();
        output.replace(regexp,"");
        m_progressBar->setValue(pass);
        m_progressBar->setFormat("%p%"+output);
    }
}

// Init status bar
void MainWindow::startProgressBar()
{
    QStatusBar* st=statusBar();
    st->clearMessage();
    st->addWidget(m_logo);
    st->addWidget(m_progressBar,90);
    st->addWidget(m_speedInfo,5);
    st->addWidget(m_clock,5);
    m_progressBar->show();
    m_clock->show();
    m_web->setEnabled(false);
}

// Reset status bar
void MainWindow::finishProgressBar()
{
    m_progressBar->reset();
    m_web->setEnabled(true);
}

// Execute a command
void MainWindow::executeCommand(QString &string)
{
    QStringList list=string.split(" ",QString::SkipEmptyParts);
    QString program=list.takeFirst();
    m_process->setReadChannel(QProcess::StandardOutput);
    // Assign the same Browser's environment to the process
    m_process->setEnvironment(QProcess::systemEnvironment());
    m_process->start(program,list);
    // Only show the command line to admin user
    if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true")
    {
        m_output->setTextColor(QColor(Qt::darkGreen));
        print(tr(gettext("Lanzando el comando: "))+string);
        m_output->setTextColor(QColor(Qt::black));
    }
    else
    {
        write(tr(gettext("Lanzando el comando: "))+string);
    }
    startProgressBar();
}

// Returns communication speed
QString MainWindow::readSpeed() {
    if(m_env.contains("OGLOGFILE"))
    {
        QString infoFile=m_env["OGLOGFILE"].replace(".log", ".info.html");
        QString command="grep -hoe \"[0-9]*Mb/s\" "+infoFile+" 2>/dev/null";
        QProcess process;
        process.start(command);
        process.waitForFinished();
        QString speed(process.readAllStandardOutput());
        return speed.simplified();
    }
    else
    {
        return QString("");
    }
}

// Show an error box with timeout
void MainWindow::showErrorMessage(QString text)
{
    QMessageBox* msgBox=new QMessageBox();
    msgBox->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    msgBox->setWindowTitle(gettext("ERROR"));
    msgBox->setIcon(QMessageBox::Warning);
    msgBox->setText(text);
    msgBox->show();
    QTimer::singleShot(5000, msgBox, SLOT(close()));
}