WSL/SLF GitLab Repository

MainWindow.cc 46.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*****************************************************************************/
/*  Copyright 2019 WSL Institute for Snow and Avalanche Research  SLF-DAVOS  */
/*****************************************************************************/
/* This file is part of INIshell.
   INIshell is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   INIshell is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with INIshell. If not, see <http://www.gnu.org/licenses/>.
*/

19
20
21
22
23
/*
 * The main window that is displayed on startup.
 * 2019-10
 */

24
#include "MainWindow.h"
Michael Reisecker's avatar
Michael Reisecker committed
25
#include "src/gui/AboutWindow.h"
26
#include "src/gui_elements/Group.h" //to exclude Groups from panel search
27
#include "src/main/colors.h"
28
#include "src/main/common.h"
29
30
31
#include "src/main/Error.h"
#include "src/main/dimensions.h"
#include "src/main/INIParser.h"
32
#include "src/main/inishell.h"
33
#include "src/main/settings.h"
34
#include "src/main/XMLReader.h"
35
36

#include <QApplication>
37
#include <QCheckBox>
38
#include <QDesktopServices>
39
#include <QDir>
40
#include <QFileDialog>
41
#include <QFileInfo>
Michael Reisecker's avatar
Michael Reisecker committed
42
#include <QGroupBox>
43
#include <QMenuBar>
44
#include <QMessageBox>
45
#include <QRegularExpression>
46
#include <QSpacerItem>
47
48
49
50
#include <QStatusBar>
#include <QSysInfo>
#include <QToolBar>

51
52
#include <QMovie>

53
54
55
#ifdef DEBUG
	#include <iostream>
#endif
56

57
58
59
60
61
62
63
/**
 * @class MouseEventFilter
 * @brief Mouse event listener for the main program window.
 * @param[in] object Object the event stems from.
 * @param[in] event The type of event.
 * @return True if the event was accepted.
 */
64
65
66
bool MouseEventFilter::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() == QEvent::MouseButtonPress) {
67
		if (object->property("mouseclick") == "open_log") {
68
			getMainWindow()->viewLogger();
69
70
71
72
		} else if (object->property("mouseclick") == "open_ini") {
			if (!getMainWindow()->ini_filename_->text().isEmpty())
				QDesktopServices::openUrl("file:" + getMainWindow()->ini_filename_->text());
		}
73
	}
74
	return QObject::eventFilter(object, event); //pass to actual event of the object
75
76
}

77
78
79
80
81
82
/**
 * @class MainWindow
 * @brief Constructor for the main window.
 * @param[in] xml_settings Settings for the static INIshell GUI.
 * @param[in] parent Unused since the main window is kept in scope by the entry point function.
 */
83
84
MainWindow::MainWindow(QString &settings_location, const QStringList &errors, QMainWindow *parent)
    : QMainWindow(parent), logger_(this), xml_settings_filename_(settings_location)
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
	/*
	 * Program flowchart sketch:
	 *
	 *   _________________________________
	 *   |  Build GUI elements from XML  |
	 *   ---------------------------------
	 *                  |
	 *                  | set elements' INI key values via:
	 *                  V
	 *
	 *         XML              INI
	 *   (default values)  (file system)                      VALIDATION
	 *          |                |                           (set styles)
	 *          |                |                                ^
	 *          v                v                               /
	 *    _____________________________________                 /
	 *    |      Element's onPropertySet      |  -----> CHECK VALUE
	 *    -------------------------------------               |
	 *          ^                ^        (Property "no_ini" not set? Value not empty?)
	 *          |                |                            |
	 *          |                |                            v
	 *         GUI              CODE                        OUTPUT
	 * (user interaction)  (reactive changes)            (on request)
	 */
111

112
	status_timer_ = new QTimer(this); //for temporary status messages
113
114
115
	status_timer_->setSingleShot(true);
	connect(status_timer_, &QTimer::timeout, this, &MainWindow::clearStatus);

116
	logger_.logSystemInfo();
117
	for (auto &err : errors) //errors from main.cc before the Logger existed
118
		logger_.log(err, "error");
119

120
	/* retrieve and set main window geometry */
Michael Reisecker's avatar
Michael Reisecker committed
121
122
	dim::setDimensions(this, dim::MAIN_WINDOW);
	dim::setDimensions(&logger_, dim::LOGGER);
123

124
	/* create basic GUI items */
125
	this->setUnifiedTitleAndToolBarOnMac(true);
126
127
	createMenu();
	createToolbar();
128
	createStatusbar();
129

130
	preview_ = new PreviewWindow(this);
131
	/* create the dynamic GUI area */
132
	control_panel_ = new MainPanel(this);
133
	this->setCentralWidget(control_panel_);
134
	ini_.setLogger(&logger_);
135
136
137
138
	if (errors.isEmpty())
		setStatus(tr("Ready."), "info");
	else
		setStatus(tr("Errors occurred on startup"), "error");
139
}
140

141
142
143
144
/**
 * @brief Destructor for the main window.
 * @details This function is called after all safety checks have already been performed.
 */
145
MainWindow::~MainWindow()
146
{ //safety checks are performed in closeEvent()
147
	setWindowSizeSettings(); //put the main window sizes into the settings XML
148
	saveSettings();
149
150
	delete mouse_events_toolbar_;
	delete mouse_events_statusbar_;
151
152
}

