summaryrefslogtreecommitdiffstats
path: root/src/widget.cpp
blob: a5f32fad60c906712ad484f0722ad2c03536f527 (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
#include "widget.h"
#include "ui_widget.h"
#include "timeoutdialog.h"
#include "x.h"
#include "main.h"

#include <QDebug>
#include <QtWidgets/QAction>
#include <QAbstractItemView>

class ScreenWidget : public QWidget
{
public:
	ScreenWidget(float scale, QWidget *parent = nullptr) : QWidget(parent), scale(scale)
	{
		QWidget::setStyleSheet(".QWidget { border-radius: 3px;border: 2px solid black; }");
		QWidget::setLayout(new QVBoxLayout(this));
	}
protected:
	float scale;
	void resizeEvent(QResizeEvent *event) override
	{
		event->accept();
		float diff = (float(event->size().width()) / float(event->size().height())) - scale;
		if(diff > .01f) {
			QWidget::resize(int(float(event->size().height()) * scale), event->size().height());
		} else if (diff < -.01f) {
			QWidget::resize(event->size().width(), int(float(event->size().width()) / scale));
		}
	}
};

class AdvancedScreen
{
public:
	ScreenWidget *screen;
	QComboBox *cboResolution;
	QSize desiredResolution;
};

class AdvancedOutput
{
public:
	AdvancedOutput(const ScreenInfo& si) : info(si) {}
	ScreenInfo info;
	QLabel *assignmentLabel;
	QLabel *rowLabel;
	QComboBox *cboPosition;
};
Q_DECLARE_METATYPE(AdvancedOutput*)

static void addBoldListener(QComboBox *combo)
{
	combo->connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index) {
		combo->setFont(qvariant_cast<QFont>(combo->itemData(index, Qt::FontRole)));
	});
}

//______________________________________________________________________________
Widget::Widget(QWidget *parent) :
	QWidget(parent),
	_ui(new Ui::Widget)
{
	_ui->setupUi(this);
	setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
	QTimer *top = new QTimer(this);
	connect(top, &QTimer::timeout, [=]() {
		auto combos = this->findChildren<QComboBox*>();
		for (auto combo : combos) {
			if (combo->view()->isVisible())
				return;
		}
		raise();
	});
	top->start(1000);
	addBoldListener(_ui->cboCloneResolution);
	addBoldListener(_ui->cboDualLeft);
	addBoldListener(_ui->cboDualRight);
	connectButtons();
}

//______________________________________________________________________________
Widget::~Widget() {

}

void Widget::showEvent(QShowEvent *event)
{
	QWidget::showEvent(event);
	ScreenMode mode = ScreenSetup::inst()->getCurrentMode();
	if (ScreenSetup::inst()->getOutputCount() >= 2 || mode == ScreenMode::Dual) {
		if (_ui->tabWidget->widget(1) != _ui->tabDual) {
			_ui->tabWidget->insertTab(1, _ui->tabDual, tr("Dual Screen"));
		}
	} else {
		if (_ui->tabWidget->widget(1) == _ui->tabDual) {
			_ui->tabWidget->removeTab(1);
		}
	}
	switch (mode) {
	case ScreenMode::Single:
	case ScreenMode::Clone:
		_ui->tabWidget->setCurrentWidget(_ui->tabClone);
		break;
	case ScreenMode::Dual:
		_ui->tabWidget->setCurrentWidget(_ui->tabDual);
		break;
	case ScreenMode::Advanced:
		_ui->tabWidget->setCurrentWidget(_ui->tabAdvanced);
		break;
	}
	initControls();
}

static void fillCombo(QComboBox *combo, const ResolutionVector &resolutions, const QSize &preselected, const QSize &preferred = QSize())
{
	combo->clear();
	QFont font = combo->font();
	font.setBold(false);
	combo->setFont(font);
	bool foundPreselected = false;
	for (auto res : resolutions) {
		combo->addItem(QCoreApplication::tr("%1x%2").arg(res.width()).arg(res.height()), QVariant(res));
		if (res == preferred) {
			QFont boldFont(font);
			boldFont.setBold(true);
			combo->setItemData(combo->count() - 1, boldFont, Qt::FontRole);
		} else {
			combo->setItemData(combo->count() - 1, font, Qt::FontRole);
		}
		if (res == preselected) {
			combo->setCurrentIndex(combo->count() - 1);
			foundPreselected = true;
		} else if (!foundPreselected && res == preferred) {
			combo->setCurrentIndex(combo->count() - 1);
		}
	}
	combo->setFont(qvariant_cast<QFont>(combo->currentData(Qt::FontRole)));
}

static bool dualHeadLess(const ScreenInfo &a, const ScreenInfo &b)
{
	if (a.position != -1 && a.position < b.position)
		return true;
	return a.position == b.position && a.output < b.output;
}

