WSL/SLF GitLab Repository

PreviewWindow.cc 54 KB
Newer Older
Mathias Bavay's avatar
Mathias Bavay committed
1
//SPDX-License-Identifier: GPL-3.0-or-later
2
3
4
5
6
/*****************************************************************************/
/*  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
7
   it under the terms of the GNU General Public License as published by
8
9
10
11
12
13
   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
14
   GNU General Public License for more details.
15

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

20
21
22
23
24
25
26
#include <src/gui/PreviewWindow.h>
#include <src/gui/RememberDialog.h>
#include <src/main/colors.h>
#include <src/main/common.h>
#include <src/main/os.h>
#include <src/main/inishell.h>
#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 <QHostInfo>
37
#include <QKeySequence>
38
#include <QMenuBar>
39
#include <QStatusBar>
Michael Reisecker's avatar
Michael Reisecker committed
40
#include <QTimer>
41

42
43
#include <vector>

44
45
46
#ifdef DEBUG
	#include <iostream>
#endif //def DEBUG
47

48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * @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:
61
			auto *current_editor( static_cast<QPlainTextEdit *>(object) );
62
63
			current_editor->moveCursor(QTextCursor::StartOfLine);
			current_editor->moveCursor(QTextCursor::Down, QTextCursor::KeepAnchor);
64
65
			current_editor->cut();
			//our convention: cut the line feed, but don't paste it back
66
			//(convenient shortcut combination to move keys around)
67
68
			QClipboard *clipboard = QGuiApplication::clipboard();
			QString clip_text( clipboard->text() );
69
			clip_text.chop(1); //remove trailing newline
70
71
72
73
74
75
76
77
			clipboard->setText(clip_text);
			event->accept();
			return true;
		}
	}
	return QObject::eventFilter(object, event); //pass to actual event of the object
}

78
79
80
81
/**
 * @class PreviewWindow
 * @brief Default constructor for the PreviewWindow.
 * @details This constructor creates a tab bar to show multiple INI file versions in.
Michael Reisecker's avatar
Michael Reisecker committed
82
 * @param[in] parent The PreviewWindow's parent window (the main window).
83
 */
84
85
PreviewWindow::PreviewWindow(QMainWindow *parent) : QMainWindow(parent),
    preview_ini_(getMainWindow()->getLogger())
86
{
87
	editor_key_filter_ = new EditorKeyPressFilter;
88
	file_tabs_ = new QTabWidget;
89
	connect(file_tabs_, &QTabWidget::tabCloseRequested, this, &PreviewWindow::closeTab);
90
	
91
	file_tabs_->setTabsClosable(true);
92
	this->setCentralWidget(file_tabs_);
93
	createMenu();
94
	setAcceptDrops(true);
95

96
	this->setWindowTitle(tr("Preview") + " ~ " + QCoreApplication::applicationName());
97
	createFindBar(); //do last to keep status bar hidden
98
	statusBar()->hide();
99
100
}

101
102
103
104
105
106
107
108
/**
 * @brief Destructor with minimal cleanup.
 */
PreviewWindow::~PreviewWindow()
{
	delete editor_key_filter_;
}

109
110
/**
 * @brief Display the current INI file in a new tab.
111
 * @param[in] infile Optional file name to load instead of the GUI values.
112
 */
