aboutsummaryrefslogtreecommitdiffstats
path: root/qt-ui/printlayout.cpp
blob: dad940fbb1e30d8c8b840385878a320d362a0bc0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#include <QtCore/qmath.h>
#include <QDebug>
#include <QPainter>
#include <QDesktopWidget>
#include <QApplication>
#include <QTableView>
#include <QHeaderView>
#include "mainwindow.h"
#include "profilegraphics.h"
#include "../dive.h"
#include "../display.h"
#include "printdialog.h"
#include "printlayout.h"
#include "models.h"
#include "modeldelegates.h"

PrintLayout::PrintLayout(PrintDialog *dialogPtr, QPrinter *printerPtr, struct options *optionsPtr)
{
	dialog = dialogPtr;
	printer = printerPtr;
	printOptions = optionsPtr;

	// table print settings
	tablePrintHeadingBackground = 0xffeeeeee;
	tablePrintColumnNames.append(tr("Dive#"));
	tablePrintColumnNames.append(tr("Date"));
	tablePrintColumnNames.append(tr("Depth"));
	tablePrintColumnNames.append(tr("Duration"));
	tablePrintColumnNames.append(tr("Master"));
	tablePrintColumnNames.append(tr("Buddy"));
	tablePrintColumnNames.append(tr("Location"));
	tablePrintColumnWidths.append(7);
	tablePrintColumnWidths.append(10);
	tablePrintColumnWidths.append(10);
	tablePrintColumnWidths.append(10);
	tablePrintColumnWidths.append(15);
	tablePrintColumnWidths.append(15);
	tablePrintColumnWidths.append(33);
	// profile print settings
	const int dw = 20; // base percentage
	profilePrintColumnWidths.append(dw);
	profilePrintColumnWidths.append(dw);
	profilePrintColumnWidths.append(dw - 3);
	profilePrintColumnWidths.append(dw - 3);
	profilePrintColumnWidths.append(dw + 6); // fit to 100%
	const int sr = 12; // smallest row height in pixels
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr + 4);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
	profilePrintRowHeights.append(sr);
}

void PrintLayout::print()
{
	// we call setup each time to check if the printer properties have changed
	setup();
	switch (printOptions->type) {
	case options::PRETTY:
		printProfileDives(3, 2);
		break;
	case options::TWOPERPAGE:
		printProfileDives(2, 1);
		break;
	case options::TABLE:
		printTable();
		break;
	}
}

void PrintLayout::setup()
{
	QDesktopWidget *desktop = QApplication::desktop();
	screenDpiX = desktop->physicalDpiX();
	screenDpiY = desktop->physicalDpiY();

	printerDpi = printer->resolution();
	pageRect = printer->pageRect();

	scaleX = (qreal)printerDpi/(qreal)screenDpiX;
	scaleY = (qreal)printerDpi/(qreal)screenDpiY;

	// a printer page scalled to screen DPI
	scaledPageW = pageRect.width() / scaleX;
	scaledPageH = pageRect.height() / scaleY;
}

// go trought the dive table and find how many dives we are a going to print
int PrintLayout::estimateTotalDives() const
{
	int total = 0, i = 0;
	struct dive *dive;
	for_each_dive(i, dive) {
		if (!dive->selected && printOptions->print_selected)
			continue;
		total++;
	}
	return total;
}

/* the used formula here is:
 * s = (S - (n - 1) * p) / n
 * where:
 * s is the length of a single element (unknown)
 * S is the total available length
 * n is the number of elements to fit
 * p is the padding between elements
 */
#define ESTIMATE_DIVE_DIM(S, n, p) \
	 ((S) - ((n) - 1) * (p)) / (n);

