summaryrefslogtreecommitdiffstats
path: root/src/server/mainwindow/mainwindow.cpp
blob: 99339ba10de42fdac9afd574aa07f7370cbbc6bb (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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
/*
 # Copyright (c) 2009 - OpenSLX Project, Computer Center University of Freiburg
 #
 # This program is free software distributed under the GPL version 2.
 # See http://openslx.org/COPYING
 #
 # If you have any feedback please consult http://openslx.org/feedback and
 # send your suggestions, praise, or complaints to feedback@openslx.org
 #
 # General information about OpenSLX can be found at http://openslx.org/
 # -----------------------------------------------------------------------------
 # mainWindow.cpp
 This is the Main class for the pvsManager. The GUI is constructed here.
 # -----------------------------------------------------------------------------
 */
// Self
#include "mainwindow.h"
// QT stuff
#include <QtGui>
#include <QFileDialog>
#include <QNetworkInterface>
// Other custom UI elements
#include "../clicklabel/clicklabel.h"
#include "../sessionnamewindow/sessionnamewindow.h"
#include "../connectionframe/connectionframe.h"
#include "../helpwindow/helpwindow.h"
// Network
#include "../net/listenserver.h"
#include "../net/client.h"
#include "../net/discoverylistener.h"
#include "../net/filedownloader.h"
// Others
#include "../../shared/settings.h"
#include "../util/util.h"
#include "../util/global.h"
// Auto-generated ui class
#include "ui_mainwindow.h"


const QString MainWindow::sStrTutorNdef = tr("No tutor defined.");
const QString MainWindow::sStrTutorOffline = tr("Tutor is offline.");
const QString MainWindow::sStrSourceNdef = tr("Please select a projection source.");
const QString MainWindow::sStrSourceOffline = tr("The projection source is offline.");
const QString MainWindow::sStrDestNdef = tr("Please select a projection destination.");
const QString MainWindow::sStrDestOffline = tr("The projection destination is offline.");
const QString MainWindow::sStrSourceDestSame = tr("Selected projection target is tutor.");

/***************************************************************************//**
 * Initialize MainWindow and ListenServer.
 * @param ipListUrl
 * @param parent
 */
MainWindow::MainWindow(QString ipListUrl, QWidget* parent) :
	QMainWindow(parent), ui(new Ui::MainWindow), _tbIconSize(24), _tbArea(Qt::LeftToolBarArea)
{

	_tutorFrame = NULL;
	_selectedFrame = NULL;
	_mode = Mode::Idle;
	_streamingSource = NULL;

	_sessionNameWindow = new SessionNameWindow(this);
	_helpWindow = new HelpWindow(this);
	_helpWindow->setWindowTitle("Help");
	ui->setupUi(this);

	Global::setSessionName();

	//conWin = new ConnectionWindow(ui->widget);
	//ui->VconWinLayout->addWidget(conWin);
	//conList = new ConnectionList(ui->ClWidget);
	//ui->ClientGLayout->addWidget(conList);

	// Show only session name label, not textbox
	_sessionNameLabel = new ClickLabel(this);
	ui->mainLayout->addWidget(_sessionNameLabel);

	ui->frmRoom->setStyleSheet("background-color:#444");

	// toolbar and actions in pvsmgr
	ui->action_Exit->setStatusTip(tr("Exit"));
	ui->action_Lock->setStatusTip(tr("Lock or Unlock all Clients"));

	// Initialize FileDownloader.
	if (!ipListUrl.isEmpty())
	{
		_fileDownloader.connectSlot(this, SLOT(onTutorListDownloaded(QByteArray&)));
		_fileDownloader.downloadFile(QUrl(ipListUrl));
	}

	// Close button in tool bar
	connect(ui->action_Exit, SIGNAL(triggered()), this, SLOT(onButtonExit()));
	connect(ui->action_BroadcastScreen, SIGNAL(triggered()), this, SLOT(onButtonStudentToAll()));
	connect(ui->action_TutorToAll, SIGNAL(triggered()), this, SLOT(onButtonTutorToAll()));
	connect(ui->action_StudentToTutor, SIGNAL(triggered()), this, SLOT(onButtonStudentToTutor()));
	connect(ui->action_StudentToTutorExclusive, SIGNAL(triggered()), this, SLOT(onButtonStudentToTutorExclusive()));
	connect(ui->action_TutorToStudent, SIGNAL(triggered()), this, SLOT(onButtonTutorToStudent()));
	connect(ui->action_StopProjection, SIGNAL(triggered()), this, SLOT(onButtonStopProjection()));
	connect(ui->action_SetAsTutor, SIGNAL(triggered()), this, SLOT(onButtonSetAsTutor()));
	connect(ui->action_SetAsTutor, SIGNAL(triggered()), this, SLOT(onButtonStopProjection()));
	connect(ui->action_Lock, SIGNAL(toggled(bool)), this, SLOT(onButtonLock(bool)));
	connect(ui->action_Help, SIGNAL(triggered()), this, SLOT(onButtonHelp()));

	/* Stuff for the button lock */
	_buttonLockTimer = new QTimer(this);
	_buttonLockTimer->setSingleShot(true);
	_buttonLockTimer->setInterval(_buttonBlockTime);
	_lockingButtons
		<< ui->action_Lock
		<< ui->action_BroadcastScreen
		<< ui->action_TutorToAll
		<< ui->action_StudentToTutor
		<< ui->action_TutorToStudent
		<< ui->action_StopProjection
		<< ui->action_SetAsTutor;
	// Disable the buttons if a button is clicked
	foreach (QAction* a, _lockingButtons)
		connect(a, SIGNAL(triggered()), this, SLOT(DisableButtons()));
	// Start the timer a button is clicked
	foreach (QAction* a, _lockingButtons)
		connect(a, SIGNAL(triggered()), _buttonLockTimer, SLOT(start()));
	// Enable the buttons if the timer fires
	connect(_buttonLockTimer, SIGNAL(timeout()), this, SLOT(EnableButtons()));


	// Clicking the session name label shows the edit field for it
	connect(_sessionNameLabel, SIGNAL(clicked()), this, SLOT(onSessionNameClick()));
	// Listen to updates to the session name through the session name window
	connect(_sessionNameWindow, SIGNAL(updateSessionName()), this,
	   SLOT(onSessionNameUpdate()));

	setAttribute(Qt::WA_QuitOnClose);
	setUnifiedTitleAndToolBarOnMac(true);
	this->showMaximized(); // show the Mainwindow maximized

	_tileWidth = 10;
	_tileHeight = 10;

	_listenServer = new ListenServer(CLIENT_PORT);
	connect(_listenServer, SIGNAL(newClient(Client*)), this, SLOT(onClientConnected(Client*)));
	_discoveryListener = new DiscoveryListener();

	// Finally
	this->onSessionNameUpdate();
}

MainWindow::~MainWindow()
{
	_sessionNameLabel->deleteLater();
	delete ui;
}

/***************************************************************************//**
 * Place the frames at possible Position.
 * If current position out of range, place frame into next free cell.
 * @param frame
 */
void MainWindow::placeFrameInFreeSlot(ConnectionFrame* frame)
{
	// Get occupied cell of each frame and store status in an array
	const int elems = _tilesX * _tilesY;
	int currentIndex = 0;
	bool grid[elems];
	memset(grid, 0, sizeof(bool) * elems); // set everything to false
	for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
	{
		const QPoint &oldpos = (*it)->frameGeometry().topLeft();
		const int tx = oldpos.x() / _tileWidth;
		const int ty = oldpos.y() / _tileHeight;
		const int index = tx + ty * _tilesX;
		if (frame == *it)
		{
			// Current frame is the frame to place, remember its old index
			currentIndex = index;
			continue;
		}
		if (index < 0 || index >= elems)
		{
			// Current frame is out of bounds, place in top left corner
			qDebug("Move A");
			(*it)->move(0, 0);
			grid[0] = true;
			continue;
		}
		// Just mark cell as occupied in array
		grid[index] = true;
	}
	// Safety
	if (currentIndex < 0 || currentIndex >= elems)
		currentIndex = 0;
	// Now place in next free cell, start looking at current position of frame
	for (int i = 0; i < elems; ++i)
	{
		const int index = (i + currentIndex) % elems;
		if (grid[index])
			continue;
		const int x = (index % _tilesX) * _tileWidth;
		const int y = (index / _tilesX) * _tileHeight;
		//qDebug() << "Index=" << index << " i=" << i << " cI=" << currentIndex << " elems=" << elems << " x=" << x << " y=" << y;
		qDebug("Move B");
		frame->move(x, y);
		break;
	}
}

/***************************************************************************//**
 * Create new Frame.
 * Create new frame and add to current available frame list.
 * Also connect signals frameMoved() and clicked() with slots.
 * @return ConnectionFrame*
 */
ConnectionFrame* MainWindow::createFrame()
{
	// Allocate and resize
	ConnectionFrame *cf = new ConnectionFrame(ui->frmRoom, _tileWidth, _tileHeight);
	_clientFrames.append(cf);
	cf->show();
	connect(cf, SIGNAL(frameMoved(ConnectionFrame *)), this, SLOT(onPlaceFrame(ConnectionFrame *)));
	connect(cf, SIGNAL(clicked(ConnectionFrame *)), this, SLOT(onFrameClicked(ConnectionFrame *)));
	return cf;
}

/***************************************************************************//**
 * Load position.
 * @param settings
 * @param id
 * @param x
 * @param y
 * @return If loadPosition was successfull.
 */
bool MainWindow::loadPosition(QSettings& settings, const QString& id, int& x, int& y)
{
	settings.beginGroup("client_position");
	const QVariant retval(settings.value(id));
	settings.endGroup();
	if (retval.type() != QVariant::Point)
		return false;
	const QPoint point(retval.toPoint());
	x = point.x();
	y = point.y();
	return true;
}

/***************************************************************************//**
 * Save position of given connectionFrame.
 * @param cf
 */
void MainWindow::savePosition(ConnectionFrame *cf)
{
	Client *client = cf->client();
	if (client == NULL)
		return;
	QPoint pos(cf->pos().x() / _tileWidth, cf->pos().y() / _tileHeight);
	USER_SETTINGS(settings);
	settings.beginGroup("client_position");
	settings.setValue(client->ip(), pos);
	settings.endGroup();
}

/***************************************************************************//**
 * Tells the new client the current situation in class room.
 * Set the specific parameters like projection source or lock screen.
 * @param client
 */
void MainWindow::tellClientCurrentSituation(Client* client)
{
	// If clients are currently locked, tell this new client
	if (ui->action_Lock->isChecked())
		client->lockScreen(true);

	if (_mode == Mode::Broadcast){
		_watchers.insert(client->id(), client);
		client->startVncClient(_streamingSource);
	}
	else if (_mode == Mode::LockedMulticast)
		client->lockScreen(true);
}

/*
 * Overridden methods
 */

/***************************************************************************//**
 * Handle closeEvent.
 * If user calls closing MainWindow, close, else ignore.
 * @param e
 */
void MainWindow::closeEvent(QCloseEvent* e)
{
	int ret = QMessageBox::question(this, "Test", "Exit?", 0, 1, 2);
	if (ret == 1)
		QApplication::exit(0);
	else
		e->ignore();
}

/***************************************************************************//**
 * Change Event.
 * @param e
 */
void MainWindow::changeEvent(QEvent* e)
{
	QMainWindow::changeEvent(e);
}

/***************************************************************************//**
 * Resize event.
 * @param e
 */
void MainWindow::resizeEvent(QResizeEvent* e)
{
	// Resize all connection windows
	if (ui->frmRoom->size().width() < 100 || ui->frmRoom->size().height() < 100 || _tilesX <= 0 || _tilesY <= 0)
		return;
	const int nw = ui->frmRoom->size().width() / _tilesX;
	const int nh = ui->frmRoom->size().height() / _tilesY;
	for (QList<ConnectionFrame*>::iterator it = _clientFrames.begin(); it != _clientFrames.end(); ++it)
	{
		const QPoint &oldpos = (*it)->frameGeometry().topLeft();
		qDebug("Move C");
		(*it)->move((oldpos.x() / _tileWidth) * nw, (oldpos.y() / _tileHeight) * nh);
		(*it)->setSize(nw, nh);
	}
	_tileWidth = nw;
	_tileHeight = nh;
}

/***************************************************************************//**
 * Handle Mouse Release Event.
 * Check if click was inside the frame and if that is the case, set the selection of each connected
 * client to false.
 * @param e
 */
void MainWindow::mouseReleaseEvent(QMouseEvent* e)
{
	// Try to figure out if the user clicked inside the "room" frame
	// No idea if there is a more elegant way to do this without
	// sub-classing that frame and overriding its mouseReleaseEvent
	const QPoint pos(ui->frmRoom->mapFrom(this, e->pos()));
	if (pos.x() < 0 || pos.y() < 0)
		return;
	const QSize frame(ui->frmRoom->size());
	if (frame.width() > pos.x() && frame.height() > pos.y())
	{
		if (_selectedFrame != NULL) {
			_selectedFrame->setSelection(false);
			_selectedFrame = NULL;
		}
	}
}


/*
 * Slots
 */

/***************************************************************************//**
 * Extract information from downloaded tutorList.
 * Split downloaded file by new line and store IPs in _tutorList.
 * @param tutorList
 */
void MainWindow::onTutorListDownloaded(QByteArray& tutorList)
{
	// qDebug() << tutorList;
	QString data = QString::fromUtf8(tutorList.constData(), tutorList.size());
	_tutorList = data.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
	qDebug() << _tutorList;
}

/***************************************************************************//**
 * Place Frame to from user specified position.
 * @param frame
 */
void MainWindow::onPlaceFrame(ConnectionFrame* frame)
{
	if (_tilesX <= 0 || _tilesY <= 0)
		return;
	const QPoint &p = frame->frameGeometry().center();
	const QSize &s = ui->frmRoom->geometry().size();
	int x = (p.x() / _tileWidth) * _tileWidth;
	int y = (p.y() / _tileHeight) * _tileHeight;
	if (x < 0)
		x = 0;
	else if (x > s.width() - _tileWidth)
		x = (_tilesX - 1) * _tileWidth;
	if (y < 0)
		y = 0;
	else if (y > s.height() - _tileHeight)
		y = (_tilesY - 1) * _tileHeight;
	qDebug("Move D");
	frame->move(x, y);
	savePosition(frame);
	const QPoint &newpos = frame->frameGeometry().topLeft();
	for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
	{
		if (*it == frame)
			continue;
		if ((*it)->frameGeometry().topLeft() == newpos)
		{
			placeFrameInFreeSlot(*it);
		}
	}
}

/***************************************************************************//**
 * Mark given frame after it was clicked on.
 * @param frame
 */
void MainWindow::onFrameClicked(ConnectionFrame* frame)
{
	// If same frame is clicked again,, do nothing
	if (_selectedFrame == frame)
	 return;

	// If another frame has been selected, unselect it
	// Set the ui selected and set a new reference
	if (_selectedFrame != NULL)
		_selectedFrame->setSelection(false);
	_selectedFrame = frame;
	_selectedFrame->setSelection(true);
}

/***************************************************************************//**
 * Show session name, after it was clicked on.
 */
void MainWindow::onSessionNameClick()
{
	_sessionNameWindow->show(Global::sessionName());
}

/***************************************************************************//**
 * Update session name.
 */
void MainWindow::onSessionNameUpdate()
{
	_sessionNameLabel->setText(tr("Session Name: %1  [click to edit]").arg(Global::sessionName()));
}

/***************************************************************************//**
 * Check if given client is valid.
 * And if that is the case return true.
 * @param client
 * @return If client is valid or not.
 */
bool MainWindow::isValidClient(Client* client)
{
	for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
	{
		Client *c = (**it).client();
		if (c == client)
			return true;
	}
	return false;
}


/***************************************************************************//**
 * @brief broadcast
 * @param from
 */
void MainWindow::broadcast(Client *from)
{
	_mode = Mode::Broadcast;

	// if there is a server running which is not "from" stop it.
	if (_streamingSource != NULL && _streamingSource != from)
		_streamingSource->stopVncServer();
	_streamingSource = from;

	// Server must not listen to anybody
	_streamingSource->stopVncClient();


	// Set desired projection source on all clients, if not "from" or oflline
	for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
		if ((*it)->client() != NULL && (*it)->client() != _streamingSource)
			_watchers.insert((*it)->client()->id(), (*it)->client());

	if (_streamingSource->isActiveVncServer())
		// From is already active
		this->onVncServerStateChange(_streamingSource);
	else
		// Could not take shortcut, start VNC server on source
		_streamingSource->startVncServer();
}


/***************************************************************************//**
 * @brief MainWindow::unicast
 * @param from
 * @param to
 * @param blockOthers
 */
void MainWindow::multicast(Client *from, Client *to, bool blockOthers)
{
	// If first call in this mode clear the watchers
	if (_mode != (blockOthers ? Mode::LockedMulticast : Mode::Multicast)) {
		_watchers.clear();
		_mode = blockOthers ? Mode::LockedMulticast : Mode::Multicast;
	}

	// if there is a server running which is not "from" stop it.
	if (_streamingSource != NULL && _streamingSource != from)
		_streamingSource->stopVncServer();
	_streamingSource = from;

	// Projection source is never allowed to be an active VNC viewer
	if (from->isActiveVncClient())
		from->stopVncClient();

	// Projection destination is never allowed to be an active VNC server
	if (to->isActiveVncServer())
		to->stopVncServer();

	from->stopVncClient();
	_watchers.insert(to->id(), to);

	if (blockOthers) {
		// Set lock others
		for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
			if ((*it)->client() != NULL && (*it)->client() != from && (*it)->client() != to)
				(*it)->client()->lockScreen(true);
	}

	if (from->isActiveVncServer())  // From is already active
		this->onVncServerStateChange(from);
	else  // Could not take shortcut, (re)start VNC server on source
		from->startVncServer();

	if (blockOthers){
		// TODO: REDESIGN TO FIT THE REQUIREMENTS
	}

}

/***************************************************************************//**
 * Display popup which explains possible actions about the buttons.
 */
void MainWindow::onButtonHelp()
{
	_helpWindow->show();
}

/***************************************************************************//**
 * Handle projection from tutor to all.
 * Get the client who is tutor and set the projectionSource of all
 * clients, except the tutor ones, to false.
 */
void MainWindow::onButtonTutorToAll()
{
	if (_tutorFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorNdef);
	else if (_tutorFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorOffline);
	else
		broadcast(_tutorFrame->client());
}

/***************************************************************************//**
 * Button projection from one student to all the others.
 * First get which client is projectionSource and set this one as from.
 * Set projection source for all clients,except the selected one, to false.
 */
void MainWindow::onButtonStudentToAll()
{
	if (_selectedFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrSourceNdef);
	if (_selectedFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrSourceOffline);
	else
		broadcast(_selectedFrame->client());
}

/***************************************************************************//**
 * Handle the projection from Tutor to specific student.
 * Set the client who is tutor as from and the selected client as to.
 */
void MainWindow::onButtonTutorToStudent()
{
	if (_selectedFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrDestNdef);
	else if (_tutorFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorNdef);
	else if (_selectedFrame == _tutorFrame)
		QMessageBox::critical(this, tr("Projection"), sStrSourceDestSame);
	else if (_selectedFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrDestOffline);
	else if (_tutorFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorOffline);
	else
		multicast(_tutorFrame->client(), _selectedFrame->client());
}

/***************************************************************************//**
 * Handle projection from one student to tutor.
 * Get the client to project from and get client, who is tutor, as to.
 */
void MainWindow::onButtonStudentToTutor()
{
	if (_selectedFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrSourceNdef);
	else if (_tutorFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorNdef);
	else if (_tutorFrame == _selectedFrame)
		QMessageBox::critical(this, tr("Projection"), sStrSourceDestSame);
	else if (_selectedFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrSourceOffline);
	else if (_tutorFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorOffline);
	else
		multicast(_selectedFrame->client(), _tutorFrame->client());
}


/***************************************************************************//**
 * @brief MainWindow::onButtonStudentToTutorExclusive
 */
void MainWindow::onButtonStudentToTutorExclusive()
{
	if (_selectedFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrSourceNdef);
	else if (_tutorFrame == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorNdef);
	else if (_tutorFrame == _selectedFrame)
		QMessageBox::critical(this, tr("Projection"), sStrSourceDestSame);
	else if (_selectedFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrSourceOffline);
	else if (_tutorFrame->client() == NULL)
		QMessageBox::critical(this, tr("Projection"), sStrTutorOffline);
	else
		multicast(_tutorFrame->client(), _selectedFrame->client(), true);
}


/***************************************************************************//**
 * Handle Button StopProjection.
 * Set ProjectionSource of each client to false,  stop the active VNC Server
 * and the active VNC Client(s) and unlock all screens.
 */
void MainWindow::onButtonStopProjection()
{
	for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
	{
		Client *c = (**it).client();
		if (c == NULL)
			continue;
		c->stopVncClient();
		c->stopVncServer();
		c->lockScreen(false);
	}
}

/***************************************************************************//**
 * Handle button to lock or unlock screens of client(s).
 * If already locked, do nothing, else lock or unlock the clients, except the
 * tutor and the manager running machine.
 * @param checked
 */
void MainWindow::onButtonLock(bool checked)
{
	for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
	{
		// Check if client is Tutor or the manager is also running on this machine.
		bool isManagerMachine = false;
		foreach (const QHostAddress &address, QNetworkInterface::allAddresses())
			if (address != QHostAddress(QHostAddress::LocalHost)
					&& (*it)->client() != NULL
					&& (*it)->client()->ip() == address.toString())
				isManagerMachine = true;

		if ((*it)->client() == NULL || isManagerMachine)
			continue; // Don't lock the tutor or the manager running machine.
		(*it)->client()->lockScreen(checked);
	}
}

/***************************************************************************//**
 * On button exit, close application.
 */
void MainWindow::onButtonExit()
{
	this->close();
}

/***************************************************************************//**
 * Handle button to set specific client as tutor.
 * Unset active tutor and set selected client, if not inactive, as new tutor.
 */
void MainWindow::onButtonSetAsTutor()
{
	// If same frame is already tutor, do nothing
	if (_selectedFrame == _tutorFrame)
		return;

	// If a frame has been selected unselect it
	if (_selectedFrame->client() == NULL){
		QMessageBox::critical(this, tr("Selection"), tr("The selected client is not connected."));
		return;
	}

	// Else unset the old and set the new tutor
	if (_tutorFrame != NULL)
		_tutorFrame->setTutor(false);
	_tutorFrame = _selectedFrame;
	_tutorFrame->setTutor(true);
}

/***************************************************************************//**
 * Handle from ListenServer signaled new client connection.
 * @param client
 */
void MainWindow::onClientConnected(Client* client)
{
	qDebug("ListenServer told MainWindow about new connection");
	connect(client, SIGNAL(authenticating(Client*, ClientLogin*)), this, SLOT(onClientAuthenticating(Client*, ClientLogin*)));
	connect(client, SIGNAL(authenticated(Client*)), this, SLOT(onClientAuthenticated(Client*)));
}

/***************************************************************************//**
 * Authenticate new Client client.
 * Check if incoming client ip already exists,
 *							if yes --> return.
 * Check if same name of client already exist,
 *							if yes --> name new client as name(x).
 *							x = number of clients with the same name.
 * @param client
 * @param request
 */
void MainWindow::onClientAuthenticating(Client* client, ClientLogin* request)
{
	qDebug("onClientAuthenticating - Slot was called.");
	disconnect(client, SIGNAL(authenticating(Client*, ClientLogin*)), this, SLOT(onClientAuthenticating(Client*, ClientLogin*)));
	if (!request->accept) // Another receiver of that signal already rejected the client, so nothing to do
		return;
	bool inuse;
	QString check = request->name;
	int addnum = 1;
	do
	{
		inuse = false;
		for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
		{
			Client *c = (**it).client();
			if (c == NULL)
				continue;
			if (!c->isAuthed())
				continue;
			if (c->ip() == request->ip)
			{
				request->accept = false;
				return;
			}
			if (c->name() == check)
			{
				inuse = true;
				check = request->name + " (" + QString::number(++addnum) + ")";
				break;
			}
		}
	} while (inuse && addnum < 100);
	if (inuse)
		request->accept = false;
	else
		request->name = check;
}

/***************************************************************************//**
 * New client was authenticated, make several checks.
 * Check if new clients ip already exists,
 *								if yes --> not necessary to create new clientFrame.
 *								if not --> create a new one and adapt this one to current
 *												   situation in class room(projection / lock screen).
 * Check if avctiv tutor is available,
 *								if not --> check if new client is possible tutor.
 * @param client
 */
void MainWindow::onClientAuthenticated(Client* client)
{
	qDebug("Entering onClientAuthenticated - Slot.");
	disconnect(client, SIGNAL(authenticated(Client*)), this, SLOT(onClientAuthenticated(Client*)));
	connect(client, SIGNAL(vncServerStateChange(Client*)), this, SLOT(onVncServerStateChange(Client*)), Qt::QueuedConnection);
	connect(client, SIGNAL(vncClientStateChange(Client*)), this, SLOT(onVncClientStateChange(Client*)), Qt::QueuedConnection);
	bool hasActiveTutor = false;
	ConnectionFrame *existing = NULL;
	for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
	{
		if ((*it)->computerId() == client->ip())
			existing = *it;
		if ((*it)->isTutor())
		{
			if ((*it)->client() != NULL)
				hasActiveTutor = true;
		}
	}

	bool isTutor = false;
	if (!hasActiveTutor)
	{
		for (int i = 0; i < _tutorList.size(); i++)
		{
			// Check if client is possible tutor
			if (client->ip() == _tutorList[i])
			{
				isTutor = true;
				break;
			}
		}
	}
	// Clients ip already exists, but was not active.
	if (existing != NULL)
	{
		existing->setTutor(isTutor);
		existing->assignClient(client);
		tellClientCurrentSituation(client);
		return;
	}
	// New one, create
	ConnectionFrame *cf = createFrame();
	// Try to load last known position
	int x, y;
	bool ok;
	USER_SETTINGS(usr);
	ok = loadPosition(usr, client->ip(), x, y);
	if (!ok)
	{
		SYSTEM_SETTINGS(sys);
		ok = loadPosition(sys, client->ip(), x, y);
	}
	if (x >= _tilesX || y >= _tilesY)
		ok = false;
	if (ok)
	{
		if (x < 0)
			x = 0;
		if (y < 0)
			y = 0;
		qDebug("Move E");
		cf->move(x * _tileWidth, y * _tileHeight);
		onPlaceFrame(cf);
	}
	else
	{
		// Move to any free tile
		placeFrameInFreeSlot(cf);
	}
	// Set Tutor option
	cf->setTutor(isTutor);
	// Assign client instance
	cf->assignClient(client);

	tellClientCurrentSituation(client);
}

/***************************************************************************//**
 * Handle if VNC Server State has changed.
 * Check if VNC server has been started/stopped on some client and start VNC server/reset pending
 * VNC projection information.
 * @param client
 */
void MainWindow::onVncServerStateChange(Client* client)
{
	if (!isValidClient(client)) // Check here because this slot is connected queued
		return;
	if (client->isActiveVncServer())
	{
		if (_mode == Mode::Broadcast)
		{
			for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
			{
				if ((*it)->client() != NULL)
				{
					// Unlock all online clients
					(*it)->client()->lockScreen(false);

					// Start VNCclients on all online clients but source
					if ((*it)->client() != client)
						(*it)->client()->startVncClient(client);
				}
			}
		}
		else  // !Mode::Broadcast  --> Mode::LockedMC || Mode::MC
		{
			for (QList<ConnectionFrame*>::iterator it(_clientFrames.begin()); it != _clientFrames.end(); ++it)
			{
				// Ignore offline clients
				if ( (*it)->client() != NULL)
				{
					if (_watchers.contains((*it)->client()->id()))
					{
						// Unlock destination and connect VNCclient
						(*it)->client()->lockScreen(false);
						(*it)->client()->startVncClient(client);
					}
					else if ((*it)->client()->id() == client->id() )
					{
						// Unlock source
						(*it)->client()->lockScreen(false);
					}
					else
					{
						// Lock others and stop their clients
						(*it)->client()->lockScreen(_mode == Mode::LockedMulticast);
						(*it)->client()->stopVncClient();
					}
				}
			}
		}
	}
	else
	{
		// VNC server stopped on some client or failed to start - reset local pending projection information
		foreach (Client *c, _watchers) {
			c->stopVncClient();
		}
	}
}

/***************************************************************************//**
 * Handle VNC client state change.
 * Check if any vnc client is in use, and if that is not the case, stop VNC Server.
 * @param client
 * @param lastProjectionSource
 */
void MainWindow::onVncClientStateChange(Client* client)
{
	if (!isValidClient(client)) // Check here because this slot is connected queued
		return;

	// VNC Client stopped -> remove from watchers
	if (!client->isActiveVncClient()){
		_watchers.remove(client->id());

		// If noboody is watching the multicast stop VNC server
		if (_watchers.isEmpty() && _mode != Mode::Broadcast)
			_streamingSource->stopVncServer();
	}
}

/***************************************************************************//**
 * DisableButtons.
 */
void MainWindow::DisableButtons()
{
	foreach (QAction* a, _lockingButtons)
		a->setDisabled(true);
}

/***************************************************************************//**
 * EnableButtons.
 */
void MainWindow::EnableButtons()
{
	foreach (QAction* a, _lockingButtons)
		a->setEnabled(true);
}