153
154
155
156
157
158
159
/**
 * @brief Build the dynamic GUI.
 * This function initiates the recursive GUI building with an XML document that was
 * parsed beforehand.
 * @param[in] xml XML to build the gui from.
 */
void MainWindow::buildGui(const QDomDocument &xml)
160
{
161
	setUpdatesEnabled(false); //disable painting until done
162
	QDomNode root = xml.firstChild();
163
164
165
166
167
168
169
170
	while (!root.isNull()) {
		if (root.isElement()) { //skip over comments
			//give no parent group - tabs will be created for top level:
			recursiveBuild(root, nullptr, QString());
			break;
		}
		root = root.nextSibling();
	}
171
	setUpdatesEnabled(true);
172
173
}

174
175
176
/**
 * @brief Set the loaded panels' values from an INI file.
 * @param[in] ini The INI file in form of an INIParser (usually the main one).
177
 * @return True if all INI keys are known to the loaded XML.
178
 */
179
bool MainWindow::setGuiFromIni(const INIParser &ini)
180
{
181
	bool all_ok = true;
182
183
184
185
	for (auto &sec : ini.getSections()) { //run through sections in INI file
		ScrollPanel *tab_scroll = getControlPanel()->getSectionScrollarea(sec.getName(),
		    QString(), QString(), true); //get the corresponding tab of our GUI
		if (tab_scroll != nullptr) { //section exists in GUI
186
			const auto kv_list( sec.getKeyValueList() );
187
			for (size_t ii = 0; ii < kv_list.size(); ++ii) {
188
189
				//find the corresponding panel, and try to create it for dynamic panels
				//(e. g. Selector, Replicator):
190
				QWidgetList widgets( findPanel(tab_scroll, sec, *sec[ii]) );
191
				if (!widgets.isEmpty()) {
192
193
					for (int jj = 0; jj < widgets.size(); ++jj) //multiple panels can share the same key
						widgets.at(jj)->setProperty("ini_value", sec[ii]->getValue());
194
				} else {
195
					logger_.log(tr("No GUI element found for INI key \"") + sec.getName() +
196
					    Cst::sep + sec[ii]->getKey() + "\"", "warning");
197
					all_ok = false;
198
				}
199
200
			} //endfor kv
		} else { //section does not exist
201
			log(tr("No matching section in GUI for section from INI file: \"") +
202
			    sec.getName() + "\"", "warning");
203
			all_ok = false;
204
		} //endif section exists
205
	} //endfor sec
206
	return all_ok;
207
208
}

209
210
211
212
213
/**
 * @brief Retrieve all panels that handle a certain INI key.
 * @param[in] ini_key The INI key to find.
 * @return A list of all panels that handle the INI key.
 */
214
215
QList<Atomic *> MainWindow::getPanelsForKey(const QString &ini_key)
{
216
	QList<Atomic *> panel_list( control_panel_->findChildren<Atomic *>(Atomic::getQtKey(ini_key)) );
217
	for (auto it = panel_list.begin(); it != panel_list.end(); ++it) {
218
219
		//groups don't count towards finding INI keys (for this reason, they additionally
		//have the "no_ini" key set):
220
		if (qobject_cast<Group *>(*it))
221
			panel_list.erase(it);
222
223
224
225
	}
	return panel_list;
}

226
227
228
229
230
231
/**
 * @brief Save the current GUI to an INI file.
 * @details This function calls the underlying function that does this and displays a message if
 * the user has neglected to set some mandatory INI values.
 * @param[in] filename The file to save to. If not given, the current INI file will be used.
 */
232
void MainWindow::saveIni(const QString &filename)
233
{
234
235
236
237
238
239
	/*
	 * We keep the original INIParser as-is, i. e. we always keep the INI file as it was loaded
	 * originally. This is solemnly to be able to check if anything has changed through user
	 * interaction, and if yes, warn before closing.
	 */
	INIParser gui_ini = ini_; //an INIParser is safe to copy around - this is a deep copy
240
	const QString missing( control_panel_->setIniValuesFromGui(&gui_ini) );
241

242
	if (!missing.isEmpty()) {
243
244
245
		QMessageBox msgMissing;
		msgMissing.setWindowTitle("Warning ~ " + QCoreApplication::applicationName());
		msgMissing.setText(tr("<b>Missing mandatory INI values.</b>"));
246
247
		msgMissing.setInformativeText(tr(
		    "Some non-optional INI keys are not set.\nSee details for a list or go back to the GUI and set all highlighted fields."));
248
		msgMissing.setDetailedText(tr("Missing INI keys:\n") + missing);
249
250
251
252
253
254
		msgMissing.setIcon(QMessageBox::Warning);
		msgMissing.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
		msgMissing.setDefaultButton(QMessageBox::Cancel);
		int clicked = msgMissing.exec();
		if (clicked == QMessageBox::Cancel)
			return;
255
	}
256
	//if no file is specified we save to the currently open INI file (save vs. save as):
257
258
259
	gui_ini.writeIni(filename.isEmpty()? gui_ini.getFilename() : filename);
}

260
261
262
/**
 * @brief Save the currently set values to a new INI file.
 */
