WSL/SLF GitLab Repository

PreviewWindow.cc 57.7 KB
Newer Older
1
2
3
4
5
/*****************************************************************************/
/*  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
6
   it under the terms of the GNU General Public License as published by
7
8
9
10
11
12
   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
13
   GNU General Public License for more details.
14

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

19
#include "PreviewWindow.h"
20
#include "src/gui_elements/Atomic.h"
21
#include "src/main/colors.h"
22
#include "src/main/common.h"
23
#include "src/main/os.h"
24
#include "src/main/dimensions.h"
25
#include "src/main/inishell.h"
26
#include "src/main/settings.h"
27

28
#include <QClipboard>
29
#include <QCoreApplication>
30
31
#include <QFile>
#include <QFileDialog>
32
#include <QFileInfo>
33
34
#include <QFont>
#include <QFontDatabase>
35
#include <QGuiApplication>
36
#include <QKeySequence>
37
#include <QMenuBar>
38
39
#include <QMessageBox>
#include <QStatusBar>
40
#include <QStringList>
Michael Reisecker's avatar
Michael Reisecker committed
41
#include <QTimer>
42
#include <QHostInfo>
43

44
45
#include <vector>

46
47
48
#ifdef DEBUG
	#include <iostream>
#endif //def DEBUG
49

50
51
52
53
54
55
56
57
58
59
60
61
62
/**
 * @class KeyPressFilter
 * @brief Key press event listener for the preview text editors.
 * @param[in] object Object the event stems from (the Text Editor).
 * @param[in] event The type of event.
 * @return True if the event was accepted.
 */
bool EditorKeyPressFilter::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() == QEvent::KeyPress) {
		auto *key_event = static_cast<QKeyEvent *>(event);
		if (keyToSequence(key_event) == QKeySequence::Cut) {
			//cut whole line on empty selection:
63
			auto *current_editor( static_cast<QPlainTextEdit *>(object) );
64
65
			current_editor->moveCursor(QTextCursor::StartOfLine);
			current_editor->moveCursor(QTextCursor::Down, QTextCursor::KeepAnchor);
66
67
			current_editor->cut();
			//our convention: cut the line feed, but don't paste it back
68
			//(convenient shortcut combination to move keys around)
69
70
			QClipboard *clipboard = QGuiApplication::clipboard();
			QString clip_text( clipboard->text() );
71
			clip_text.chop(1); //remove trailing newline
72
73
74
75
76
77
78
79
			clipboard->setText(clip_text);
			event->accept();
			return true;
		}
	}
	return QObject::eventFilter(object, event); //pass to actual event of the object
}

80
81
82
83
84
/**
 * @class SyntaxHighlighter
 * @brief Default constructor for a syntax highlighter used in the INI preview.
 * @param[in] textdoc Text document to handle syntax highlighting for.
 */
85
86
87
88
SyntaxHighlighter::SyntaxHighlighter(QTextDocument *textdoc) : QSyntaxHighlighter(textdoc)
{
	HighlightingRule rule;

89
90
91
92
93
94
95
	/*
	 * The SyntaxHighlighter parses a document for INI file syntax and checks the sections
	 * and keys against the curently loaded XML. Sections and keys that are not present
	 * in the XML are highlighted differently.
	 */

	/* unknown sections */
96
	QTextCharFormat format_section;
97
	format_section.setForeground(colors::getQColor("syntax_unknown_section"));
98
	format_section.setFontWeight(QFont::Bold);
99
	rule.pattern = QRegularExpression(R"(.*\)" + Cst::section_open + R"(.*\)" + Cst::section_close + R"(.*)");
100
101
102
	rule.format = format_section;
	rules_.append(rule);

103
	/* unknown keys */
104
105
	QTextCharFormat format_unknown_key;
	format_unknown_key.setForeground(colors::getQColor("syntax_unknown_key"));
Michael Reisecker's avatar
Michael Reisecker committed
106
107
	rule.pattern = QRegularExpression(R"(^\s*[\w|:|*]+(?=\s*=))"); //TODO: only :: but not :
	//TODO: collect and unify all regex handling (e. g. use the same here as in INIParser)
108
	rule.format = format_unknown_key;
109
110
	rules_.append(rule);

111
	/* INI values */
112
	QTextCharFormat format_value;
113
	format_value.setForeground(colors::getQColor("syntax_value"));
114
115
116
117
	rule.pattern = QRegularExpression(R"((?<=\=).*)");
	rule.format = format_value;
	rules_.append(rule);

118

119
120
121
122
123
124
125
	/* populate highlighter with known sections and keys */
	QTextCharFormat format_known_key;
	format_known_key.setForeground(colors::getQColor("syntax_known_key"));
	QTextCharFormat format_known_section;
	format_known_section.setForeground(colors::getQColor("syntax_known_section"));
	format_known_section.setFontWeight(QFont::Bold);

126
	const QList<Atomic *> panel_list( getMainWindow()->findChildren<Atomic *>() );
127
	for (auto &panel : panel_list) {
Michael Reisecker's avatar
Michael Reisecker committed
128
		if (panel->property("no_ini").toBool()) //e. g. Groups / frames
129
			continue;
130
		QString section, key;
131
		(void) panel->getIniValue(section, key);
132
		key.replace("*", "\\*");
133
		rule.pattern = QRegularExpression("\\" + Cst::section_open + section + "\\" +
134
		    Cst::section_close, QRegularExpression::CaseInsensitiveOption); //TODO: escape only if needed for the set char
135
136
137
138
139
140
141
		rule.format = format_known_section;
		rules_.append(rule);
		rule.pattern = QRegularExpression(R"(^\s*)" + key + R"((=|\s))", QRegularExpression::CaseInsensitiveOption);
		rule.format = format_known_key;
		rules_.append(rule);
	}

142
143
144
145
146
147
148
149
150
	/* comments */
	QTextCharFormat format_block_comment;
	format_block_comment.setForeground(colors::getQColor("syntax_comment"));
	rule.pattern = QRegularExpression(R"(^\s*[#;].*)");
	rule.format = format_block_comment;
	rules_.append(rule);
	rule.pattern = QRegularExpression(R"(([#;](?!$).*))");
	rules_.append(rule);

Mathias Bavay's avatar
Mathias Bavay committed
151
152
153
154
155
156
157
	/* coordinates */
	QTextCharFormat format_coordinate;
	format_coordinate.setForeground(colors::getQColor("coordinate"));
 	rule.pattern = QRegularExpression(R"((latlon|xy)\s*\([-\d\s\.,;]+\))");
	rule.format = format_coordinate;
	rules_.append(rule);
	
158
	/* equals sign */
159
160
161
162
	QTextCharFormat format_equal;
	format_equal.setForeground(Qt::black);
	rule.pattern = QRegularExpression(R"(=)");
	rule.format = format_equal;
163
164
165
	rules_.append(rule);
}

