summaryrefslogtreecommitdiffstats
path: root/src/fbgui/ndgui.cpp
blob: 4e0b3f647c02c0828f29426aa5af70d7fd3b4193 (plain) (blame)
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/**
 * @class ndgui
 *
 * @brief the GUI.
 *
 * This class is responsible for creating and displaying the user interface.
 * It also connects the webView via QWebBridge to javascript functions inside the html files.
 */



#include "ndgui.h"


#include <log4cxx/logger.h>
#include "qlog4cxx.h"

using namespace log4cxx;
using namespace log4cxx::helpers;
LoggerPtr ndLogger(Logger::getLogger("fbgui.nd"));


QString gServerIp("");
bool gAutoUp = true;
QString gSocketServerPath("");
QString gPathToDhcpExe("");



/**
 * constructor
 */
ndgui::ndgui(QMainWindow *parent) :
	QMainWindow(parent) {
}



/**
 * destructor
 */
ndgui::~ndgui() {

	delete _debugConsole;
	delete _toggleDebugConsole;
	delete _allowUserChoice;
	delete _tryAgain;
	delete _webView;
	delete _networkDiscovery;

}



/**
 * @brief initialize all variables and prepare everything for a successful run
 */
void ndgui::init() {

	_started = false;
	_userChoice = false;
	_ifNameList.clear();
	_manConfList.clear();

	setupLayout();
	createAction();

	_networkDiscovery = new NetworkDiscovery();
	connect(_networkDiscovery, SIGNAL(addInterface(const QString &)), this,
			SLOT(addInterface( const QString &)));
	connect(_networkDiscovery,
			SIGNAL(changeProgressBarValue(const QString & , const int& )),
			this, SLOT(updateIfProgressBar(const QString & , const int&)));
	connect(_networkDiscovery, SIGNAL(connectionEstablished(QString)), this,
			SLOT(handleConnectionEstablished(QString)));
	connect(_networkDiscovery, SIGNAL(abortBoot(QString)), this,
			SLOT(abortBoot(const QString)));
	connect(_networkDiscovery, SIGNAL(updateIfStatus(QString,QString)), this,
			SLOT(updateIfStatus(const QString &, const QString &)));
	connect(_networkDiscovery, SIGNAL(updateStatus(QString)), this,
			SLOT(updateStatus(const QString&)));
	connect(_networkDiscovery, SIGNAL(allProcessesFinished()), this,
			SLOT(handleAllProcessesFinished()));
	connect(_networkDiscovery, SIGNAL(continueBoot(QString)), this,
			SLOT(continueBoot(QString)));
	connect(_networkDiscovery, SIGNAL(continueBootWithoutCheck(QString )),
			this, SLOT(continueBootWithoutCheck(QString)));

	connect(_webView->page()->mainFrame(), SIGNAL(
			javaScriptWindowObjectCleared()), this, SLOT(attachToDOM()));
	connect(_webView, SIGNAL(loadFinished(bool)), this, SLOT(startSingleShot()));

	setWindowTitle(tr("NetD"));
	setAttribute(Qt::WA_QuitOnClose, true);
	setWindowFlags(Qt::FramelessWindowHint);
	showFullScreen();

	if (debugMode > -1) {
		_webView->load(QUrl("qrc:html/networkdiscovery_debug.html"));
	} else {
		_webView->load(QUrl("qrc:html/networkdiscovery.html"));

	}

	_webView->show();
}



/**
 * @brief This method sets the used Layout.
 *
 * This method sets the used Layout. Possible layout are:
 *  - browser mode: only the browser is visible
 *  - debug mode: the screen is divided into the browser and a debug
 *      out console
 */
void ndgui::setupLayout() {
   // setup layout of the gui: debug split or browser
   _webView = new QWebView(this);
   _webView->setContextMenuPolicy(Qt::NoContextMenu); // if this does not work try Qt::CustomContextMenu

   if (debugMode == 1) {
      // split main window in browser & debug console
      createDebugConsole();
      _splitter = new QSplitter(Qt::Vertical, this);
      _splitter->addWidget(_webView);
      _splitter->addWidget(_debugConsole);
      setCentralWidget(_splitter);
   } else {
	  _webView->page()->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
      setCentralWidget(_webView);
   }
}