263
264
void MainWindow::saveIniAs()
{
265
266
267
	QString start_path( getSetting("auto::history::last_ini", "path") );
	if (start_path.isEmpty())
		start_path = getSetting("auto::history::last_preview_write", "path");
268
269
270
271
272
	if (start_path.isEmpty())
		start_path = QDir::currentPath();

	const QString filename = QFileDialog::getSaveFileName(this, tr("Save INI file"),
	    start_path + "/" + ini_filename_->text(),
273
	    "INI files (*.ini *.INI);;All files (*)", nullptr, QFileDialog::DontUseNativeDialog);
274
275
276
	if (filename.isNull()) //cancelled
		return;
	saveIni(filename);
277
	ini_.setFilename(filename); //the new file is the new current file like in all programs
278
	ini_filename_->setText(filename);
279
	autoload_->setVisible(true); //if started from an empty GUI, this could still be disabled
280
281
	toolbar_save_ini_->setEnabled(true); //toolbar entry
	file_save_ini_->setEnabled(true); //menu entry
282
283
284

	const QFileInfo finfo(filename);
	setSetting("auto::history::last_ini", "path", finfo.absoluteDir().path());
285
286
}

287
288
289
/**
 * @brief Select a path for an INI file to be opened, and then open it.
 */
290
void MainWindow::openIni()
291
{
292
	QString start_path( getSetting("auto::history::last_ini", "path") );
293
294
295
296
	if (start_path.isEmpty())
		start_path = QDir::currentPath();

	const QString path = QFileDialog::getOpenFileName(this, tr("Open INI file"), start_path,
297
298
	    "INI files (*.ini);;All files (*)", nullptr,
	    QFileDialog::DontUseNativeDialog | QFileDialog::DontConfirmOverwrite);
299
	if (path.isNull()) //cancelled
300
301
		return;
	openIni(path);
302
303
304

	const QFileInfo finfo(path);
	setSetting("auto::history::last_ini", "path", finfo.absoluteDir().path());
305
306
}

307
308
309
310
311
/**
 * @brief Open an INI file and set the GUI to it's values.
 * @param[in] path The INI file to open.
 * @param[in] is_autoopen Is the INI being loaded through the autoopen mechanism?
 */
312
void MainWindow::openIni(const QString &path, const bool &is_autoopen, const bool &fresh)
313
{
314
	this->getControlPanel()->getWorkflowPanel()->setEnabled(false); //hint at INIshell processing...
315
	setStatus(tr("Reading INI file..."), "info", true);
316
	refreshStatus(); //necessary if heavy operations follow
317
318
	if (fresh)
		clearGui();
319
320
321
322
323
	const bool success = ini_.setFile(path); //load the file into the main INI parser
	if (!setGuiFromIni(ini_)) //set the GUI to the INI file's values
		setStatus(tr("INI file read with unknown keys"), "warning");
	else
		setStatus(tr("INI file read ") + (success? tr("successfully") : tr("with warnings")),
324
		    (success? "info" : "warning")); //ill-formatted lines in INI file
325
	toolbar_save_ini_->setEnabled(true);
326
	file_save_ini_->setEnabled(true);
327
	autoload_->setVisible(true);
328
	ini_filename_->setText(path);
329
	autoload_box_->setText(tr("autoload this INI for ") + current_application_);
330
	if (!is_autoopen) //when a user clicks an INI file to open it we ask anew whether to autoopen
331
		autoload_box_->setCheckState(Qt::Unchecked);
332

333
	this->getControlPanel()->getWorkflowPanel()->setEnabled(true);
Mathias Bavay's avatar
Mathias Bavay committed
334
	QApplication::alert( this ); //notify the user that the task is finished
335
336
}

337
338
339
340
341
342
/**
 * @brief Close the currently opened INI file.
 * @details This function checks whether the user has made changes to the INI file and if yes,
 * allows to save first, discard changes, or cancel the operation.
 * @return True if the INI file was closed, false if the user has cancelled.
 */
343
bool MainWindow::closeIni()
344
{
345
	if (!help_loaded_ && //unless user currently has the help opened which we always allow to close
346
	    getSetting("user::inireader::warn_unsaved_ini", "value") == "TRUE") {
347
348
349
350
351
352
353
		/*
		 * We leave the original INIParser - the one that holds the values like they were
		 * originally read from an INI file - intact and make a copy of it. The currently
		 * set values from the GUI are loaded into the copy, and then the two are compared
		 * for changes. This way we don't display a "settings may be lost" warning if in
		 * fact nothing has changed, resp. the changes cancelled out.
		 */
354
355
356
357
358
359
		INIParser gui_ini = ini_;
		(void) control_panel_->setIniValuesFromGui(&gui_ini);
		if (ini_ != gui_ini) {
			QMessageBox msgNotSaved;
			msgNotSaved.setWindowTitle("Warning ~ " + QCoreApplication::applicationName());
			msgNotSaved.setText(tr("<b>INI settings will be lost.</b>"));
360
361
			msgNotSaved.setInformativeText(tr(
			    "Some INI keys you have set will be lost if you don't save the current INI file."));
362
			msgNotSaved.setDetailedText(ini_.getEqualityCheckMsg());
363
364
365
			msgNotSaved.setIcon(QMessageBox::Warning);
			msgNotSaved.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard);
			msgNotSaved.setDefaultButton(QMessageBox::Cancel);
366

367
			auto *show_msg_again = new QCheckBox(tr("Don't show this warning again"));
368
369
370
371
372
373
374
375
			show_msg_again->setToolTip(tr("The warning can be re-enabled in the settings"));
			show_msg_again->setStyleSheet("QCheckBox {color: " + colors::getQColor("info").name() + "}");
			msgNotSaved.setCheckBox(show_msg_again);
			connect(show_msg_again, &QCheckBox::stateChanged, [](int state) {
				const bool checked = (state == Qt::CheckState::Checked);
				setSetting("user::inireader::warn_unsaved_ini", "value", !checked? "TRUE" : "FALSE");
			});

376
377
378
			int clicked = msgNotSaved.exec();
			if (clicked == QMessageBox::Cancel)
				return false;
Michael Reisecker's avatar
Michael Reisecker committed
379
			if (clicked == QMessageBox::Save)
380
				saveIni();
381
			delete show_msg_again;
382
383
		}
	} //endif help_loaded