void Widget::comboBold(int index)
{
	QComboBox *cbo = qobject_cast<QComboBox*>(QObject::sender());
	if (cbo != nullptr) {
		cbo->setFont(qvariant_cast<QFont>(cbo->itemData(index, Qt::FontRole)));
	}
}

void Widget::initControls()
{
	if (_ui->btnDualSwap->isChecked()) {
		_ui->btnDualSwap->toggle();
	}
	auto resolutions = ScreenSetup::inst()->getVirtualResolutions();
	auto screenMap = ScreenSetup::inst()->getScreenPositions();
	auto modes = ScreenSetup::inst()->getCommonModes();
	auto screenList = screenMap.values();
	qSort(screenList.begin(), screenList.end(), dualHeadLess);
	// Clone
	QSize preferredClone;
	for (auto screen : screenList) {
		if (!screen.preferredResolution.isEmpty()) {
			preferredClone = screen.preferredResolution;
			if (screen.isProjector)
				break;
		}
	}
	fillCombo(_ui->cboCloneResolution, modes, screenList[0].currentResolution, preferredClone);
	// Dual
	if (screenList.size() >= 2) {
		auto lists = QList<QComboBox*>({_ui->cboDualLeft, _ui->cboDualRight});
		int j = 0;
		for (int i = 0; i < screenList.size() && j < 2; ++i) {
			fillCombo(lists[j], screenList[i].modes, screenList[i].currentResolution, screenList[i].preferredResolution);
			lists[j]->setProperty("output", screenList[i].output);
			QLabel *sl = ( j == 0 ? _ui->lblDualLeft : _ui->lblDualRight );
			sl->setText(screenList[i].output + "\n" + screenList[i].name);
			if (screenList[i].currentResolution.isEmpty())
				continue;
			++j;
		}
	}

	//
	// Clear advanced controls
	for (auto e : _advancedScreens) {
		delete e;
	}
	for (auto e : _advancedOutput) {
		if (e->assignmentLabel->layout() == nullptr) {
			e->assignmentLabel->deleteLater();
		}
		delete e;
	}
	_advancedScreens.clear();
	_advancedOutput.clear();
	QLayoutItem *w;
	while ((w = _ui->advancedCombos->takeAt(0)) != nullptr) {
		if (w->widget() != nullptr) {
			w->widget()->deleteLater();
		}
		delete w;
	}
	while ((w = _ui->advancedContainer->takeAt(0)) != nullptr) {
		if (w->widget() != nullptr) {
			w->widget()->deleteLater();
		}
		delete w;
	}
	// Create new
	// Screens
	QStringList positionList(tr("(off)"));
	for (int i = 0; i < screenMap.size(); ++i) {
		QSize res;
		if (i < resolutions.size()) {
			res = resolutions[i];
		} else {
			res = QSize(16, 9);
		}
		AdvancedScreen *a = new AdvancedScreen();
		a->screen = new ScreenWidget(float(res.width()) / float(res.height()));
		a->desiredResolution = res;
		a->cboResolution = new QComboBox();
		_ui->advancedContainer->addWidget(a->screen);
		_advancedScreens.append(a);
		a->screen->layout()->addWidget(a->cboResolution);
		a->screen->layout()->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
		positionList.append(QString::number(_advancedScreens.size()));
		connect(a->cboResolution, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index) {
			if (!_ignoreResolutionChange) {
				a->desiredResolution = a->cboResolution->itemData(index).toSize();
			}
		});
		addBoldListener(a->cboResolution);
	}
	// Header
	_ui->advancedCombos->addWidget(new QLabel(tr("Output")), 0, 0);
	_ui->advancedCombos->addWidget(new QLabel(tr("Position")), 0, 2);
	// List
	int row = 1;
	for (auto it = screenMap.begin(); it != screenMap.end(); ++it) {
		AdvancedOutput *a = new AdvancedOutput(it.value());
		a->assignmentLabel = new QLabel(it.key(), this);
		a->assignmentLabel->hide();
		a->rowLabel = new QLabel(it.key());
		_ui->advancedCombos->addWidget(a->rowLabel, row, 0);
		_ui->advancedCombos->addWidget(new QLabel(a->info.name), row, 1);
		QComboBox *cbo = new QComboBox();
		a->cboPosition = cbo;
		cbo->setProperty("output", QVariant::fromValue(a));
		_ui->advancedCombos->addWidget(cbo, row, 2);
		_ui->advancedCombos->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum), row, 3);
		_advancedOutput.append(a);
		row++;
		// Logic
		cbo->addItems(positionList);
		// TODO Signal
		connect(cbo, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index) {
			a->info.position = index - 1;
			if (a->assignmentLabel->layout() != nullptr) {
				a->assignmentLabel->layout()->removeWidget(cbo);
			}
			if (index > 0) {
				_advancedScreens[index - 1]->screen->layout()->addWidget(a->assignmentLabel);
				a->assignmentLabel->show();
			} else {
				a->assignmentLabel->hide();
			}
			// Refill boxes
			_ignoreResolutionChange = true;
			for (int i = 0; i < _advancedScreens.size(); ++i) {
				QSize preferred, fallbackPreferred;
				// Iterate over all virtual screens
				AdvancedScreen *screen = _advancedScreens[i];
				bool first = true;
				ResolutionVector common;
				for (auto output : _advancedOutput) {
					if (output->info.position != i)
						continue; // Output not mapped to this virtual screen
					if (first) {
						common = output->info.modes;
						first = false;
					} else {
						QMutableVectorIterator<QSize> it(common);
						while (it.hasNext()) {
							if (!output->info.modes.contains(it.next())) {
								it.remove();
							}
						}
					}
					if (!output->info.preferredResolution.isEmpty()) {
						QSize &p = output->info.isProjector ? preferred : fallbackPreferred;
						if (p.isEmpty() || !common.contains(p)) {
							p = output->info.preferredResolution;
						}
					}
				}
				// Set list
				// TODO: Highlight preferred mode
				if (preferred.isEmpty()) {
					preferred = fallbackPreferred;
				}
				qDebug() << "Preferred:" << preferred;
				fillCombo(screen->cboResolution, common, screen->desiredResolution, preferred);
			}
			_ignoreResolutionChange = false;
		});
		cbo->setCurrentIndex(a->info.position + 1);
	}
}