166
167
168
169
/**
 * @brief Send a chunk of text through the syntax highlighter.
 * @param[in] text The text to syntax-highlight.
 */
170
171
172
void SyntaxHighlighter::highlightBlock(const QString &text)
{
	for (const HighlightingRule &rule : qAsConst(rules_)) {
173
		QRegularExpressionMatchIterator mit( rule.pattern.globalMatch(text) );
174
		while (mit.hasNext()) { //run trough regex matches and set the stored formats
175
176
177
178
179
180
			QRegularExpressionMatch match = mit.next();
			setFormat(match.capturedStart(), match.capturedLength(), rule.format);
		}
	}
}

181
182
183
184
185
186
/**
 * @class PreviewWindow
 * @brief Default constructor for the PreviewWindow.
 * @details This constructor creates a tab bar to show multiple INI file versions in.
 * @param [in] parent The PreviewWindow's parent window (the main window).
 */
187
188
PreviewWindow::PreviewWindow(QMainWindow *parent) : QMainWindow(parent),
    preview_ini_(getMainWindow()->getLogger())
189
{
190
	editor_key_filter_ = new EditorKeyPressFilter;
191
	this->setUnifiedTitleAndToolBarOnMac(true);
192
	file_tabs_ = new QTabWidget;
193
	connect(file_tabs_, &QTabWidget::tabCloseRequested, this, &PreviewWindow::closeTab);
194
	file_tabs_->setTabsClosable(true);
195
	this->setCentralWidget(file_tabs_);
196
197
	createMenu();	
	setAcceptDrops(true);
198

199
	//size this window (from "outside" via a timer to have it work on macOS; works without for the logger?):
Michael Reisecker's avatar
Michael Reisecker committed
200
	QTimer::singleShot(1, [=]{ dim::setDimensions(this, dim::PREVIEW); });
201
	this->setWindowTitle(tr("Preview") + " ~ " + QCoreApplication::applicationName());
202
	createFindBar(); //do last to keep status bar hidden
203
	statusBar()->hide();
204
205
}

206
207
208
209
210
211
212
213
/**
 * @brief Destructor with minimal cleanup.
 */
PreviewWindow::~PreviewWindow()
{
	delete editor_key_filter_;
}

214
215
/**
 * @brief Display the current INI file in a new tab.
216
 * @param[in] infile Optional file name to load instead of the GUI values.
217
 */
218
void PreviewWindow::addIniTab(const QString& infile)
219
{
220
	/* get currently set INI values */
221
222
	QString ini_contents;
	QTextStream ss(&ini_contents);
223
224
225
226
	if (infile.isNull()) //load INI from GUI
		loadIniWithGui(); //extend original file's INIParser with GUI values
	else
		preview_ini_.parseFile(infile); //load INI from file system
227

228
	/* text box for the current INI */
229
	const bool setMonospace = (getSetting("user::preview::mono_font", "value") == "TRUE");
230
	auto *preview_editor( new PreviewEdit(setMonospace) );
231
	preview_editor->installEventFilter(editor_key_filter_);
232
	preview_editor->setStyleSheet("QPlainTextEdit {background-color: " + colors::getQColor("syntax_background").name() + "; color: " + colors::getQColor("syntax_invalid").name() + "}");
233

234
235
	highlighter_ = new SyntaxHighlighter(preview_editor->document());

236
	/* display the current GUI's contents */
237
	preview_ini_.outputIni(ss);
238
	if (ini_contents.isEmpty()) {
239
240
		ini_contents = tr("#Empty INI file\n");
		previewStatus(tr("Open an application and load an INI file to view contents"));
241
242
243
	} else {
		previewStatus(QString());
		this->statusBar()->hide();
244
	}
245
	preview_editor->setPlainText(ini_contents); //without undo history --> can't undo to empty
246
247
248

	const QString loaded_file = infile.isNull()? getMainWindow()->getIni()->getFilename() : infile;
	QFileInfo file_info(loaded_file);
249
	QString file_name(file_info.fileName());
250
251
252
	QString file_path;
	if (file_info.exists()) //avoid warning
		file_path = file_info.absolutePath();
253
	if (file_name.isEmpty()) { //pick file name if no INI is opened yet
254
		file_name = "io_new.ini";
255
256
257
258
259
260
	} else {
		INIParser gui_ini = getMainWindow()->getIniCopy();
		(void) getMainWindow()->getControlPanel()->setIniValuesFromGui(&gui_ini);
		if (getMainWindow()->getIniCopy() != gui_ini)
			file_name += " *"; //asterisk for "not saved yet", unless it's only the info text
	}
261
262
263
264
	if (file_path.isEmpty())
		file_path = QDir::currentPath();
	file_tabs_->addTab(preview_editor, file_name);
	file_tabs_->setTabToolTip(file_tabs_->count() - 1, file_path);
265
	file_tabs_->setCurrentIndex(file_tabs_->count() - 1); //switch to new tab
266
	connect(preview_editor, &QPlainTextEdit::textChanged, this, [=]{ textChanged(file_tabs_->count() - 1); });
267
268
269
270

	onShowWhitespacesMenuClick((getSetting("user::preview::show_ws", "value") == "TRUE"));

} //TODO: tab completion for INI keys
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

/**
 * @brief Event listener for when the window is being closed.
 * @details This function allows the user to cancel the closing if there are unsaved
 * changes in the opened INI files.
 * @param[in] event The close event.
 */