384

385
	ini_.clear();
386
	toolbar_save_ini_->setEnabled(false);
387
	file_save_ini_->setEnabled(false);
388
	ini_filename_->setText(QString());
389
	autoload_->setVisible(false);
390
	return true;
391
392
}

393
394
395
396
397
/**
 * @brief Reset the GUI to default values.
 * @details This function checks whether there were any changes to the INI values
 * (if yes, the user can save first or discard or cancel), then clears the whole GUI.
 */
398
void MainWindow::clearGui(const bool &set_default)
399
{
400
	const bool perform_close = closeIni();
401
	if (!perform_close) //user clicked 'cancel'
402
		return;
403
	getControlPanel()->clearGui(set_default);
404
	ini_filename_->setText(QString());
405
	autoload_->setVisible(false);
406
407
}

408
409
410
411
412
/**
 * @brief Store the main window sizes in the settings XML.
 */
void MainWindow::setWindowSizeSettings()
{
413
	setSplitterSizeSettings();
414
415
416
417
418
419
420
421
422
423
424
425
426

	setSetting("auto::sizes::window_" + QString::number(dim::window_type::PREVIEW),
	    "width", QString::number(preview_->width()));
	setSetting("auto::sizes::window_" + QString::number(dim::window_type::PREVIEW),
	    "height", QString::number(preview_->height()));
	setSetting("auto::sizes::window_" + QString::number(dim::window_type::LOGGER),
	    "width", QString::number(logger_.width()));
	setSetting("auto::sizes::window_" + QString::number(dim::window_type::LOGGER),
	    "height", QString::number(logger_.height()));
	setSetting("auto::sizes::window_" + QString::number(dim::window_type::MAIN_WINDOW),
	    "width", QString::number(this->width()));
	setSetting("auto::sizes::window_" + QString::number(dim::window_type::MAIN_WINDOW),
	    "height", QString::number(this->height()));
427
428
429

	//remember the toolbar position:
	setSetting("auto::position::toolbar", "position", QString::number(this->toolBarArea(toolbar_)));
430
431
}

432
433
434
435
436
437
438
439
440
441
/**
 * @brief Remember the main splitter's space distribution.
 */
void MainWindow::setSplitterSizeSettings()
{
	QList<int> splitter_sizes(control_panel_->getSplitterSizes());
	setSetting("auto::sizes::splitter_workflow", "size", QString::number(splitter_sizes.at(0)));
	setSetting("auto::sizes::splitter_mainpanel", "size", QString::number(splitter_sizes.at(1)));
}

442
443
444
445
446
447
/**
 * @brief Create a context menu for the toolbar.
 */
void MainWindow::createToolbarContextMenu()
{
	/* allow user to enable toolbar dragging */
448
	auto *fix_toolbar_position = new QAction(tr("Fix toolbar position"), this);
449
450
451
452
453
	fix_toolbar_position->setCheckable(true);
	fix_toolbar_position->setChecked(getSetting("user::appearance::fix_toolbar_pos", "value") == "TRUE");
	toolbar_context_menu_.addAction(fix_toolbar_position);
}

454
455
456
457
458
459
/**
 * @brief Open an XML file containing an application/simulation.
 * @param[in] path Path to the file to open.
 * @param[in] app_name When looking for applications, the application name was parsed and put
 * into a list. This is the app_name so we don't have to parse again.
 * @param[in] fresh If true, reset the GUI before opening a new application.
460
 * @param[in] is_settings_dialog Is it the settings that are being loaded?
461
 */
462
463
void MainWindow::openXml(const QString &path, const QString &app_name, const bool &fresh,
    const bool &is_settings_dialog)