/**
 * @brief This method creates a debug console as a widget.
 *
 * It is basicly a QTextEdit widget as provided by QT's Framework.
 * An action to toggle this widget is implemented (CTRL + D).
 *
 * @see fbgui::toggleDebugConsole()
 */
void ndgui::createDebugConsole() {
   // create the debug console widget
   _debugConsole = new QTextEdit(this);
   _debugConsole->setWindowFlags(Qt::FramelessWindowHint);
   // fanciness
   QPalette pal;
   pal.setColor(QPalette::Base, Qt::black);
   _debugConsole->setPalette(pal);
   _debugConsole->setTextColor(Qt::white);
   // enable custom logger engine
//   qxtLog->addLoggerEngine("fb_logger", new LoggerEngine_fb(_debugConsole));
   //qxtLog->initLoggerEngine("fb_logger");
//   qxtLog->setMinimumLevel("fb_logger", QxtLogger::DebugLevel);
   // CTRL + D  toggles debug window
   _toggleDebugConsole = new QAction(tr("&toggleDebug"), this);
   _toggleDebugConsole->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_D));
   addAction(_toggleDebugConsole);
   connect(_toggleDebugConsole, SIGNAL(triggered()), this, SLOT(
         toggleDebugConsole()));
}



/**
 * @brief This method toggles the debug console.
 *
 * Toggle the visibility of the debug console if the action _toggleDebugConsole is triggered.
 *
 * @see fbgui::createDebugConsole()
 */
void ndgui::toggleDebugConsole() {
   (_debugConsole->isVisible()) ? _debugConsole->hide() : _debugConsole->show();
}



/**
 * @brief Create actions
 *
 * creates an action which you can trigger with the F5 and F9 Button.
 */
void ndgui::createAction() {
	_allowUserChoice = new QAction(tr("&userChoice"), this);
	_allowUserChoice->setShortcut(QKeySequence(Qt::Key_F5));
	connect(_allowUserChoice, SIGNAL(triggered()), this, SLOT(setUserChoiceTrue()));
	this->addAction(_allowUserChoice);
	_tryAgain = new QAction(tr("&tryAgain"), this);
	_tryAgain->setShortcut(QKeySequence(Qt::Key_F9));
	connect(_tryAgain, SIGNAL(triggered()), this, SLOT(tryAgain()));
	this->addAction(_tryAgain);
}



/**
 * @brief set userChoice true
 *
 * is the connected to the triggered action pressing the F5 button.
 * set the _userChoice member true
 */
void ndgui::setUserChoiceTrue() {
	_userChoice = true;
}



/**
 * @brief starts a singleshot event.
 *
 * is connected to the singleShot event. Triggering this method means
 * that we go on with the main NetworkDiscovery screen.
 * connects the loadFinished signal of the _webView with the
 * startNetworkDiscovery slot and removes the
 * action.
 */
void ndgui::startSingleShot() {

	LOG4CXX_DEBUG(ndLogger, "start single shot");
	QTimer::singleShot(3000, this, SLOT(startNetworkDiscovery()));
}



/**
 * @brief start the network discovery
 *
 * main starting point of the whole procedure.
 * disconnect the loadFinished signal with the startNetworkDiscovery
 * and starts the networkDiscovery.
 */
void ndgui::startNetworkDiscovery() {
	disconnect(_webView, SIGNAL(loadFinished(bool)), this,
			SLOT(startSingleShot()));
	if (!_started) {
		_started = true;
		_networkDiscovery->initAndRun(gServerIp, _userChoice, gAutoUp,
				logFilePath, gSocketServerPath, gPathToDhcpExe);
	} else {
		LOG4CXX_DEBUG(ndLogger, "NetworkDiscovery already started");
	}
}



/**
 * @brief handle if a interface is able to connect
 *
 * if we have a user choice (_userChoice = true) than networkDiscovery will
 * emit connectionEstablished signals.
 * Add the interface name to a _ifNameList. This list holds all interfaces
 * the user can choose out of.
 */
void ndgui::handleConnectionEstablished(QString ifName) {
	_ifNameList.append(ifName);
}



/**
 * @brief determines if we continue the boot sequence or if we show the chooseInterface or abortBoot dialog
 *
 * if we have a user choice (_userChoice = true) than networkDiscovery will
 * emit a allProcessesFinished signal if all processes are done.
 * This method determines if user will see an abort boot dialog (no interface names in
 * the ifNameList list) or an
 * choose interface dialog (one or more interface names in the list (add with
 * handleConnectionEstablished)).
 */
