summaryrefslogtreecommitdiffstats
path: root/commands/command_base.cpp
blob: 8ebbf9be545c975fe2b07249e371a34b06d75d8e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// SPDX-License-Identifier: GPL-2.0

#include "command_base.h"
#include "core/qthelper.h" // for updateWindowTitle()
#include "core/subsurface-qt/divelistnotifier.h"
#include <QVector>

namespace Command {

static QUndoStack undoStack;

// forward declaration
QString changesMade();

// General commands
void init()
{
	QObject::connect(&undoStack, &QUndoStack::cleanChanged, &updateWindowTitle);
	changesCallback = &changesMade;
}

void clear()
{
	undoStack.clear();
}

void setClean()
{
	undoStack.setClean();
}

bool isClean()
{
	return undoStack.isClean();
}

// this can be used to get access to the signals emitted by the QUndoStack
QUndoStack *getUndoStack()
{
	return &undoStack;
}

QAction *undoAction(QObject *parent)
{
	return undoStack.createUndoAction(parent, QCoreApplication::translate("Command", "&Undo"));
}

QAction *redoAction(QObject *parent)
{
	return undoStack.createRedoAction(parent, QCoreApplication::translate("Command", "&Redo"));
}

QString diveNumberOrDate(struct dive *d)
{
	if (d->number != 0)
		return QStringLiteral("#%1").arg(d->number);
	else
		return QStringLiteral("@%1").arg(get_short_dive_date_string(d->when));
}

QString getListOfDives(const std::vector<struct dive*> &dives)
{
	QString listOfDives;
	if ((int)dives.size() == dive_table.nr)
		return Base::tr("all dives");
	int i = 0;
	for (dive *d: dives) {
		// we show a maximum of five dive numbers, or 4 plus ellipsis
		if (++i == 4 && dives.size() >= 5)
			return listOfDives + "...";
		listOfDives += diveNumberOrDate(d) + ", ";
	}
	if (!listOfDives.isEmpty())
		listOfDives.truncate(listOfDives.length() - 2);
	return listOfDives;
}

QString getListOfDives(QVector<struct dive *> dives)
{
	return getListOfDives(std::vector<struct dive *>(dives.begin(), dives.end()));
}


// return a string that can be used for the commit message and should list the changes that
// were made to the dive list
QString changesMade()
{
	QString changeTexts;
	for (int i = 0; i < undoStack.index(); i++)
		changeTexts += undoStack.text(i) + "\n";
	return changeTexts;
}

bool execute(Base *cmd)
{
	if (cmd->workToBeDone()) {
		undoStack.push(cmd);
		emit diveListNotifier.commandExecuted();
		return true;
	} else {
		delete cmd;
		return false;
	}
}

} // namespace Command