void PreviewWindow::closeEvent(QCloseEvent *event)
{
	bool has_unsaved_changes = false; //run through tabs and check for asterisks
	for (int ii = 0; ii < file_tabs_->count(); ++ii) {
		if (file_tabs_->tabText(ii).endsWith("*")) {
			has_unsaved_changes = true;
			break;
		}
	}
287
	if (has_unsaved_changes &&
288
	    getSetting("user::inireader::warn_unsaved_ini", "value") == "TRUE") { //at least one tab has unsaved changes
289
290
291
292
293
294
295
		const int cancel = warnOnUnsavedIni();
		if (cancel == QMessageBox::Cancel) {
			event->ignore();
			return;
		}
	}
	event->accept();
296
297
}

298
/**
299
300
 * @brief Event listener for key presses.
 * @details Close the Preview, add tab, or show the logger.
301
302
303
304
 * @param event The key press event that is received.
 */
void PreviewWindow::keyPressEvent(QKeyEvent *event)
{
305
	if (event->key() == Qt::Key_Escape) {
306
		hideFindBar();
307
308
309
310
311
312
	} else if (keyToSequence(event) == QKeySequence::Print) {
		addIniTab();
	} else if (event->modifiers() == Qt::CTRL && event->key() == Qt::Key_L) {
		getMainWindow()->getLogger()->show();
		getMainWindow()->getLogger()->raise();
	}
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
/**
 * @brief Event listener for drag events.
 * @details This function reacts if a user starts dragging content into the Preview Editor
 * and accepts the dragging.
 * @param[in] event The drag event.
 */
void PreviewWindow::dragEnterEvent(QDragEnterEvent *event)
{
	event->acceptProposedAction();
}

/**
 * @brief Event listener for drop events.
 * @details This is an event listener for the parent preview window, not the text editor itself.
 * As such, the text editor will sill handle its drag & drop functionality accordingly. In order
 * for users to be able to drop files, they need to drop it ouside of the text area. When dragging
 * into the text area however, an info status about this is displayed.
 * @param[in] event The drop event.
 */
void PreviewWindow::dropEvent(QDropEvent *event)
{
	for (const QUrl &url : event->mimeData()->urls()) //run through all files
		addIniTab(url.toLocalFile());
}

340
341
342
343
/**
 * @brief Close an INI file's tab.
 * @param[in] index Index of the tab that is being closed.
 */
344
345
void PreviewWindow::closeTab(int index)
{
346
	//Check for unsaved changes. Note that changes that cancel out leaving the INI file
347
	//unaltered will still trigger the warning (unlike the GUI).
348
	if (file_tabs_->tabText(index).endsWith("*") &&
349
	    getSetting("user::inireader::warn_unsaved_ini", "value") == "TRUE") { //not saved yet
350
351
352
353
354
355
		const int cancel = warnOnUnsavedIni();
		if (cancel == QMessageBox::Cancel)
			return;
	}

	file_tabs_->removeTab(index);
356
357
358
359
	if (file_tabs_->count() == 0)
		this->close();
}

360
361
362
/**
 * @brief Create the PreviewWindow's menu.
 */
363
364
void PreviewWindow::createMenu()
{
365
	/* FILE menu */
366
	QMenu *menu_file = this->menuBar()->addMenu(tr("&File"));
367
368
369
370
371
	auto *file_open = new QAction(getIcon("document-open"), tr("&Open..."), menu_file);
	file_open->setShortcut( QKeySequence::Open );
	menu_file->addAction(file_open);
	connect(file_open, &QAction::triggered, this, &PreviewWindow::openFile);
	menu_file->addSeparator();
372
	auto *file_save = new QAction(getIcon("document-save"), tr("&Save"), menu_file);
373
	file_save->setShortcut( QKeySequence::Save );
374
375
	menu_file->addAction(file_save);
	connect(file_save, &QAction::triggered, this, &PreviewWindow::saveFile);
376
	auto *file_save_as = new QAction(getIcon("document-save-as"), tr("Save &as..."), menu_file);
377
	file_save_as->setShortcut( QKeySequence::SaveAs );
378
379
	menu_file->addAction(file_save_as);
	connect(file_save_as, &QAction::triggered, this, &PreviewWindow::saveFileAs);
380
	menu_file->addSeparator();
381
382
383
384
385
386
	file_save_and_load_ = new QAction(tr("Save and load into GUI"), menu_file);
	menu_file->addAction(file_save_and_load_);
	connect(file_save_and_load_, &QAction::triggered, this, &PreviewWindow::saveFileAndLoadIntoGui);
	file_load_ = new QAction(tr("Load into GUI"), menu_file);
	menu_file->addAction(file_load_);
	connect(file_load_, &QAction::triggered, this, &PreviewWindow::loadIntoGui);
387
388
389
	menu_file->addSeparator();
	auto *file_backup = new QAction(tr("Quicksave backup"), menu_file);
	menu_file->addAction(file_backup);
390
	file_backup->setShortcut(Qt::CTRL + Qt::ALT + Qt::Key_B);
391
	connect(file_backup, &QAction::triggered, this, &PreviewWindow::quickBackup);
392

393
	/* EDIT menu */
394
	QMenu *menu_edit = this->menuBar()->addMenu(tr("&Edit"));
Mathias Bavay's avatar
Mathias Bavay committed
395
	auto *edit_undo = new QAction(getIcon("edit-undo"), tr("Undo"), menu_edit);
396
397
398
	menu_edit->addAction(edit_undo);
	edit_undo->setShortcut(QKeySequence::Undo);
	connect(edit_undo, &QAction::triggered, this, [=]{ getCurrentEditor()->undo(); });
Mathias Bavay's avatar
Mathias Bavay committed
399
	auto *edit_redo = new QAction(getIcon("edit-redo"), tr("Redo"), menu_edit);
400
401
402
403
	menu_edit->addAction(edit_redo);
	edit_redo->setShortcut(QKeySequence::Redo);
	connect(edit_redo, &QAction::triggered, this, [=]{ getCurrentEditor()->redo(); });
	menu_edit->addSeparator();
Mathias Bavay's avatar
Mathias Bavay committed
404
	auto *edit_cut = new QAction(getIcon("edit-cut"), tr("Cut"), menu_edit);
405
406
407
	menu_edit->addAction(edit_cut);
	edit_cut->setShortcut(QKeySequence::Cut);
	connect(edit_cut, &QAction::triggered, this, [=]{ getCurrentEditor()->cut(); });
Mathias Bavay's avatar
Mathias Bavay committed
408
	auto *edit_copy = new QAction(getIcon("edit-copy"), tr("Copy"), menu_edit);
409
410
411
	menu_edit->addAction(edit_copy);
	edit_copy->setShortcut(QKeySequence::Copy);
	connect(edit_copy, &QAction::triggered, this, [=]{ getCurrentEditor()->copy(); });
Mathias Bavay's avatar
Mathias Bavay committed
412
	auto *edit_paste = new QAction(getIcon("edit-paste"), tr("Paste"), menu_edit);
413
414
415
	menu_edit->addAction(edit_paste);
	edit_paste->setShortcut(QKeySequence::Paste);
	connect(edit_paste, &QAction::triggered, this, [=]{ getCurrentEditor()->paste(); });
416
417
	auto *edit_paste_newline = new QAction(tr("Paste to new line"), menu_edit);
	menu_edit->addAction(edit_paste_newline);
418
419
	edit_paste_newline->setShortcut("Alt+" +
	    QKeySequence(QKeySequence::Paste).toString(QKeySequence::NativeText));
420
	connect(edit_paste_newline, &QAction::triggered, this, [=]{ pasteToNewline(); });
Mathias Bavay's avatar
Mathias Bavay committed
421
	auto *edit_select_all = new QAction(getIcon("edit-select-all"), tr("Select all"), menu_edit);
422
423
424
425
426
427
428
429
430
	menu_edit->addAction(edit_select_all);
	edit_select_all->setShortcut(QKeySequence::SelectAll);
	connect(edit_select_all, &QAction::triggered, this, [=]{ getCurrentEditor()->selectAll(); });
	menu_edit->addSeparator();
	auto *edit_find = new QAction(getIcon("edit-find"), tr("&Find text..."), menu_edit);
	menu_edit->addAction(edit_find);
	edit_find->setShortcut(QKeySequence::Find);
	connect(edit_find, &QAction::triggered, this, &PreviewWindow::showFindBar);

431
432
	/* INSERT menu */
	QMenu *menu_insert = this->menuBar()->addMenu(tr("&Insert"));
433
434
435
436
437
438
	auto *edit_insert_header = new QAction(tr("Comment header"), menu_insert);
	menu_insert->addAction(edit_insert_header);
	connect(edit_insert_header, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_header"); });
	menu_insert->addSeparator();
	edit_insert_missing_ = new QAction(tr("Missing keys for GUI"), menu_insert);
439
440
441
	menu_insert->addAction(edit_insert_missing_);
	connect(edit_insert_missing_, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_missing"); });
442
	edit_insert_missing_mandatory_ = new QAction(tr("Mandatory keys for GUI"),
443
444
445
446
447
	     menu_insert);
	menu_insert->addAction(edit_insert_missing_mandatory_);
	connect(edit_insert_missing_mandatory_, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_missing_mandatory"); });

448
	/* TRANSFORM menu */
449
	QMenu *menu_transform = this->menuBar()->addMenu(tr("&Transform"));
450
	/* Whitespaces menu */
451
	auto *transform_whitespaces = new QMenu(tr("Whitespaces"), menu_transform);
452
	transform_whitespaces->setIcon( getIcon("markasblank") );
453
	menu_transform->addMenu(transform_whitespaces);
Mathias Bavay's avatar
Mathias Bavay committed
454
	auto *transform_transform_singlews = new QAction(getIcon("unmarkasblank"), tr("To single spaces"), transform_whitespaces);
455
456
457
	connect(transform_transform_singlews, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_whitespace_singlews"); } );
	transform_whitespaces->addAction(transform_transform_singlews);
458
459
	auto *transform_transform_longestws = new QAction(tr("Adapt to longest keys"),
	    transform_whitespaces);
460
461
462
	connect(transform_transform_longestws, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_whitespace_longestws"); } );
	transform_whitespaces->addAction(transform_transform_longestws);
463
	/* Sort */
464
	auto *transform_sort = new QMenu(tr("Sort"), menu_transform);
Mathias Bavay's avatar
Mathias Bavay committed
465
	transform_sort->setIcon( getIcon("view-sort") );
466
467
468
469
470
471
472
473
474
	menu_transform->addMenu(transform_sort);
	auto *transform_sort_alphabetically = new QAction(tr("Alphabetically"), transform_sort);
	connect(transform_sort_alphabetically, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_sort_alphabetically"); } );
	transform_sort->addAction(transform_sort_alphabetically);
	auto *transform_sort_order = new QAction(tr("In order of INI file"), transform_sort);
	connect(transform_sort_order, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_sort_order"); } );
	transform_sort->addAction(transform_sort_order);
475
	/* Capitalization menu */
476
477
	auto *transform_capitalization = new QMenu(tr("Capitalization"), menu_transform);
	menu_transform->addMenu(transform_capitalization);
478
	auto *transform_capitalization_sections_upper = new QAction(
479
480
481
482
	    tr("Sections to upper case"), transform_capitalization);
	connect(transform_capitalization_sections_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_sections_upper"); } );
	transform_capitalization->addAction(transform_capitalization_sections_upper);
483
	auto *transform_capitalization_sections_lower = new QAction(
484
485
486
487
	    tr("Sections to lower case"), transform_capitalization);
	connect(transform_capitalization_sections_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_sections_lower"); } );
	transform_capitalization->addAction(transform_capitalization_sections_lower);
488
	auto *transform_capitalization_keys_upper = new QAction(
489
490
491
492
	    tr("Keys to upper case"), transform_capitalization);
	connect(transform_capitalization_keys_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_keys_upper"); } );
	transform_capitalization->addAction(transform_capitalization_keys_upper);
493
	auto *transform_capitalization_keys_lower = new QAction(
494
495
496
497
	    tr("Keys to lower case"), transform_capitalization);
	connect(transform_capitalization_keys_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_keys_lower"); } );
	transform_capitalization->addAction(transform_capitalization_keys_lower);
498
	auto *transform_capitalization_values_upper = new QAction(
499
500
501
502
	    tr("Values to upper case"), transform_capitalization);
	connect(transform_capitalization_values_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_values_upper"); } );
	transform_capitalization->addAction(transform_capitalization_values_upper);
503
	auto *transform_capitalization_values_lower = new QAction(
504
505
506
507
508
509
510
	    tr("Values to lower case"), transform_capitalization);
	connect(transform_capitalization_values_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_values_lower"); } );
	transform_capitalization->addAction(transform_capitalization_values_lower);
	transform_capitalization->addSeparator();
	auto *transform_capitalization_upper = new QAction(getIcon("format-text-uppercase"),
	    tr("All to upper case"), transform_capitalization);
511
512
513
	connect(transform_capitalization_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_upper"); } );
	transform_capitalization->addAction(transform_capitalization_upper);
514
515
	auto *transform_capitalization_lower = new QAction(getIcon("format-text-lowercase"),
	    tr("All to lower case"), transform_capitalization);
516
517
518
	connect(transform_capitalization_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_lower"); } );
	transform_capitalization->addAction(transform_capitalization_lower);
519
	/* Comments menu */
520
	auto *transform_comments = new QMenu(tr("Comments"), menu_transform);
521
	transform_comments->setIcon( getIcon("code-context") );
522
	menu_transform->addMenu(transform_comments);
523
524
525
526
527
528
529
530
531
532
	auto *transform_comment_block = new QAction(tr("Comment selection"));
	transform_comments->addAction(transform_comment_block);
	transform_comment_block->setShortcut(Qt::CTRL + Qt::Key_NumberSign);
	connect(transform_comment_block, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comment_block"); });
	auto *transform_uncomment_block = new QAction(tr("Uncomment selection"));
	transform_comments->addAction(transform_uncomment_block);
	transform_uncomment_block->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_NumberSign);
	connect(transform_uncomment_block, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_uncomment_block"); });
533
	transform_comments->addSeparator();
534
	auto *transform_comments_content = new QAction(tr("Comment all content"),
535
	    transform_comments);
536
537
538
	connect(transform_comments_content, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_content"); } );
	transform_comments->addAction(transform_comments_content);
539
	auto *transform_comments_duplicate = new QAction(tr("Duplicate all to comment"),
540
	    transform_comments);
541
	transform_comments_duplicate->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_B);
542
543
544
	connect(transform_comments_duplicate, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_duplicate"); } );
	transform_comments->addAction(transform_comments_duplicate);
545
546
547
548
549
	auto *transform_comments_move_values = new QAction(tr("Move next to values"),
	    transform_comments);
	connect(transform_comments_move_values, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_move_value"); } );
	transform_comments->addAction(transform_comments_move_values);
550
	auto *transform_comments_move_end = new QAction(tr("Collect at bottom"),
551
	    transform_comments);
552
553
554
	connect(transform_comments_move_end, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_move_end"); } );
	transform_comments->addAction(transform_comments_move_end);
Mathias Bavay's avatar
Mathias Bavay committed
555
	auto *transform_comments_trim = new QAction(getIcon("edit-clear-all"), tr("Trim"), transform_comments);
556
557
558
559
	connect(transform_comments_trim, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_trim"); } );
	transform_comments->addAction(transform_comments_trim);
	auto *transform_comments_delete = new QAction(tr("Delete all"), transform_comments);
560
561
562
	connect(transform_comments_delete, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_delete"); } );
	transform_comments->addAction(transform_comments_delete);
563
	transform_comments->addSeparator();
564
565
566
567
568
569
570
571
572
	auto *transform_comments_numbersign = new QAction(tr("Switch to #"), transform_comments);
	connect(transform_comments_numbersign, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_numbersign"); } );
	transform_comments->addAction(transform_comments_numbersign);
	auto *transform_comments_semicolon = new QAction(tr("Switch to ;"), transform_comments);
	connect(transform_comments_semicolon, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_semicolon"); } );
	transform_comments->addAction(transform_comments_semicolon);
	/* Reset menu */
573
	auto *transform_reset = new QMenu(tr("Reset"), menu_transform);
Mathias Bavay's avatar
Mathias Bavay committed
574
	transform_reset->setIcon( getIcon("view-refresh") );
575
	menu_transform->addMenu(transform_reset);
576
577
	auto *transform_reset_original = new QAction(tr("To original INI on file system"),
	    transform_reset);
578
579
580
	connect(transform_reset_original, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_reset_original"); } );
	transform_reset->addAction(transform_reset_original);
581
582
	transform_reset_full_ = new QAction(tr("To full INI with GUI keys"), transform_reset);
	connect(transform_reset_full_, &QAction::triggered, this,
583
	    [=]{ onTransformMenuClick("transform_reset_full"); } );
584
	transform_reset->addAction(transform_reset_full_);
585

586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
	/* CONVERT menu */
	QMenu *menu_convert = this->menuBar()->addMenu(tr("&Convert"));
	QMenu *menu_convert_tabs = new QMenu("&Tabs", menu_convert);
	menu_convert->addMenu(menu_convert_tabs);
	auto *convert_long_spaces_to_tabs = new QAction(tr("8 spaces to tabs"), menu_convert_tabs);
	connect (convert_long_spaces_to_tabs, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_long_spaces_to_tabs"); } );
	menu_convert_tabs->addAction(convert_long_spaces_to_tabs);
	auto *convert_short_spaces_to_tabs = new QAction(tr("4 spaces to tabs"), menu_convert_tabs);
	connect (convert_short_spaces_to_tabs, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_short_spaces_to_tabs"); } );
	menu_convert_tabs->addAction(convert_short_spaces_to_tabs);
	auto *convert_tabs_to_long_spaces = new QAction(tr("Tabs to 8 spaces"), menu_convert_tabs);
	connect (convert_tabs_to_long_spaces, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_tabs_to_long_spaces"); } );
	menu_convert_tabs->addAction(convert_tabs_to_long_spaces);
	auto *convert_tabs_to_short_spaces = new QAction(tr("Tabs to 4 spaces"), menu_convert_tabs);
	connect (convert_tabs_to_short_spaces, &QAction::triggered, this,
	    [=]{ onConvertMenuClick("convert_tabs_to_short_spaces"); } );
	menu_convert_tabs->addAction(convert_tabs_to_short_spaces);

607
	/* VIEW menu */
608
	QMenu *menu_view = this->menuBar()->addMenu(tr("&View"));
609
610
611
612
613
614
615
616
	auto *view_hidden_chars = new QAction(tr("Show &whitespaces"), menu_view);
	view_hidden_chars->setCheckable(true);
	if (getSetting("user::preview::show_ws", "value") == "TRUE")
		view_hidden_chars->setChecked(true);
	connect (view_hidden_chars, &QAction::triggered, this,
	    [=]{ onShowWhitespacesMenuClick(view_hidden_chars->isChecked()); } );
	menu_view->addAction(view_hidden_chars);
	menu_view->addSeparator();
617
	auto *view_new_tab = new QAction(getIcon("tab-new"), tr("&New tab"), menu_view);
618
	view_new_tab->setShortcut(QKeySequence::AddTab);
619
620
	connect(view_new_tab, &QAction::triggered, this, [=]{ addIniTab(); });
	menu_view->addAction(view_new_tab);
621
	auto *view_close_tab = new QAction(getIcon("tab-close"), tr("&Close tab"), menu_view);
622
623
624
	view_close_tab->setShortcut(QKeySequence::Close);
	connect(view_close_tab, &QAction::triggered, this, [=]{ closeTab(file_tabs_->currentIndex()); });
	menu_view->addAction(view_close_tab);
625
626

	/* HELP menu */
627
#if !defined Q_OS_MAC
628
629
	auto *menu_help_main = new QMenuBar(this->menuBar());
	QMenu *menu_help = menu_help_main->addMenu(tr("&?"));
630
	menu_help_main->addMenu(menu_help);
631
	auto *help = new QAction(getIcon("help-contents"), tr("&Help"), menu_help);
632
	this->menuBar()->setCornerWidget(menu_help_main); //push help menu to the right
633
	menu_help->addAction(help);
634
635
636
637
638
639
640

#else
	auto *menu_help_main = this->menuBar()->addMenu("&?");
	auto *help = new QAction(getIcon("help-contents"), tr("&Help"), menu_help_main);
	menu_help_main->addAction(help);
#endif
	help->setMenuRole(QAction::ApplicationSpecificRole);
641
642
	connect(help, &QAction::triggered, this,
	    [=]{ getMainWindow()->loadHelp("UI of INIshell", "help-preview"); });
643
644
645
}

/**
646
 * @brief Prepare a panel in the status bar that allows users to search for text in the preview.
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
 */
void PreviewWindow::createFindBar()
{
	find_text_ = new QLineEdit(this);
	connect(find_text_, &QLineEdit::textChanged, this, &PreviewWindow::onFindTextChanged);
	close_find_bar_ = new QToolButton(this);
	close_find_bar_->setIcon(getIcon("window-close"));
	close_find_bar_->setAutoRaise(true);
	connect(close_find_bar_, &QToolButton::clicked, this, [&]{ hideFindBar(); });
	this->statusBar()->addWidget(find_text_, 1);
	this->statusBar()->addWidget(close_find_bar_);
	hideFindBar();
}

/**
 * @brief Show the find bar.
 */
void PreviewWindow::showFindBar()
{
	previewStatus(QString( ));
	statusBar()->show();
	find_text_->show();
	close_find_bar_->show();
	find_text_->setFocus();
	find_text_->selectAll();
}

/**
 * @brief Hide the find bar.
 */
void PreviewWindow::hideFindBar()

{
	find_text_->hide();
	close_find_bar_->hide();
	statusBar()->hide();
683
684
}

685
686
687
688
689
690
691
692
693
694
695
696
697
698
/**
 * @brief Delegated event listener for when the preview text changes.
 * @details A lambda calls this function with the text box index to add an asterisk
 * to the title ("not saved").
 * @param[in] index Index of the tab the text changed in.
 */
void PreviewWindow::textChanged(const int &index)
{
	const QString file_name(file_tabs_->tabText(index));
	if (!file_name.endsWith("*"))
		file_tabs_->setTabText(index, file_name + " *");

}

699
700
701
702
703
704
/**
 * @brief Combine the original file's INIParser with GUI values and
 * set the local copy to access both.
 */
void PreviewWindow::loadIniWithGui()
{
705
	const QString current_app( getMainWindow()->getCurrentApplication() );
706
	preview_ini_ = getMainWindow()->getIniCopy();
707
708
	preview_ini_.clear(true); //only keep unknown keys (which are transported from input to output)

709
710
	getMainWindow()->getControlPanel()->setIniValuesFromGui(&preview_ini_);
	file_save_and_load_->setText("Save and load into " + getMainWindow()->getCurrentApplication());
711
	file_load_->setText(tr("Load into ") + current_app);
712
713
714
	edit_insert_missing_->setText(tr("Missing keys for ") + current_app);
	edit_insert_missing_mandatory_->setText(tr("Mandatory keys for ") + current_app);
	transform_reset_full_->setText(tr("To full INI with %1 keys").arg(current_app));
715
716
}

717
718
719
720
721
722
723
724
/**
 * @brief Write an opened INI file to the file system.
 * @param[in] file_name The path to save to.
 */
void PreviewWindow::writeIniToFile(const QString &file_name)
{
	QFile outfile(file_name);
	if (!outfile.open(QIODevice::WriteOnly)) {
725
		previewStatus(tr("Could not open %1").arg(QDir::toNativeSeparators(file_name)));
726
727
728
		return;
	}
	QTextStream ss(&outfile);
729
	const auto text_box( getCurrentEditor() );
730
731
732
733
	if (text_box)
		ss << text_box->toPlainText();
	outfile.close();

734
	const QFileInfo finfo(file_name); //switch the displayed name to new file (without asterisk)
735
	const QString shown_name(finfo.fileName());
736
	file_tabs_->setTabText(file_tabs_->currentIndex(), shown_name);
737
	previewStatus(tr("Saved to ") + file_name);
738
739

	setSetting("auto::history::last_preview_write", "path", finfo.absoluteDir().path());
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
}

/**
 * @brief Ask a user if they want to cancel an action.
 * @details This function is called before closing INI tabs with unsaved changes.
 * @return Button the user has clicked.
 */
int PreviewWindow::warnOnUnsavedIni()
{
	QMessageBox msgNotSaved;
	msgNotSaved.setWindowTitle("Warning ~ " + QCoreApplication::applicationName());
	msgNotSaved.setText(tr("<b>INI file not saved yet.</b>"));
	msgNotSaved.setInformativeText(tr("Your INI file(s) may contain unsaved changes."));
	msgNotSaved.setIcon(QMessageBox::Warning);
	msgNotSaved.setStandardButtons(QMessageBox::Cancel | QMessageBox::Discard);
	msgNotSaved.setDefaultButton(QMessageBox::Cancel);
	int clicked = msgNotSaved.exec();
	return clicked;
}

760
761
762
763
764
/**
 * @brief Show a temporary status message in the preview window. This text is volatile.
 * @param[in] text Text to show in the status.
 */
void PreviewWindow::previewStatus(const QString &text)
765
{ //temporary message - erased for e. g. on menu hover
766
767
	statusBar()->showMessage(text);
	statusBar()->show(); //might be hidden from closing the find bar
768
	statusBar()->setToolTip(text);
769
770
}

771
/**
772
773
 * @brief Helper function to get the current tab's text editor.
 * @return The text editor currently in view.
774
 */
775
PreviewEdit * PreviewWindow::getCurrentEditor()
776
{
777
#ifdef DEBUG
778
779
	if (!qobject_cast<PreviewEdit *>(file_tabs_->currentWidget()))
		qDebug() << "PreviewWindow::getCurrentEditor() should have casted to a PreviewEdit but did not";
780
#endif //def DEBUG
781
	return qobject_cast<PreviewEdit *>(file_tabs_->currentWidget());
782
783
784
785
786
787
788
}

/**
 * @brief Helper function to retrieve the currently displayed file's name.
 * @return The current INI file's path.
 */
QString PreviewWindow::getCurrentFilename() const
789
{ //TODO: Store the filename properly without asterisk shuffling
790
	QString shown_name( file_tabs_->tabText(file_tabs_->currentIndex()) );
791
	if (shown_name.endsWith("*")) //remove "unsaved" asterisk for the file name
792
		shown_name.chop(2);
793
794
795
	return file_tabs_->tabToolTip(file_tabs_->currentIndex()) + "/" + shown_name;
}

796
797
798
799
800
801
802
/**
 * @brief Set an editor's text programmatically and add it to the undo history.
 * @details This is a small hack and inserts the text by selecting all and pasting;
 * otherwise this change is not remembered in the document's history.
 * @param[in] editor Editor to set text for.
 * @param[in] text Text to set.
 */
803
void PreviewWindow::setTextWithHistory(QPlainTextEdit *editor, const QString &text)
804
805
806
807
808
809
810
{
	QTextDocument *doc( editor->document() );
	QTextCursor cursor( doc );
	cursor.select(QTextCursor::Document);
	cursor.insertText(text);
}

811
812
813
814
/**
 * @brief Insert missing keys.
 * @details This function looks through the keys in the GUI and adds the
 * ones that are missing.
815
 * @param[in] mode Insert mode (fill missing, fill missing mandatory).
816
 */
817
void PreviewWindow::insertText(const insert_text &mode)
818
{
819
	if (mode == HEADER) {
820
		static const QString marker("############################################################");
821
822
		const QString year( QDate::currentDate().toString("yyyy") );
		const QString date( QDate::currentDate().toString("yyyy-MM-dd") );
823
		const QString username( os::getLogName() );
824
		const QString user_domain( QHostInfo::localDomainName() );
825
826
827
828
829
830
831
832
		QString copyright("# Copyright ");
		if (!username.isEmpty()) copyright.append(username);
		if (!user_domain.isEmpty()) {
			if (!username.isEmpty()) copyright.append(" - ");
			copyright.append(user_domain);
		}
		if (!username.isEmpty() || !user_domain.isEmpty()) copyright.append(", ");
		copyright.append(year);
833
		for (int ii=copyright.size()+1; ii<marker.size(); ii++)
834
			copyright.append(" ");
Michael Reisecker's avatar
Michael Reisecker committed
835

836
		QString header;
837
		header += marker + "\n";
838
		header += copyright + "#\n";
839
		header += marker + "\n";
840
841
		header += "#" + QCoreApplication::applicationName() + " " + APP_VERSION_STR;
		header += " for " + getMainWindow()->getCurrentApplication() + "\n";
842
843
844
845
846
		header += "#" + date + "\n\n";
		preview_ini_.parseText(getCurrentEditor()->toPlainText().prepend(header));
		return;
	}

847
848
849
850
851
	INIParser gui_ini(getMainWindow()->getLogger());
	getMainWindow()->getControlPanel()->setIniValuesFromGui(&gui_ini);
	int counter = 0;
	for (auto &sec : *gui_ini.getSections()) {
		for (auto &keyval : sec.getKeyValueList()) {
Michael Reisecker's avatar
Michael Reisecker committed
852
			if (!preview_ini_.hasKeyValue(keyval.first)) {
853
854
855
856
857
858
859
860
861
862
863
864
865
				if ((mode == MISSING) ||
				    (mode == MISSING_MANDATORY && keyval.second.isMandatory())) {
					QString value( keyval.second.getValue() );
					preview_ini_.set(sec.getName(), keyval.first,
					    value.isEmpty()? "MISSING" : value);
					counter++;
				}
			}
		}
	}
	previewStatus(tr("Inserted %1 keys").arg(counter));
}

866
867
868
869
870
871
872
873
874
875
876
/**
 * @brief Perform whitespaces related transformations on the local INIParser copy.
 * @param[in] mode Type of transformation.
 */
void PreviewWindow::transformWhitespaces(const transform_whitespaces &mode)
{
	switch (mode) {
	case SINGLE_WS:
		for (auto &sec : *preview_ini_.getSections()) {
			for (auto &key : sec.getKeyValueList())
				sec.getKeyValue(key.first)->setKeyValWhitespaces(
877
				    std::vector<QString>( {"", " ", " ", " "} )); //(0)key(1)=(2)value(3)#comment
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
		}
		break;
	case LONGEST_WS:
		for (auto &sec : *preview_ini_.getSections()) {
			int max_key_length = 0;
			for (auto &key : sec.getKeyValueList()) {
				if (!key.second.getValue().isNull() && key.first.length() > max_key_length)
					max_key_length = key.first.length();
			}
			for (auto &key : sec.getKeyValueList()) {
				const int nr_ws = max_key_length - key.first.length() + 1;
				sec.getKeyValue(key.first)->setKeyValWhitespaces(
				    std::vector<QString>( {"", QString(" ").repeated(nr_ws), " ", " "} ) );
			}
		}
	} //switch
}

/**
 * @brief Perform capitalization related transformations on the local INIParser copy.
 * @param[in] mode Type of transformation.
 */
void PreviewWindow::transformCapitalization(const transform_capitalization &mode)
{
902
903
904
905
906
907
908
	const bool lower = (mode == LOWER_CASE || mode == SECTIONS_LOWER ||
	    mode == KEYS_LOWER || mode == VALUES_LOWER);
	const bool value = (mode == VALUES_UPPER || mode == VALUES_LOWER);
	const bool all = (mode == UPPER_CASE || mode == LOWER_CASE);
	const bool section = (mode == SECTIONS_UPPER || mode == SECTIONS_LOWER);

	for (auto &sec : *preview_ini_.getSections()) {
909
		if (section || all)
910
			sec.setName(lower? sec.getName().toLower() : sec.getName().toUpper());
911
		if (!section || all) {
912
913
			for (auto &key : sec.getKeyValueList()) {
				auto *keyvalue = sec.getKeyValue(key.first);
914
915
916
				if (value || all) {
					keyvalue->setValue(lower? keyvalue->getValue().toLower() :
					    keyvalue->getValue().toUpper());
917
918
				}
				if (!value || all) {
919
920
921
922
923
924
					keyvalue->setKey(lower? keyvalue->getKey().toLower() :
					    keyvalue->getKey().toUpper());
				}
			} //endfor key
		} //endif section
	} //endfor sec
925
926
927
928
929
}

/**
 * @brief Perform transformations concerning INI comments on the local INIParser copy.
 * @param[in] mode Type of transformation.
930
 * @return True if at least one comment prefix was removed.
931
 */
932
bool PreviewWindow::transformComments(const transform_comments &mode)
933
{
934
	bool removed_comment = false;
935
936
937
	if (mode == BLOCK_COMMENT || mode == BLOCK_UNCOMMENT) { //block (un)comment
		int first_line, last_line;
		getSelectionMargins(first_line, last_line); //span of selected lines
938
		QStringList lines( getCurrentEditor()->toPlainText().split("\n") );
939
940
941
942
943
944
945
946
947
948
949
		for (int ii = first_line - 1; ii < last_line; ++ii) {
			if (mode == BLOCK_COMMENT) { //add comment prefix
				lines[ii] = "#" + lines[ii];
			} else { //remove comment prefix
				if (lines.at(ii).trimmed().startsWith("#") ||
				    lines.at(ii).trimmed().startsWith(";")) {
					//find first "#" or ";" and delete:
					int prefix_pos = lines.at(ii).indexOf("#");
					if (prefix_pos == -1)
						prefix_pos = lines.at(ii).indexOf(";");
					lines[ii].remove(prefix_pos, 1);
950
					removed_comment = true;
951
952
953
954
				}
			}
		}
		setTextWithHistory(getCurrentEditor(), lines.join("\n"));
955
956
957
958
959
960
961
962
963
964
965
966
967
968
	} else if (mode == ALL_CONTENT) { //put whole content in comment
		QStringList all_lines( getCurrentEditor()->toPlainText().split("\n") );
		for (auto &line : all_lines)
			line = "#" + line;
		const QString loaded_filename( preview_ini_.getFilename() );
		preview_ini_.clear();
		preview_ini_.setFilename(loaded_filename);
		preview_ini_.setBlockCommentAtEnd(all_lines.join("\n"));
	} else if (mode == DUPLICATE) { //copy content to comment
		QStringList all_lines( getCurrentEditor()->toPlainText().split("\n") );
		for (auto &line : all_lines)
			line = "#" + line;
		preview_ini_.setBlockCommentAtEnd(preview_ini_.getBlockCommentAtEnd() + "\n" +
		    all_lines.join("\n"));
969
970
971
972
973
974
975
976
977
978
979
	} else if (mode == MOVE_TO_VALUES) { //remove spaces before comments
		for (auto &sec : *preview_ini_.getSections()) {
			std::vector<QString> ws_sec(sec.getKeyValWhiteSpaces()); //(0)[SECTION](1)#comment
			ws_sec.at(1) = " ";
			sec.setKeyValWhitespaces(ws_sec);
			for (auto &key : sec.getKeyValueList()) {
				std::vector<QString> ws_key(sec.getKeyValue(key.first)->getKeyValWhiteSpaces());
				ws_key.at(3) = " ";
				sec.getKeyValue(key.first)->setKeyValWhitespaces(ws_key);
			}
		}
980
	} else if (mode == MOVE_TO_END) { //collect all comments at end of file
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
		QString comment;
		for (auto &sec : *preview_ini_.getSections()) {
			comment += carryIfContent(sec.getBlockComment());
			comment += carryIfContent(sec.getInlineComment());
			sec.setBlockComment(QString());
			sec.setInlineComment(QString());
			for (auto &key : sec.getKeyValueList()) {
				auto *keyvalue = sec.getKeyValue(key.first);
				comment += carryIfContent(keyvalue->getBlockComment());
				comment += carryIfContent(keyvalue->getInlineComment());
				keyvalue->setBlockComment(QString());
				keyvalue->setInlineComment(QString());
			}
		} //endfor sec
		preview_ini_.setBlockCommentAtEnd(preview_ini_.getBlockCommentAtEnd()
		    + "\n" + comment);
997
998
999
1000
	} else if (mode == TRIM) {
		preview_ini_.setBlockCommentAtEnd(trimComment(preview_ini_.getBlockCommentAtEnd()));
		for (auto &sec : *preview_ini_.getSections()) {
			sec.setBlockComment(trimComment(sec.getBlockComment()));
For faster browsing, not all history is shown. View entire blame