void ndgui::handleAllProcessesFinished() {
	LOG4CXX_DEBUG(ndLogger, "all Processes finished");
	_allowUserChoice->setEnabled(false);
	if (_ifNameList.size() > 0) {
		if (_userChoice) {
			QString jsonArr = "[";
			for (int i = 0; i < _ifNameList.size() - 1; i++) {
				jsonArr += "\"" + _ifNameList.value(i) + "\",";
			}
			jsonArr += "\"" + _ifNameList.last() + "\"]";
			chooseInterfaceDialog(jsonArr);
		} else {
			foreach(QString i, _ifNameList)
			{
				if (_networkDiscovery->checkConnectivity(i)) {
					continueBootWithoutCheck(i);
					break;
				}
			}
		}
	} else {
		LOG4CXX_DEBUG(ndLogger, " No usable interfaces found!: " << _networkDiscovery->GetErrorStr());
		LOG4CXX_DEBUG(ndLogger, " list is empty");
		abortBoot("No usable interfaces found!"
				+ _networkDiscovery->GetErrorStr());
	}
}



/**
 * @brief restart the system
 *
 * this method will restart the system.
 * triggered through a button click in the gui.
 */
void ndgui::restartSystem() {
	QFile file("/proc/sysrq-trigger");
	if (file.open(QIODevice::WriteOnly)) {
		file.write("b");
		file.close();
	} else {
		LOG4CXX_DEBUG(ndLogger, "Could not open /proc/sysrq-trigger");
	}
}



/**
 * @brief shut down the system
 *
 * this method will restart the system.
 * triggered through a button click in the gui.
 */
void ndgui::shutDownSystem() {
	QFile file("/proc/sysrq-trigger");
	if (file.open(QIODevice::WriteOnly)) {
		file.write("o");
		file.close();
	} else {
		LOG4CXX_DEBUG(ndLogger, "Could not open /proc/sysrq-trigger");
	}
}



/**
 * @brief continue the boot sequence
 *
 * represents the end of the NetworkDiscovery life time.
 * will start the fbgui screen. All networkDiscovery signals
 * will be ignored after this point.
 */
//void ndgui::continueBoot(QString ifName, int userChoice) {
void ndgui::continueBoot(QString ifName) {
	if (_networkDiscovery->checkConnectivity(ifName)) {
		LOG4CXX_DEBUG(ndLogger, " continue with interface: " << ifName);
		emit initFbgui();
		this->close();
	} else {
		abortBoot(
				"Interface was suddenly made unusable. Please check the log and try again.");
	}

}



/**
 * @brief continue the boot sequence without further checking if the connection is still possible.
 */
void ndgui::continueBootWithoutCheck(QString ifName) {
	LOG4CXX_DEBUG(ndLogger, " continue with interface: " << ifName);
	emit initFbgui();
	this->close();
}



/**
 * @brief read the log file. Log File will be presented inside of a dialog.
 */
QString ndgui::readLogFile() {
	LOG4CXX_DEBUG(ndLogger, "show log");
	return _networkDiscovery->readLogFile();
}



/**
 * @brief starts the whole application again.
 */
void ndgui::tryAgain() {
	LOG4CXX_DEBUG(ndLogger, " try again ");
	_networkDiscovery->prepareTryAgain();
	if(debugMode > -1) {
		delete _splitter;
		delete _debugConsole;
		delete _toggleDebugConsole;
	}
	delete _allowUserChoice;
	delete _tryAgain;
	delete _webView;
	delete _networkDiscovery;

	init();

}



/*test html gui version*/

/**
 * @brief fills the drop down box of the manual interface configuration
 * dialog.
 */
QVariantList ndgui::getManualConfInterfaces() {
	LOG4CXX_DEBUG(ndLogger, "call getManualConfInterfaces");
	QVariantList jsonArr;
	QString debugOut;
	foreach (QString s, _manConfList) {
		QVariant e(s);
		jsonArr << e;
		debugOut += s + "; ";
	}
	LOG4CXX_DEBUG(ndLogger, "value of jsonArr:" << debugOut);
	return jsonArr;
}


/**
 * @brief return a json formated interface configuration
 *
 * @param ifName
 *        the name of the interface
 */