113
void PreviewWindow::addIniTab(const QString& infile)
114
{
115
	const bool fromGUI = infile.isNull();
116
	/* get currently set INI values */
117
	QString ini_contents;
118
	if (fromGUI) //load INI from GUI
119
120
121
		loadIniWithGui(); //extend original file's INIParser with GUI values
	else
		preview_ini_.parseFile(infile); //load INI from file system
122

123
	/* text box for the current INI */
124
	const bool setMonospace = (getSetting("user::preview::mono_font", "value") == "TRUE");
125
	auto *preview_editor( new PreviewEdit(setMonospace, this) );
126
	preview_editor->installEventFilter(editor_key_filter_);
127
128
	preview_editor->setStyleSheet("QPlainTextEdit {background-color: " + colors::getQColor("syntax_background").name() +
		"; color: " + colors::getQColor("syntax_invalid").name() + "}");
129

130
	/* display the current GUI's contents */
131
	QTextStream ss(&ini_contents);
132
	preview_ini_.outputIni(ss);
133
	if (ini_contents.isEmpty()) {
134
135
		ini_contents = tr("#Empty INI file\n");
		previewStatus(tr("Open an application and load an INI file to view contents"));
136
137
138
	} else {
		previewStatus(QString());
		this->statusBar()->hide();
139
	}
140
	preview_editor->setPlainText(ini_contents); //without undo history --> can't undo to empty
141
142
143
144
145
146
147
148
149
	if (!fromGUI) preview_editor->setReadOnly(true); //INIs read directly from file are RO

	bool gui_is_saved = true;
	QString loaded_file( fromGUI? getMainWindow()->getIni()->getFilename() : infile );
	if (loaded_file.isEmpty()) { //pick file name if no INI is opened yet
		loaded_file = QDir::currentPath() + "/" + "unsaved("+QString::number(unsaved_ini_counter_)+").ini";
		unsaved_ini_counter_++;
	}
	if (fromGUI) { //check for difference between last saved (in GUI) and current state
150
		INIParser gui_ini = getMainWindow()->getIniCopy();
151
		(void) getMainWindow()->getControlPanel()->getSectionTab()->setIniValuesFromGui(&gui_ini);
152
		if (getMainWindow()->getIniCopy() != gui_ini)
153
			gui_is_saved = false;
154
	}
155
156
157
158
159
	preview_editor->setFile(loaded_file);
	//if loaded from GUI (i. e. not a different INI preview), and the GUI has not been saved...
	const QString shown_name( preview_editor->getFileName() + ((fromGUI && !gui_is_saved)? " *" : "") );
	file_tabs_->addTab(preview_editor, shown_name); //...open with 'unsaved' asterisk
	file_tabs_->setTabToolTip(file_tabs_->count() - 1, preview_editor->getFullFilePath());
160
	file_tabs_->setCurrentIndex(file_tabs_->count() - 1); //switch to new tab
161
162
163
	preview_editor->setFocus(); //ATT: the first ever focus inexplicably fires a textChanged()
	const int curr_tab_count = file_tabs_->count(); //a const to give to the lambda
	connect(preview_editor, &QPlainTextEdit::textChanged, this, [=]{ textChanged(curr_tab_count - 1); });
164
165
166

	onShowWhitespacesMenuClick((getSetting("user::preview::show_ws", "value") == "TRUE"));
} //TODO: tab completion for INI keys
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182

/**
 * @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;
		}
	}
183
	if (has_unsaved_changes &&
184
		getSetting("user::warnings::warn_unsaved_preview", "value") == "TRUE") { //at least one tab has unsaved changes
185
186
187
188
189
190
191
		const int cancel = warnOnUnsavedIni();
		if (cancel == QMessageBox::Cancel) {
			event->ignore();
			return;
		}
	}
	event->accept();
192
193
}

194
/**
195
196
 * @brief Event listener for key presses.
 * @details Close the Preview, add tab, or show the logger.
Michael Reisecker's avatar
Michael Reisecker committed
197
 * @param[in] event The key press event that is received.
198
199
200
 */