464
{
465
	if (fresh) {
466
		const bool perform_close = closeIni();
467
		if (!perform_close)
468
			return;
469
		control_panel_->closeSettingsTab();
470
		control_panel_->clearGuiElements();
471
		help_loaded_ = false;
472
	}
473
	current_application_ = app_name;
474

475
	QString autoload_ini;
476
	if (QFile::exists(path)) {
477
		setStatus(tr("Reading application XML..."), "info", true);
478
		refreshStatus();
479
480
		XMLReader xml;
		QString xml_error = QString();
481
		autoload_ini = xml.read(path, xml_error);
482
483
484
		if (!xml_error.isNull()) {
			xml_error.chop(1); //trailing \n
			Error(tr("Errors occured when parsing the XML configuration file"),
485
			    tr("File: \"") + QDir::toNativeSeparators(path) + "\"", xml_error);
486
		}
487
		setStatus("Building GUI...", "info", true);
488
		buildGui(xml.getXml());
489
		setStatus("Ready.", "info", false);
490
		control_panel_->getWorkflowPanel()->buildWorkflowPanel(xml.getXml());
491
492
493
494
495
496
497
498
		if (!autoload_ini.isEmpty()) {
			if (QFile::exists(autoload_ini)) {
				openIni(autoload_ini);
			} else {
				log(QString("Can not load INI file \"%1\" automatically because it does not exist.").arg(
				    QDir::toNativeSeparators(autoload_ini)), "error");
			}
		}
499
	} else {
500
		topLog(tr("An application or simulation file that has previously been found is now missing. Right-click the list to refresh."),
501
		     "error");
502
		setStatus(tr("File has been removed"), "error");
503
		return;
504
	}
505

506
	toolbar_clear_gui_->setEnabled(true);
507
	gui_reset_->setEnabled(true);
508
509
510
	gui_clear_->setEnabled(true);
	if (is_settings_dialog) //no real XML - don't enable XML options
		return;
511
	toolbar_save_ini_as_->setEnabled(true);
512
	file_save_ini_as_->setEnabled(true);
513

514
	//run through all INIs that were saved to be autoloaded and check if it's the application we are opening:
515
	for (auto ini_node = global_xml_settings.firstChildElement().firstChildElement("user").firstChildElement(
516
	    "autoload").firstChildElement("ini");
517
518
519
520
	    !ini_node.isNull(); ini_node = ini_node.nextSiblingElement("ini")) {
		if (ini_node.attribute("application").toLower() == app_name.toLower()) {
			autoload_box_->blockSignals(true); //don't re-save the setting we just fetched
			autoload_box_->setCheckState(Qt::Checked);
521
			autoload_box_->setText(tr("autoload this INI for ") + current_application_);
522
			autoload_box_->blockSignals(false);
523
			openIni(ini_node.text(), true); //TODO: delete if non-existent
524
525
526
			break;
		}
	}
527
528
	toolbar_open_ini_->setEnabled(true); //toolbar entry
	file_open_ini_->setEnabled(true); //menu entry
529
530
531
532
	auto *file_view = getControlPanel()->getWorkflowPanel()->getFilesystemView();
	file_view->setEnabled(true);
	auto *path_label = file_view->getInfoLabel();
	path_label->setText(file_view->getInfoLabel()->property("path").toString());
Mathias Bavay's avatar
Mathias Bavay committed
533
534
	path_label->setWordWrap(true);
	path_label->setStyleSheet("QLabel {font-style: italic}");
Mathias Bavay's avatar
Mathias Bavay committed
535
	QApplication::alert( this ); //notify the user that the task is finished
536
537
}

538
539
540
541
542
543
544
545
546
547
/**
 * @brief Find the panels that control a certain key/value pair.
 * @details This function includes panels that could be created by dynamic panels (Selector etc.).
 * @param[in] parent The parent panel or window to search, since usually we have some information
 * about where to find it. This function is used when iterating through INIParser elements
 * to load the GUI with values.
 * @param[in] section The section to find.
 * @param[in] keyval The key/value pair to find.
 * @return A list of all panels controlling the key/value pair.
 */
548
QWidgetList MainWindow::findPanel(QWidget *parent, const Section &section, const KeyValue &keyval)
549
{
550
	QWidgetList panels;
551
	//first, check if there is a panel for it loaded and available:
552
	panels = findSimplePanel(parent, section, keyval);
553
	int panel_count = parent->findChildren<Atomic *>().count();
554
	//if not found, check if one of our Replicators can create it:
555
	if (panels.isEmpty())
556
		panels = prepareReplicator(parent, section, keyval);
557
558
559
560
561
562
	//if still not found, check if one of our Selectors can create it:
	if (panels.isEmpty())
		panels = prepareSelector(parent, section, keyval);
	//TODO: For the current MeteoIO XML the order is important here so that a TIME filter
	//does not show up twice (because both the normal and time filter's panel fit the pattern).
	//Cleaning up here would also increase performance.
563
	if (parent->findChildren<Atomic *>().count() != panel_count) //new elements were created
564
		return findPanel(parent, section, keyval); //recursion through Replicators that create Selectors that...
Michael Reisecker's avatar
Michael Reisecker committed
565
	return panels; //no more suitable dynamic panels found
566
567
}

568
569
570
571
572
573
574
575
576
/**
 * @brief Find the panels that control a certain key/value pair.
 * @details This function does not include dynamic panels (Selector etc.) and searches only
 * what has already been created.
 * @param[in] parent The parent panel or window to search, because usually we have some information.
 * @param[in] section Section to find.
 * @param[in] keyval Key-value pair to find.
 * @return A list of all panels controlling the key/value pair.
 */
577
QWidgetList MainWindow::findSimplePanel(QWidget *parent, const Section &section, const KeyValue &keyval)
578
579
580
{
	QString id(section.getName() + Cst::sep + keyval.getKey());
	/* simple, not nested, keys */
Michael Reisecker's avatar
Michael Reisecker committed
581
	return parent->findChildren<QWidget *>(Atomic::getQtKey(id));
582
583
}