void PrintLayout::printProfileDives(int divesPerRow, int divesPerColumn)
{
	int i, row = 0, col = 0, printed = 0, total = estimateTotalDives();
	struct dive *dive;
	if (!total)
		return;

	// setup a painter
	QPainter painter;
	painter.begin(printer);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);
	painter.scale(scaleX, scaleY);

	// setup the profile widget
	ProfileGraphicsView *profile = mainWindow()->graphics();
	const int profileFrameStyle = profile->frameStyle();
	profile->setFrameStyle(QFrame::NoFrame);
	profile->clear();
	profile->setPrintMode(true, !printOptions->color_selected);
	QSize originalSize = profile->size();
	// swap rows/col for landscape
	if (printer->orientation() == QPrinter::Landscape) {
		int swap = divesPerColumn;
		divesPerColumn = divesPerRow;
		divesPerRow = swap;
	}
	// padding in pixels between two dives. no padding if only one dive per page.
	const int padDef = 20;
	const int padW = (divesPerColumn < 2) ? 0 : padDef;
	const int padH = (divesPerRow < 2) ? 0 : padDef;
	// estimate dimensions for a single dive
	const int scaledW = ESTIMATE_DIVE_DIM(scaledPageW, divesPerColumn, padW);
	const int scaledH = ESTIMATE_DIVE_DIM(scaledPageH, divesPerRow, padH);
	// padding in pixels between profile and table
	const int padPT = 5;
	// create a model and table
	ProfilePrintModel model;
	QTableView *table = createProfileTable(&model, scaledW);
	// profilePrintTableMaxH updates after the table is created
	const int tableH = profilePrintTableMaxH;
	// resize the profile widget
	profile->resize(scaledW, scaledH - tableH - padPT);
	// offset table or profile on top
	int yOffsetProfile = 0, yOffsetTable = 0;
	if (printOptions->notes_up)
		yOffsetProfile = tableH + padPT;
	else
		yOffsetTable = scaledH - tableH;

	// plot the dives at specific rows and columns on the page
	for_each_dive(i, dive) {
		if (!dive->selected && printOptions->print_selected)
			continue;
		if (col == divesPerColumn) {
			col = 0;
			row++;
			if (row == divesPerRow) {
				row = 0;
				printer->newPage();
			}
		}
		QTransform origTransform = painter.transform();

		// draw a profile
		painter.translate((scaledW + padW) * col, (scaledH + padH) * row + yOffsetProfile);
		profile->plot(dive, true);
		profile->render(&painter, QRect(0, 0, scaledW, scaledH - tableH - padPT));
		painter.setTransform(origTransform);

		// draw a table
		painter.translate((scaledW + padW) * col, (scaledH + padH) * row + yOffsetTable);
		model.setDive(dive);
		table->render(&painter);
		painter.setTransform(origTransform);
		col++;
		printed++;
		emit signalProgress((printed * 100) / total);
	}

	// cleanup
	painter.end();
	delete table;
	profile->setFrameStyle(profileFrameStyle);
	profile->setPrintMode(false);
	profile->resize(originalSize);
	profile->clear();
	profile->plot(current_dive, true);
}

/* we create a table that has a fixed height, but can stretch to fit certain width */
QTableView *PrintLayout::createProfileTable(ProfilePrintModel *model, const int tableW)
{
	// setup a new table
	QTableView *table = new QTableView();
	QHeaderView *vHeader = table->verticalHeader();
	QHeaderView *hHeader = table->horizontalHeader();
	table->setAttribute(Qt::WA_DontShowOnScreen);
	table->setSelectionMode(QAbstractItemView::NoSelection);
	table->setFocusPolicy(Qt::NoFocus);
	table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	hHeader->setVisible(false);
	hHeader->setResizeMode(QHeaderView::Fixed);
	vHeader->setVisible(false);
	vHeader->setResizeMode(QHeaderView::Fixed);
	// set the model
	table->setModel(model);

	/* setup cell span for the table using QTableView::setSpan().
	 * changes made here reflect on ProfilePrintModel::data(). */
	const int cols = model->columnCount();
	const int rows = model->rowCount();
	// info on top
	table->setSpan(0, 0, 1, 4);
	table->setSpan(1, 0, 1, 4);
	// gas used
	table->setSpan(2, 0, 1, 2);
	table->setSpan(3, 0, 1, 2);
	// notes
	table->setSpan(6, 0, 1, 5);
	table->setSpan(7, 0, 5, 5);

	/* resize row heights to the 'profilePrintRowHeights' indexes.
	 * profilePrintTableMaxH will then hold the table height. */
	int i;
	profilePrintTableMaxH = 0;
	for (i = 0; i < rows; i++) {
		int h = profilePrintRowHeights.at(i);
		profilePrintTableMaxH += h;
		vHeader->resizeSection(i, h);
	}
	// resize columns. columns widths are percentages from the table width.
	int accW = 0;
	for (i = 0; i < cols; i++) {
		int pw = qCeil((qreal)(profilePrintColumnWidths.at(i) * tableW) / 100.0);
		accW += pw;
		if (i == cols - 1 && accW > tableW) /* adjust last column */
			pw -= accW - tableW;
		hHeader->resizeSection(i, pw);
	}
	// resize
	table->resize(tableW, profilePrintTableMaxH);
	// hide the grid and set a stylesheet
	table->setItemDelegate(new ProfilePrintDelegate());
	table->setShowGrid(false);
	table->setStyleSheet(
		"QTableView { border: none }"
		"QTableView::item { border: 0px; padding-left: 2px; padding-right: 2px; }"
	);
	// return
	return table;
}