void PreviewWindow::keyPressEvent(QKeyEvent *event)
{
201
	if (event->key() == Qt::Key_Escape) {
202
		if (this->find_text_->isHidden())
203
204
205
			this->close();
		else
			hideFindBar();
206
207
208
209
210
211
	} else if (keyToSequence(event) == QKeySequence::Print) {
		addIniTab();
	} else if (event->modifiers() == Qt::CTRL && event->key() == Qt::Key_L) {
		getMainWindow()->getLogger()->show();
		getMainWindow()->getLogger()->raise();
	}
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
/**
 * @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());
}

239
240
241
242
/**
 * @brief Close an INI file's tab.
 * @param[in] index Index of the tab that is being closed.
 */
243
244
void PreviewWindow::closeTab(int index)
{
245
	//Check for unsaved changes. Note that changes that cancel out leaving the INI file
246
	//unaltered will still trigger the warning (unlike the GUI).
247
	if (file_tabs_->tabText(index).endsWith("*") &&
248
	    getSetting("user::warnings::warn_unsaved_preview", "value") == "TRUE") { //not saved yet
249
250
251
252
253
254
		const int cancel = warnOnUnsavedIni();
		if (cancel == QMessageBox::Cancel)
			return;
	}

	file_tabs_->removeTab(index);
255
256
	if (file_tabs_->count() == 0) {
		unsaved_ini_counter_ = 1; //reset auto-chosen display number
257
		this->close();
258
	}
259
260
}

261
262
263
/**
 * @brief Create the PreviewWindow's menu.
 */
264
265
void PreviewWindow::createMenu()
{
266
	/* FILE menu */
267
	QMenu *menu_file = this->menuBar()->addMenu(tr("&File"));
268
269
270
271
272
	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();
273
	auto *file_save = new QAction(getIcon("document-save"), tr("&Save"), menu_file);
274
	file_save->setShortcut( QKeySequence::Save );
275
276
	menu_file->addAction(file_save);
	connect(file_save, &QAction::triggered, this, &PreviewWindow::saveFile);
277
	auto *file_save_as = new QAction(getIcon("document-save-as"), tr("Save &as..."), menu_file);
278
	file_save_as->setShortcut( QKeySequence::SaveAs );
279
280
	menu_file->addAction(file_save_as);
	connect(file_save_as, &QAction::triggered, this, &PreviewWindow::saveFileAs);
281
	menu_file->addSeparator();
282
283
284
285
286
287
	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);
288
289
290
	menu_file->addSeparator();
	auto *file_backup = new QAction(tr("Quicksave backup"), menu_file);
	menu_file->addAction(file_backup);
291
	file_backup->setShortcut(Qt::CTRL + Qt::ALT + Qt::Key_B);
292
	connect(file_backup, &QAction::triggered, this, &PreviewWindow::quickBackup);
293
294
295
296
	auto *file_close_ = new QAction(getIcon("application-exit"), tr("&Close preview"), menu_file);
	file_close_->setShortcut(Qt::Key_Escape);
	menu_file->addAction(file_close_);
	connect(file_close_, &QAction::triggered, this, [=]{ this->close(); });
297

298
	/* EDIT menu */
299
	QMenu *menu_edit = this->menuBar()->addMenu(tr("&Edit"));
Mathias Bavay's avatar
Mathias Bavay committed
300
	auto *edit_undo = new QAction(getIcon("edit-undo"), tr("Undo"), menu_edit);
301
302
303
	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
304
	auto *edit_redo = new QAction(getIcon("edit-redo"), tr("Redo"), menu_edit);
305
306
307
308
	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
309
	auto *edit_cut = new QAction(getIcon("edit-cut"), tr("Cut"), menu_edit);
310
311
312
	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
313
	auto *edit_copy = new QAction(getIcon("edit-copy"), tr("Copy"), menu_edit);
314
315
316
	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
317
	auto *edit_paste = new QAction(getIcon("edit-paste"), tr("Paste"), menu_edit);
318
319
320
	menu_edit->addAction(edit_paste);
	edit_paste->setShortcut(QKeySequence::Paste);
	connect(edit_paste, &QAction::triggered, this, [=]{ getCurrentEditor()->paste(); });
321
322
	auto *edit_paste_newline = new QAction(tr("Paste to new line"), menu_edit);
	menu_edit->addAction(edit_paste_newline);
323
324
	edit_paste_newline->setShortcut("Alt+" +
	    QKeySequence(QKeySequence::Paste).toString(QKeySequence::NativeText));
325
	connect(edit_paste_newline, &QAction::triggered, this, [=]{ pasteToNewline(); });
Mathias Bavay's avatar
Mathias Bavay committed
326
	auto *edit_select_all = new QAction(getIcon("edit-select-all"), tr("Select all"), menu_edit);
327
328
329
330
331
332
333
334
335
	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);

336
337
	/* INSERT menu */
	QMenu *menu_insert = this->menuBar()->addMenu(tr("&Insert"));
338
339
340
341
342
343
	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);