584
585
586
587
588
589
590
591
592
593
/**
 * @brief Find a Selector in our GUI that could handle a given INI key.
 * @details This function looks for Selectors handling keys like "%::COPY". If one is found,
 * it requests the Selector to create a new panel for the key which will then be available
 * to the parent function that is currently looking for a suitable panel for the INI key.
 * @param[in] parent The parent panel or window to search.
 * @param[in] section Section to find.
 * @param[in] keyval Key/value pair to find.
 * @return A list of panels for the INI key including the possibly newly created ones.
 */
594
QWidgetList MainWindow::prepareSelector(QWidget *parent, const Section &section, const KeyValue &keyval)
595
{
596
	QString id(section.getName() + Cst::sep + keyval.getKey());
597
	//INI key as it would be given in the file, i. e. with the parameters in place instead of the Selector's %:
598
	const QString regex_selector("^" + section.getName() + Cst::sep + R"(([\w\.]+)()" + Cst::sep + R"()(\w+?)([0-9]*$))");
599
600
601
	const QRegularExpression rex(regex_selector);
	const QRegularExpressionMatch matches = rex.match(id);

602
	if (matches.captured(0) == id) { //it could be from a selector with template children
603
604
605
606
607
608
		static const size_t idx_parameter = 1;
		static const size_t idx_keyname = 3;
		static const size_t idx_optional_number = 4;
		const QString parameter(matches.captured(idx_parameter));
		const QString key_name(matches.captured(idx_keyname));
		const QString number(matches.captured(idx_optional_number));
609
		//this would be the ID given in an XML, i. e. with a "%" staing for a parameter:
610
		const QString gui_id = section.getName() + Cst::sep + "%" + Cst::sep + key_name + (number.isEmpty()? "" : "#");
611

612
		//try to find Selector:
Michael Reisecker's avatar
Michael Reisecker committed
613
		QList<Selector *> selector_list = parent->findChildren<Selector *>(Atomic::getQtKey(gui_id));
614
		for (int ii = 0; ii < selector_list.size(); ++ii)
615
			selector_list.at(ii)->setProperty("ini_value", parameter); //cf. notes in prepareReplicator
616
		//now all the right child widgets should exist and we can try to find again:
617
		const QString key_id = section.getName() + Cst::sep + keyval.getKey(); //the one we were originally looking for
618

Michael Reisecker's avatar
Michael Reisecker committed
619
		return parent->findChildren<QWidget *>(Atomic::getQtKey(key_id));
620
	}
621
	return QWidgetList();
622
623
}

624
625
626
627
628
629
630
631
632
633
/**
 * @brief Find a Replicator in our GUI that could handle a given INI key.
 * @details This function looks for Replicators handling keys like "STATION#". If one is found,
 * it requests the Replicator to create a new panel for the key which will then be available
 * to the parent function that is currently looking for a suitable panel for the INI key.
 * @param[in] parent The parent panel or window to search.
 * @param[in] section Section to find.
 * @param[in] keyval Key/value pair to find.
 * @return A list of panels for the INI key including the possibly newly created ones.
 */
634
QWidgetList MainWindow::prepareReplicator(QWidget *parent, const Section &section, const KeyValue &keyval)
635
636
{
	QString id(section.getName() + Cst::sep + keyval.getKey());
637
	//the key how it would look in an INI file:
638
	const QString regex_selector("^" + section.getName() + Cst::sep +
639
	    R"(([\w\.]+)" + Cst::sep + R"()*(\w*?)(?=\d)(\d*)$)");
640
641
642
	const QRegularExpression rex(regex_selector);
	const QRegularExpressionMatch matches = rex.match(id);

643
644
645
646
647
648
649
650
651
652
653
	if (matches.captured(0) == id) { //it's from a replicator with template children
		/*
		 * If we arrive here, we try to find the panel for an INI key that could belong
		 * to the child of a Replicator, e. g. "INPUT::STATION1" or "FILTERS::TA::FILTER1".
		 * We extract the name the Replicator would have (number to "#") and try finding it.
		 */
		static const size_t idx_parameter = 1;
		static const size_t idx_key = 2;
		static const size_t idx_number = 3;
		QString parameter(matches.captured(idx_parameter)); //has trailing "::" if existent
		const QString key(matches.captured(idx_key));
654
		const QString number(matches.captured(idx_number));
655
		//the key how it would look in an XML:
656
657
658
659
660
661
662
663
664
665
666
		QString gui_id = section.getName() + Cst::sep + parameter + key + "#"; //Replicator's name

		/*
		 * A replicator can't normally be accessed via INI keys, because there is no
		 * standalone XML code for it. It always occurs together with child panels,
		 * and those are the ones that will be sought by the INI parser to set values.
		 * Therefore we can use the "ini_value" property listener for a Replicator to
		 * tell it to replicate its panel, thus creating the necessary child panels.
		 */
		QList<Replicator *> replicator_list = parent-> //try to find replicator:
		    findChildren<Replicator *>(Atomic::getQtKey(gui_id));
667
668
		for (int ii = 0; ii < replicator_list.count(); ++ii)
			replicator_list.at(ii)->setProperty("ini_value", number);
669
670
		//now all the right child panels should exist and we can try to find again:
		const QString key_id(section.getName() + Cst::sep + keyval.getKey()); //the one we were originally looking for
Michael Reisecker's avatar
Michael Reisecker committed
671
		return parent->findChildren<QWidget *>(Atomic::getQtKey(key_id));
672
	} //endif has match
673
674

	return QWidgetList(); //no suitable Replicator found
675
676
}