void PrintLayout::printTable()
{
	struct dive *dive;
	int done = 0; // percents done
	int i, row = 0, progress, total = estimateTotalDives();
	if (!total)
		return;

	// create and setup a table
	QTableView table;
	table.setAttribute(Qt::WA_DontShowOnScreen);
	table.setSelectionMode(QAbstractItemView::NoSelection);
	table.setFocusPolicy(Qt::NoFocus);
	table.horizontalHeader()->setVisible(false);
	table.horizontalHeader()->setResizeMode(QHeaderView::Fixed);
	table.verticalHeader()->setVisible(false);
	table.verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
	table.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	table.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	// fit table to one page initially
	table.resize(scaledPageW,  scaledPageH);

	// don't show border
	table.setStyleSheet(
		"QTableView { border: none }"
	);

	// create and fill a table model
	TablePrintModel model;
	addTablePrintHeadingRow(&model, row); // add one heading row
	row++;
	progress = 0;
	for_each_dive(i, dive) {
		if (!dive->selected && printOptions->print_selected)
			continue;
		addTablePrintDataRow(&model, row, dive);
		row++;
		progress++;
		emit signalProgress((progress * 10) / total);
	}
	done = 10;
	table.setModel(&model); // set model to table
	// resize columns to percentages from page width
	int accW = 0;
	int cols = model.columns;
	int tableW = table.width();
	for (int i = 0; i < model.columns; i++) {
		int pw = qCeil((qreal)(tablePrintColumnWidths.at(i) * table.width()) / 100.0);
		accW += pw;
		if (i == cols - 1 && accW > tableW) /* adjust last column */
			pw -= accW - tableW;
		table.horizontalHeader()->resizeSection(i, pw);
	}
	// reset the model at this point
	model.callReset();

	// a list of vertical offsets where pages begin and some helpers
	QList<unsigned int> pageIndexes;
	pageIndexes.append(0);

	/* the algorithm bellow processes the table rows in multiple passes,
	 * compensating for loss of space due to moving rows on a new page instead
	 * of truncating them.
	 * there is a 'passes' array defining how much percents of the total
	 * progress each will take. given, the first and last stage of this function
	 * use 10% each, then the sum of passes[] here should be 80%.
	 * two should be enough! */
	const int passes[] = { 70, 10 };
	int tableHeight = 0, lastAccIndex = 0, rowH, accH, headings;
	bool isHeading = false;

	for (unsigned int pass = 0; pass < sizeof(passes) / sizeof(passes[0]); pass++) {
		progress = headings = accH = 0;
		total = model.rows - lastAccIndex;
		for (int i = lastAccIndex; i < model.rows; i++) {
			rowH = table.rowHeight(i);
			accH += rowH;
			if (isHeading) {
				headings += rowH;
				isHeading = false;
			}
			if (accH > scaledPageH) {
				lastAccIndex = i;
				pageIndexes.append(pageIndexes.last() + (accH - rowH));
				addTablePrintHeadingRow(&model, i);
				isHeading = true;
				accH = 0;
				i--;
			}
			tableHeight += table.rowHeight(i);
			progress++;
			emit signalProgress(done + (progress * passes[pass]) / total);
		}
		done += passes[pass];
	}
	done = 90;
	pageIndexes.append(pageIndexes.last() + accH + headings);
	table.resize(scaledPageW, tableHeight);

	// attach a painter and render pages by using pageIndexes
	QPainter painter(printer);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.setRenderHint(QPainter::SmoothPixmapTransform);
	painter.scale(scaleX, scaleY);
	total = pageIndexes.size() - 1;
	progress = 0;
	for (int i = 0; i < total; i++) {
		if (i > 0)
			printer->newPage();
		QRegion region(0, pageIndexes.at(i) - 1,
			       table.width(),
			       pageIndexes.at(i + 1) - pageIndexes.at(i) + 1);
		table.render(&painter, QPoint(0, 0), region);
		progress++;
		emit signalProgress(done + (progress * 10) / total);
	}
}

void PrintLayout::addTablePrintDataRow(TablePrintModel *model, int row, struct dive *dive) const
{
	struct DiveItem di;
	di.dive = dive;
	model->insertRow();
	model->setData(model->index(row, 0), QString::number(dive->number), Qt::DisplayRole);
	model->setData(model->index(row, 1), di.displayDate(), Qt::DisplayRole);
	model->setData(model->index(row, 2), di.displayDepth(), Qt::DisplayRole);
	model->setData(model->index(row, 3), di.displayDuration(), Qt::DisplayRole);
	model->setData(model->index(row, 4), dive->divemaster, Qt::DisplayRole);
	model->setData(model->index(row, 5), dive->buddy, Qt::DisplayRole);
	model->setData(model->index(row, 6), dive->location, Qt::DisplayRole);
}

void PrintLayout::addTablePrintHeadingRow(TablePrintModel *model, int row) const
{
	model->insertRow(row);
	for (int i = 0; i < model->columns; i++) {
		model->setData(model->index(row, i), tablePrintColumnNames.at(i), Qt::DisplayRole);
		model->setData(model->index(row, i), tablePrintHeadingBackground, Qt::BackgroundRole);
	}
}