344
345
346
	menu_insert->addAction(edit_insert_missing_);
	connect(edit_insert_missing_, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_missing"); });
347
	edit_insert_missing_mandatory_ = new QAction(tr("Mandatory keys for GUI"),
348
349
350
351
352
	     menu_insert);
	menu_insert->addAction(edit_insert_missing_mandatory_);
	connect(edit_insert_missing_mandatory_, &QAction::triggered, this,
	    [=]{ onInsertMenuClick("insert_missing_mandatory"); });

353
	/* TRANSFORM menu */
354
	QMenu *menu_transform = this->menuBar()->addMenu(tr("&Transform"));
355
	/* Whitespaces menu */
356
	auto *transform_whitespaces = new QMenu(tr("Whitespaces"), menu_transform);
357
	transform_whitespaces->setIcon( getIcon("markasblank") );
358
	menu_transform->addMenu(transform_whitespaces);
Mathias Bavay's avatar
Mathias Bavay committed
359
	auto *transform_transform_singlews = new QAction(getIcon("unmarkasblank"), tr("To single spaces"), transform_whitespaces);
360
361
362
	connect(transform_transform_singlews, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_whitespace_singlews"); } );
	transform_whitespaces->addAction(transform_transform_singlews);
363
364
	auto *transform_transform_longestws = new QAction(tr("Adapt to longest keys"),
	    transform_whitespaces);
365
366
367
	connect(transform_transform_longestws, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_whitespace_longestws"); } );
	transform_whitespaces->addAction(transform_transform_longestws);
368
	/* Sort */
369
	auto *transform_sort = new QMenu(tr("Sort"), menu_transform);
Mathias Bavay's avatar
Mathias Bavay committed
370
	transform_sort->setIcon( getIcon("view-sort") );
371
372
373
374
375
376
377
378
379
	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);
380
	/* Capitalization menu */
381
382
	auto *transform_capitalization = new QMenu(tr("Capitalization"), menu_transform);
	menu_transform->addMenu(transform_capitalization);
383
	auto *transform_capitalization_sections_upper = new QAction(
384
385
386
387
	    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);
388
	auto *transform_capitalization_sections_lower = new QAction(
389
390
391
392
	    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);
393
	auto *transform_capitalization_keys_upper = new QAction(
394
395
396
397
	    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);
398
	auto *transform_capitalization_keys_lower = new QAction(
399
400
401
402
	    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);
403
	auto *transform_capitalization_values_upper = new QAction(
404
405
406
407
	    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);
408
	auto *transform_capitalization_values_lower = new QAction(
409
410
411
412
413
414
415
	    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);
416
417
418
	connect(transform_capitalization_upper, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_upper"); } );
	transform_capitalization->addAction(transform_capitalization_upper);
419
420
	auto *transform_capitalization_lower = new QAction(getIcon("format-text-lowercase"),
	    tr("All to lower case"), transform_capitalization);
421
422
423
	connect(transform_capitalization_lower, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_capitalization_lower"); } );
	transform_capitalization->addAction(transform_capitalization_lower);
424
	/* Comments menu */
425
	auto *transform_comments = new QMenu(tr("Comments"), menu_transform);
426
	transform_comments->setIcon( getIcon("code-context") );
427
	menu_transform->addMenu(transform_comments);
428
429
430
431
432
433
434
435
436
437
	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"); });
438
	transform_comments->addSeparator();
439
	auto *transform_comments_content = new QAction(tr("Comment all content"),
440
	    transform_comments);
441
442
443
	connect(transform_comments_content, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_content"); } );
	transform_comments->addAction(transform_comments_content);
444
	auto *transform_comments_duplicate = new QAction(tr("Duplicate all to comment"),
445
	    transform_comments);
446
	transform_comments_duplicate->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_B);
447
448
449
	connect(transform_comments_duplicate, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_duplicate"); } );
	transform_comments->addAction(transform_comments_duplicate);
450
451
452
453
454
	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);
455
	auto *transform_comments_move_end = new QAction(tr("Collect at bottom"),
456
	    transform_comments);
457
458
459
	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
460
	auto *transform_comments_trim = new QAction(getIcon("edit-clear-all"), tr("Trim"), transform_comments);
461
462
463
464
	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);
465
466
467
	connect(transform_comments_delete, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_comments_delete"); } );
	transform_comments->addAction(transform_comments_delete);
468
	transform_comments->addSeparator();
469
470
471
472
473
474
475
476
477
	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 */
478
	auto *transform_reset = new QMenu(tr("Reset"), menu_transform);
Mathias Bavay's avatar
Mathias Bavay committed
479
	transform_reset->setIcon( getIcon("view-refresh") );
480
	menu_transform->addMenu(transform_reset);
481
482
	auto *transform_reset_original = new QAction(tr("To original INI on file system"),
	    transform_reset);
483
484
485
	connect(transform_reset_original, &QAction::triggered, this,
	    [=]{ onTransformMenuClick("transform_reset_original"); } );
	transform_reset->addAction(transform_reset_original);
486
487
	transform_reset_full_ = new QAction(tr("To full INI with GUI keys"), transform_reset);
	connect(transform_reset_full_, &QAction::triggered, this,
488
	    [=]{ onTransformMenuClick("transform_reset_full"); } );
489
	transform_reset->addAction(transform_reset_full_);
490

491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
	/* 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);

512
	/* VIEW menu */
513
	QMenu *menu_view = this->menuBar()->addMenu(tr("&View"));
514
515
516
517
518
519
520
521
	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();
522
	auto *view_new_tab = new QAction(getIcon("tab-new"), tr("&New tab"), menu_view);
523
	view_new_tab->setShortcut(QKeySequence::AddTab);
524
525
	connect(view_new_tab, &QAction::triggered, this, [=]{ addIniTab(); });
	menu_view->addAction(view_new_tab);
526
	auto *view_close_tab = new QAction(getIcon("tab-close"), tr("&Close tab"), menu_view);
527
528
529
	view_close_tab->setShortcut(QKeySequence::Close);
	connect(view_close_tab, &QAction::triggered, this, [=]{ closeTab(file_tabs_->currentIndex()); });
	menu_view->addAction(view_close_tab);
530
531

	/* HELP menu */
532
#if !defined Q_OS_MAC //use extra tab bar that is pushed to the right
533
534
	auto *menu_help_main = new QMenuBar(this->menuBar());
	QMenu *menu_help = menu_help_main->addMenu(tr("&?"));
535
	menu_help_main->addMenu(menu_help);
Michael Reisecker's avatar
Michael Reisecker committed
536
	auto *help = new QAction(getIcon("help-contents"), tr("Preview &help"), menu_help);
537
	help->setShortcut(QKeySequence::HelpContents);
538
	this->menuBar()->setCornerWidget(menu_help_main); //push help menu to the right
539
	menu_help->addAction(help);
540
#else  //normal menu that can be re-ordered by Qt/macOS
541
	auto *menu_help_main = this->menuBar()->addMenu("&?");
Michael Reisecker's avatar
Michael Reisecker committed
542
543
	auto *help = new QAction(getIcon("help-contents"), tr("Preview &help"), menu_help_main);
	help->setMenuRole(QAction::ApplicationSpecificRole);
544
545
	menu_help_main->addAction(help);
#endif
546
547
	connect(help, &QAction::triggered, this,
	    [=]{ getMainWindow()->loadHelp("UI of INIshell", "help-preview"); });
548
549
550
}

/**
551
 * @brief Prepare a panel in the status bar that allows users to search for text in the preview.
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
 */
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();
587
588
}

589
590
591
592
593
594
595
596
/**
 * @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)
{
597
	file_tabs_->setTabText(index, getCurrentEditor()->getFileName() + " *");
598
599
}

600
601
602
603
604
605
/**
 * @brief Combine the original file's INIParser with GUI values and
 * set the local copy to access both.
 */
void PreviewWindow::loadIniWithGui()
{
606
	const QString current_app( getMainWindow()->getCurrentApplication() );
607
	preview_ini_ = getMainWindow()->getIniCopy();
608
609
	preview_ini_.clear(true); //only keep unknown keys (which are transported from input to output)

610
	getMainWindow()->getControlPanel()->getSectionTab()->setIniValuesFromGui(&preview_ini_);
611
	file_save_and_load_->setText(tr("Save and load into ") + getMainWindow()->getCurrentApplication());
612
	file_load_->setText(tr("Load into ") + current_app);
613
614
615
	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));
616
617
}