677
678
679
/**
 * @brief Build the main window's menu items.
 */
680
void MainWindow::createMenu()
681
{
682
	/* File menu */
683
	QMenu *menu_file = this->menuBar()->addMenu(tr("&File"));
684
	file_open_ini_ = new QAction(getIcon("document-open"), tr("&Open INI file..."), menu_file);
685
	menu_file->addAction(file_open_ini_); //note that this does not take ownership
686
	connect(file_open_ini_, &QAction::triggered, this, [=]{ toolbarClick("open_ini"); });
687
	file_open_ini_->setShortcut(QKeySequence::Open);
688
	file_open_ini_->setMenuRole(QAction::ApplicationSpecificRole);
689
	file_save_ini_ = new QAction(getIcon("document-save"), tr("&Save INI file"), menu_file);
690
	file_save_ini_->setShortcut(QKeySequence::Save);
691
	file_save_ini_->setMenuRole(QAction::ApplicationSpecificRole);
692
693
694
	menu_file->addAction(file_save_ini_);
	file_save_ini_->setEnabled(false); //enable after an INI is opened
	connect(file_save_ini_, &QAction::triggered, this, [=]{ toolbarClick("save_ini"); });
695
	file_save_ini_as_ = new QAction(getIcon("document-save-as"), tr("Save INI file &as..."), menu_file);
696
	file_save_ini_as_->setShortcut(QKeySequence::SaveAs);
697
	file_save_ini_as_->setMenuRole(QAction::ApplicationSpecificRole);
698
699
700
701
	menu_file->addAction(file_save_ini_as_);
	file_save_ini_as_->setEnabled(false);
	connect(file_save_ini_as_, &QAction::triggered, this, [=]{ toolbarClick("save_ini_as"); });
	menu_file->addSeparator();
702
703
704
705
706
	auto *file_quit_ = new QAction(getIcon("application-exit"), tr("&Exit"), menu_file);
	file_quit_->setShortcut(QKeySequence::Quit);
	file_quit_->setMenuRole(QAction::QuitRole);
	menu_file->addAction(file_quit_);
	connect(file_quit_, &QAction::triggered, this, &MainWindow::quitProgram);
707

708
709
	/* GUI menu */
	QMenu *menu_gui = this->menuBar()->addMenu(tr("&GUI"));
710
	gui_reset_ = new QAction(getIcon("document-revert"), tr("&Reset GUI to default values"), menu_gui);
711
712
713
	menu_gui->addAction(gui_reset_);
	gui_reset_->setEnabled(false);
	gui_reset_->setShortcut(Qt::CTRL + Qt::Key_Backspace);
714
	gui_reset_->setMenuRole(QAction::ApplicationSpecificRole);
715
	connect(gui_reset_, &QAction::triggered, this, [=]{ toolbarClick("reset_gui"); });
716
	gui_clear_ = new QAction(getIcon("edit-delete"), tr("&Clear GUI"), menu_gui);
717
718
	menu_gui->addAction(gui_clear_);
	gui_clear_->setEnabled(false);
719
	gui_clear_->setShortcut( Qt::CTRL + Qt::Key_Backspace );
720
	gui_clear_->setMenuRole(QAction::ApplicationSpecificRole);
721
	connect(gui_clear_, &QAction::triggered, this, [=]{ toolbarClick("clear_gui"); });
722
	menu_gui->addSeparator();
723
724
725
726
	gui_close_all_ = new QAction(getIcon("window-close"), tr("Close all content"), menu_gui);
	menu_gui->addAction(gui_close_all_);
	connect(gui_close_all_, &QAction::triggered, this, &MainWindow::resetGui);
	gui_close_all_->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_Backspace);
727
	gui_close_all_->setMenuRole(QAction::ApplicationSpecificRole);
728

729
	/* View menu */
730
	QMenu *menu_view = this->menuBar()->addMenu(tr("&View"));
731
	auto *view_preview = new QAction(getIcon("document-print-preview"), tr("P&review"), menu_view);
732
	menu_view->addAction(view_preview);
733
	view_preview->setShortcut(QKeySequence::Print);
734
	view_preview->setMenuRole(QAction::ApplicationSpecificRole);
735
	connect(view_preview, &QAction::triggered, this, &MainWindow::viewPreview);
736
	auto *view_log = new QAction(getIcon("utilities-system-monitor"), tr("&Log"), menu_view);
737
	menu_view->addAction(view_log);
738
	connect(view_log, &QAction::triggered, this, &MainWindow::viewLogger);
739
	view_log->setShortcut(Qt::CTRL + Qt::Key_L);
740
	view_log->setMenuRole(QAction::ApplicationSpecificRole);
741
	menu_view->addSeparator();
742
	auto *view_settings = new QAction(getIcon("preferences-system"), tr("&Settings"), menu_view);
743
	view_settings->setShortcut(Qt::Key_F3);
Mathias Bavay's avatar
Mathias Bavay committed
744
	view_settings->setMenuRole(QAction::PreferencesRole);
745
	menu_view->addAction(view_settings);
746
	connect(view_settings, &QAction::triggered, this, &MainWindow::viewSettings);