bool Widget::keepResolution()
{
	// Show a dialog asking if the res should be kept
	TimeOutDialog keepDialog(15, this);
	keepDialog.setWindowModality(Qt::ApplicationModal);
	keepDialog.setWindowTitle(" ");
	keepDialog.setLabelText(trUtf8("Do you want to keep this resolution?"));
	keepDialog.setCancelButtonText(trUtf8("Keep"));
	/*
  keepDialog.move(monitorMode->width/2  - this->width()/2,
				   monitorMode->height/2 - this->height());
				   */
	keepDialog.show();

	do {
		QCoreApplication::processEvents();
	} while (keepDialog.isActive());

	return keepDialog.wasCanceled();
}

//______________________________________________________________________________
void Widget::connectButtons() {

	// Swap dualscreen
	connect(_ui->btnDualSwap, &QPushButton::clicked, [=](bool) {
		_ui->dualContainer->addItem(_ui->dualContainer->takeAt(1));
		_ui->dualContainer->addItem(_ui->dualContainer->takeAt(0));
	});

	// Apply CLONE
	connect(_ui->btnCloneApply, &QPushButton::clicked, [=](bool) {
		if (!ScreenSetup::inst()->setClone(_ui->cboCloneResolution->currentData().toSize()) || !keepResolution()) {
			qDebug() << "reverting clone";
			ScreenSetup::inst()->revertChanges();
		}
		ScreenSetup::inst()->updateScreenResources();
		initControls();
	});

	// Apply DUALHEAD
	connect(_ui->btnDualApply, &QPushButton::clicked, [=](bool) {
		QPair<QSize, QList<QString>> left = { _ui->cboDualLeft->currentData().toSize(), { _ui->cboDualLeft->property("output").toString() } };
		QPair<QSize, QList<QString>> right = { _ui->cboDualRight->currentData().toSize(), { _ui->cboDualRight->property("output").toString() } };
		if (_ui->btnDualSwap->isChecked()) {
			qSwap(left, right);
		}
		if (!ScreenSetup::inst()->setCustom({left, right}) || !keepResolution()) {
			qDebug() << "reverting dualhead";
			ScreenSetup::inst()->revertChanges();
		}
		ScreenSetup::inst()->updateScreenResources();
		initControls();
	});

	// Apply custom
	connect(_ui->btnAdvancedApply, &QPushButton::clicked, [=](bool) {
		QList<QPair<QSize, QList<QString>>> list;
		for (auto e : _advancedScreens) {
			list.append({ e->cboResolution->currentData().toSize(), QList<QString>() });
		}
		for (auto e : _advancedOutput) {
			int index = e->cboPosition->currentIndex() - 1;
			if (index < 0 || index >= list.size())
				continue;
			list[index].second.append(e->cboPosition->property("output").toString());
		}
		if (!ScreenSetup::inst()->setCustom(list) || !keepResolution()) {
			qDebug() << "reverting custom";
			ScreenSetup::inst()->revertChanges();
		}
		ScreenSetup::inst()->updateScreenResources();
		initControls();
	});

}

////////////////////////////////////////////////////////////////////////////////