618
619
620
621
622
623
624
625
/**
 * @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)) {
626
		previewStatus(tr("Could not open %1").arg(QDir::toNativeSeparators(file_name)));
627
628
629
		return;
	}
	QTextStream ss(&outfile);
630
	const auto text_box( getCurrentEditor() );
631
632
633
634
	if (text_box)
		ss << text_box->toPlainText();
	outfile.close();

635
636
637
	getCurrentEditor()->setFile(file_name);
	//switch the displayed name to new file (without asterisk):
	file_tabs_->setTabText(file_tabs_->currentIndex(), getCurrentEditor()->getFileName());
638
	previewStatus(tr("Saved to ") + file_name);
639

640
	setSetting("auto::history::last_preview_write", "path", getCurrentEditor()->getFilePath());
641
642
643
644
645
646
647
648
649
}

/**
 * @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()
{
650
651
652
653
	const QString msg( tr("Preview INI not saved yet") );
	const QString informative( tr("Your INI file preview(s) may contain unsaved changes.") );
	const QFlags<QMessageBox::StandardButton> buttons( QMessageBox::Cancel | QMessageBox::Discard );
	RememberDialog msgNotSaved("user::warnings::warn_unsaved_preview", msg, informative, QString(), buttons, this);
654
655
656
657
	int clicked = msgNotSaved.exec();
	return clicked;
}

658
659
660
661
662
/**
 * @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)
663
{ //temporary message - erased for e. g. on menu hover
664
665
	statusBar()->showMessage(text);
	statusBar()->show(); //might be hidden from closing the find bar
666
	statusBar()->setToolTip(text);
667
668
}

669
/**
670
671
 * @brief Helper function to get the current tab's text editor.
 * @return The text editor currently in view.
672
 */