747
748
749
	view_close_settings_ = new QAction(tr("Close settings"), menu_view);
	view_close_settings_->setEnabled(false);
	view_close_settings_->setShortcut(Qt::CTRL + Qt::Key_F3);
750
	view_close_settings_->setMenuRole(QAction::ApplicationSpecificRole);
751
752
	menu_view->addAction(view_close_settings_);
	connect(view_close_settings_, &QAction::triggered, this, &MainWindow::closeSettings);
Michael Reisecker's avatar
Michael Reisecker committed
753

754
755
	/* Window menu */
	QMenu *menu_window = this->menuBar()->addMenu(tr("&Window"));
756
	auto *window_show_workflow = new QAction(tr("Show wor&kflow"), menu_window);
757
758
	menu_window->addAction(window_show_workflow);
	connect(window_show_workflow, &QAction::triggered, this, &MainWindow::showWorkflow);
759
	window_show_workflow->setShortcut(Qt::CTRL + Qt::Key_K);
760
	window_show_workflow->setMenuRole(QAction::ApplicationSpecificRole);
761
	auto *window_hide_workflow = new QAction(tr("&Hide workflow"), menu_window);
762
763
	menu_window->addAction(window_hide_workflow);
	connect(window_hide_workflow, &QAction::triggered, this, &MainWindow::hideWorkflow);
764
	window_hide_workflow->setShortcut(Qt::CTRL + Qt::Key_H);
765
	window_hide_workflow->setMenuRole(QAction::ApplicationSpecificRole);
766

Michael Reisecker's avatar
Michael Reisecker committed
767
768
769
#ifdef DEBUG
	/* Debug menu */
	QMenu *menu_debug = this->menuBar()->addMenu("&Debug");
770
	auto *debug_run = new QAction("&Run action", menu_debug); //to run arbitrary code with a click
Michael Reisecker's avatar
Michael Reisecker committed
771
	menu_debug->addAction(debug_run);
772
	connect(debug_run, &QAction::triggered, this, &MainWindow::z_onDebugRunClick);
Michael Reisecker's avatar
Michael Reisecker committed
773
774
#endif //def DEBUG

Michael Reisecker's avatar
Michael Reisecker committed
775
	/* Help menu */
Michael Reisecker's avatar
Michael Reisecker committed
776
	auto *menu_help_main = new QMenuBar(this->menuBar());
777
	QMenu *menu_help = menu_help_main->addMenu(tr("&Help"));
778
	auto *help = new QAction(getIcon("help-contents"), tr("&Help"), menu_help_main);
779
	help->setShortcut(QKeySequence::HelpContents);
780
	help->setMenuRole(QAction::ApplicationSpecificRole);
781
782
	menu_help->addAction(help);
	connect(help, &QAction::triggered, this, &MainWindow::loadHelp);
783
	auto *help_about = new QAction(getIcon("help-about"), tr("&About"), menu_help_main);
Mathias Bavay's avatar
Mathias Bavay committed
784
	help_about->setMenuRole(QAction::AboutRole);
785
786
	menu_help->addAction(help_about);
	connect(help_about, &QAction::triggered, this, &MainWindow::helpAbout);
787
	help_about->setShortcut(QKeySequence::WhatsThis);
788
	menu_help->addSeparator();
789
	auto *help_dev = new QAction(tr("&Developer's help"), menu_help_main);
790
	help_dev->setShortcut(Qt::Key_F2);
791
	help_dev->setMenuRole(QAction::ApplicationSpecificRole);
792
793
	menu_help->addAction(help_dev);
	connect(help_dev, &QAction::triggered, this, &MainWindow::loadHelpDev);
794
	auto *help_bugreport = new QAction(tr("File &bug report..."), menu_help_main);
795
	help_bugreport->setMenuRole(QAction::ApplicationSpecificRole);
796
797
	menu_help->addAction(help_bugreport);
	connect(help_bugreport, &QAction::triggered,
798
	    []{ QDesktopServices::openUrl(QUrl("https://models.slf.ch/p/inishell-ng/issues/")); });
799

800
#if !defined Q_OS_MAC
801
	this->menuBar()->setCornerWidget(menu_help_main); //push help menu to the right
802
#endif
803
804
}

805
806
807
/**
 * @brief Create the main window's toolbar.
 */
808
void MainWindow::createToolbar()
809
810
{
	/* toolbar */
811
	toolbar_ = new QToolBar("Shortcuts toolbar");
812
813
814
815
	toolbar_->setContextMenuPolicy(Qt::CustomContextMenu);
	createToolbarContextMenu();
	connect(toolbar_, &QToolBar::customContextMenuRequested, this, &MainWindow::onToolbarContextMenuRequest);
	toolbar_->setMovable(getSetting("user::appearance::fix_toolbar_pos", "value") == "FALSE");
816
	toolbar_->setFloatable(false);
817

818
819
820
821
822
823
824
	bool toolbar_success;
	Qt::ToolBarArea toolbar_area = static_cast<Qt::ToolBarArea>( //restore last toolbar position
	    getSetting("auto::position::toolbar", "position").toInt(&toolbar_success));
	if (!toolbar_success)
		toolbar_area = Qt::ToolBarArea::TopToolBarArea;
	this->addToolBar(toolbar_area, toolbar_);

825
	/* user interaction buttons */
826
	toolbar_->setIconSi