QVariantMap ndgui::getInterfaceConf(QString ifName) {

  return _networkDiscovery->getInterfaceConfig(ifName);
}



/**
 * @brief takes the entered manual configuration dates and delivers it
 * to the networkDiscovery for further actions.
 *
 * @param jsonArr
 *        a jsonArr which contains the manual entered interface configuration
 */
int ndgui::ip4_setManualConfiguration(QVariantMap jsonArr) {
	return _networkDiscovery->ip4_setManualConfiguration(jsonArr);

}



/* slots */
/************************************************/
//////////////////////////////////////////////////
/************************************************/

/**
 * @brief stellt ein ndgui/fbgui Objekt zur verwendung durch die html bereit.
 */
void ndgui::attachToDOM(){
	_webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("fbgui"), this);
	loadJQuery();
}



/**
 * @brief load jQuery and js scripts into the page so that all javascript functions will work.
 */
void ndgui::loadJQuery() {
   QString js;
   QString pathToJsDir(":/html");
   pathToJsDir.append("/js");

   QDir qrcJSDir(pathToJsDir);
   QFileInfoList fiList = qrcJSDir.entryInfoList();
   QFileInfo fi;
   foreach(fi, fiList)
      {
         if (fi.suffix() == "js") {
            //LOG4CXX_DEBUG(ndLogger, fi.fileName());
            //LOG4CXX_DEBUG(ndLogger, fi.fileName());
            //if (fi.fileName() != "test.js" && fi.fileName() != "nd-functions.js") {
               QFile file;
               file.setFileName(pathToJsDir + "/" + fi.fileName());
               file.open(QIODevice::ReadOnly);
               js = file.readAll();
               file.close();

               _webView->page()->mainFrame()->evaluateJavaScript(js);
               //LOG4CXX_DEBUG(ndLogger, "evaluated " + fi.fileName());
            //}
         }
      }
}




/**
 * @brief show abortBoot dialog
 *
 * @param msg
 *        the message, displayed in the dialog.
 */
void ndgui::abortBoot(const QString msg) {
	QString code = QString("abortBootDialog('\%1')").arg(msg);
	_webView->page()->mainFrame()->evaluateJavaScript(code);
}



/**
 * @brief opens ths chooseInterfaceDialog
 *
 * @param msg
 *        the interfaces as json formated string. will be displayed in a select box.
 */
void ndgui::chooseInterfaceDialog(const QString msg) {
	QString code = QString("chooseInterfaceDialog(\%1)").arg(msg);
	_webView->page()->mainFrame()->evaluateJavaScript(code);
}



/**
 * @brief updates the over all status
 *
 * @param status
 *        the new status message
 */
void ndgui::updateStatus(const QString &status) {
   if (status == "")
      return;
   QString code = QString("updateStatus('\%1')").arg(status);
   _webView->page()->mainFrame()->evaluateJavaScript(code);
}



/**
 * @brief updates the progress bar for each interface.
 *
 * @param	ifname
 * 			the name ot the interface to update
 *
 * @param	percent
 * 			the progress in percent
 */
void ndgui::updateIfProgressBar(const QString &ifName, const int& percent) {
   if (percent == 0)
      return;
   QString code = QString("updateIfProgressBar('\%1',\%2)").arg(ifName).arg(percent);
   _webView->page()->mainFrame()->evaluateJavaScript(code);
}



/**
 * @brief update the status for each interface
 *
 * @param	ifName
 * 			the name ot the interface to update
 *
 * @param 	status
 * 			the new status of the interface.
 */
void ndgui::updateIfStatus(const QString &ifName, const QString &status) {
   if (ifName == "")
      return;
   QString code = QString("updateIfStatus('\%1','\%2')").arg(ifName).arg(status);
   _webView->page()->mainFrame()->evaluateJavaScript(code);
}



/**
 * @brief adds an interface to the DOM tree. Creates its progress bar and it's status label.
 *
 * @param 	ifName
 * 			name of the new interface.
 */
void ndgui::addInterface(const QString &ifName) {
   if (ifName == "")
      return;
   _manConfList.append(ifName);
   QString code = QString("addInterface('\%1')").arg(ifName);
   _webView->page()->mainFrame()->evaluateJavaScript(code);
}



/**
 * @brief just for debugging.
 */
void ndgui::notifyCall(QString msg){
	LOG4CXX_DEBUG(ndLogger, "------ called:" << msg);
}