673
PreviewEdit * PreviewWindow::getCurrentEditor() const
674
{
675
#ifdef DEBUG
676
677
	if (!qobject_cast<PreviewEdit *>(file_tabs_->currentWidget()))
		qDebug() << "PreviewWindow::getCurrentEditor() should have casted to a PreviewEdit but did not";
678
#endif //def DEBUG
679
	return qobject_cast<PreviewEdit *>(file_tabs_->currentWidget());
680
681
}

682
683
684
685
686
687
688
/**
 * @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.
 */
689
void PreviewWindow::setTextWithHistory(QPlainTextEdit *editor, const QString &text)
690
691
692
693
694
695
696
{
	QTextDocument *doc( editor->document() );
	QTextCursor cursor( doc );
	cursor.select(QTextCursor::Document);
	cursor.insertText(text);
}

697
698
699
700
/**
 * @brief Insert missing keys.
 * @details This function looks through the keys in the GUI and adds the
 * ones that are missing.
701
 * @param[in] mode Insert mode (fill missing, fill missing mandatory).
702
 */
703
void PreviewWindow::insertText(const insert_text &mode)
704
{
705
	if (mode == HEADER) {
706
		static const QString marker( QString("#").repeated(60) );
707
708
		const QString year( QDate::currentDate().toString("yyyy") );
		const QString date( QDate::currentDate().toString("yyyy-MM-dd") );
709
		const QString username( os::getLogName() );
710
		const QString user_domain( QHostInfo::localDomainName() );
711
712
713
714
715
716
717
718
		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);
719
		for (int ii=copyright.size()+1; ii<marker.size(); ii++)
720
			copyright.append(" ");
Michael Reisecker's avatar
Michael Reisecker committed
721

722
		QString header;
723
		header += marker + "\n";
724
		header += copyright + "#\n";
725
		header += marker + "\n";
726
727
		header += "#" + QCoreApplication::applicationName() + " " + APP_VERSION_STR;
		header += " for " + getMainWindow()->getCurrentApplication() + "\n";
728
729
730
731
732
		header += "#" + date + "\n\n";
		preview_ini_.parseText(getCurrentEditor()->toPlainText().prepend(header));
		return;
	}

733
	INIParser gui_ini(getMainWindow()->getLogger());
734
	getMainWindow()->getControlPanel()->getSectionTab()->setIniValuesFromGui(&gui_ini, true);
735
736
737
	int counter = 0;
	for (auto &sec : *gui_ini.getSections()) {
		for (auto &keyval : sec.getKeyValueList()) {
Michael Reisecker's avatar
Michael Reisecker committed
738
			if (!preview_ini_.hasKeyValue(keyval.first)) {
739
740
741
				if ((mode == MISSING) ||
				    (mode == MISSING_MANDATORY && keyval.second.isMandatory())) {
					QString value( keyval.second.getValue() );
742
					preview_ini_.set(sec.getName(), keyval.first, value);
743
744
745
					counter++;
				}
			}
746
		} //endfor keyval
747
748
749
750
	}
	previewStatus(tr("Inserted %1 keys").arg(counter));
}

751
752
753
754
755
756
757
758
759
760
761
/**
 * @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(
762
				    std::vector<QString>( {"", " ", " ", " "} )); //(0)key(1)=(2)value(3)#comment
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
		}
		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)
{
787
788
789
790
791
792
793
	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()) {
794
		if (section || all)
795
			sec.setName(lower? sec.getName().toLower() : sec.getName().toUpper());
796
		if (!section || all) {
797
798
			for (auto &key : sec.getKeyValueList()) {
				auto *keyvalue = sec.getKeyValue(key.first);
799
800
801
				if (value || all) {
					keyvalue->setValue(lower? keyvalue->getValue().toLower() :
					    keyvalue->getValue().toUpper());
802
803
				}
				if (!value || all) {
804
805
806
807
808
809
					keyvalue->setKey(lower? keyvalue->getKey().toLower() :
					    keyvalue->getKey().toUpper());
				}
			} //endfor key
		} //endif section
	} //endfor sec
810
811
812
813
814
}

/**
 * @brief Perform transformations concerning INI comments on the local INIParser copy.
 * @param[in] mode Type of transformation.
815
 * @return True if at least one comment prefix was removed.
816
 */
817
bool PreviewWindow::transformComments(const transform_comments &mode)
818
{
819
	bool removed_comment = false;
820
821
822
	if (mode == BLOCK_COMMENT || mode == BLOCK_UNCOMMENT) { //block (un)comment
		int first_line, last_line;
		getSelectionMargins(first_line, last_line); //span of selected lines
823
		QStringList lines( getCurrentEditor()->toPlainText().split("\n") );
824
825
826
827
828
829
830
831
832
833
834
		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);
835
					removed_comment = true;
836
837
838
839
				}
			}
		}
		setTextWithHistory(getCurrentEditor(), lines.join("\n"));
840
841
842
843
844
845
846
847
848
849
850
851
852
853
	} 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"));
854
855
856
857
858
859
860
861
862
863
864
	} 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);
			}
		}
865
	} else if (mode == MOVE_TO_END) { //collect all comments at end of file
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
		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);
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
	} else if (mode == TRIM) {
		preview_ini_.setBlockCommentAtEnd(trimComment(preview_ini_.getBlockCommentAtEnd()));
		for (auto &sec : *preview_ini_.getSections()) {
			sec.setBlockComment(trimComment(sec.getBlockComment()));
			sec.setInlineComment(trimComment(sec.getInlineComment()));
			for (auto &key : sec.getKeyValueList()) {
				auto *keyvalue = sec.getKeyValue(key.first);
				keyvalue->setBlockComment(trimComment(keyvalue->getBlockComment()));
				keyvalue->setInlineComment(trimComment(keyvalue->getInlineComment()));
			}
		}
	} else if (mode == DELETE) { //delete all comments
		preview_ini_.setBlockCommentAtEnd(QString());
		for (auto &sec : *preview_ini_.getSections()) {
			sec.setBlockComment(QString());
			sec.setInlineComment(QString());
			for (auto &key : sec.getKeyValueList()) {
				auto *keyvalue = sec.getKeyValue(key.first);
				keyvalue->setBlockComment(QString());
				keyvalue->setInlineComment(QString());
			}
		}
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
	} else if (mode == CONVERT_NUMBERSIGN || mode == CONVERT_SEMICOLON) {
		const bool hash = (mode == CONVERT_NUMBERSIGN);
		for (auto &sec : *preview_ini_.getSections()) {
			if (!sec.getBlockComment().isEmpty())
				sec.setBlockComment(convertPrefix(sec.getBlockComment(), hash));
			if (!sec.getInlineComment().isEmpty())
				sec.setInlineComment(convertPrefix(sec.getInlineComment(), hash));
			for (auto &key : sec.getKeyValueList()) {
				auto *keyvalue = sec.getKeyValue(key.first);
				if (!keyvalue->getBlockComment().isEmpty())
					keyvalue->setBlockComment(convertPrefix(
					    keyvalue->getBlockComment(), hash));
				if (!keyvalue->getInlineComment().isEmpty())
					keyvalue->setInlineComment(convertPrefix(
					    keyvalue->getInlineComment(), hash));
			}
			if (!preview_ini_.getBlockCommentAtEnd().isEmpty())
				preview_ini_.setBlockCommentAtEnd(convertPrefix(
				    preview_ini_.getBlockCommentAtEnd(), hash));
		} //endfor sec
924
	}
925
	return removed_comment; //for text selection handling
926
927
}

928
929
930
931
932
933
/**
 * @brief Conversion between spaces and tabs and vice versa.
 * @param[in] mode Mode of operation
 */
void PreviewWindow::convertTabs(const convert_tabs &mode)
{
934
	QPlainTextEdit *current_editor( getCurrentEditor() );
935
936
937
938
939
940
941
942
943
944
945
946
	QString current_text( current_editor->toPlainText() );
	QString new_text;
	if (mode == LONG_SPACES_TO_TABS || mode == SHORT_SPACES_TO_TABS) {
		new_text = current_text.replace(QString(" ").repeated(
		    mode == SHORT_SPACES_TO_TABS? short_spaces_for_tabs : long_spaces_for_tabs), "\t");
	} else if (mode == TABS_TO_LONG_SPACES || mode == TABS_TO_SHORT_SPACES) {
		new_text = current_text.replace("\t", QString(" ").repeated(
		    mode == TABS_TO_SHORT_SPACES? short_spaces_for_tabs : long_spaces_for_tabs));
	}
	preview_ini_.parseText(new_text);
}

947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
/**
 * @brief Return the current cursor's line number in the file.
 * @return The current line number.
 */
int PreviewWindow::getCurrentLineNumber()
{
	int nr_of_lines = 1;
	QTextCursor cursor( getCurrentEditor()->textCursor() );
	cursor.movePosition(QTextCursor::StartOfLine);
	//count line numbers in current block:
	while(cursor.positionInBlock() > 0) {
		cursor.movePosition(QTextCursor::Up);
		nr_of_lines++;
	}
	//count line numbers in all blocks above that:
	QTextBlock block( cursor.block().previous() );
	while(block.isValid()) {
		nr_of_lines += block.lineCount();
		block = block.previous();
	}
	return nr_of_lines;
968
} //this is obviously a bit of a HACK: but there doesn't seem to be a good way
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998

/**
 * @brief Find the number of currently selected lines.
 * @return Number of selected lines.
 */
int PreviewWindow::getNrOfSelectedLines()
{
	const QTextCursor cursor( getCurrentEditor()->textCursor() );
	return cursor.selectedText().split(paragraph_separator).count();
}

/**
 * @brief Return line number of text selection start and selection end.
 * @details The current cursor line will change depending on if the user
 * selects text from top to bottom or from bottom to top.
 * @param[out] first_line Line number of selection start.
 * @param[out] last_line Line number of selection end.
 */
void PreviewWindow::getSelectionMargins(int &first_line, int &last_line)
{
	const QTextCursor cursor( getCurrentEditor()->textCursor() );
	const int current_line = getCurrentLineNumber();

	if (cursor.position() > cursor.selectionStart()) { //selected from top to bottom
		first_line = current_line - getNrOfSelectedLines() + 1;
		last_line = current_line;
	} else { //bottom to top or nothing
		first_line = current_line;
		last_line = current_line + getNrOfSelectedLines() - 1;
	}
999
1000
}

For faster browsing, not all history is shown. View entire blame