[go: up one dir, main page]

File: dataloader.cpp

package info (click to toggle)
qgit 2.3-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 1,152 kB
  • ctags: 1,477
  • sloc: cpp: 11,857; makefile: 51; sh: 39
file content (318 lines) | stat: -rw-r--r-- 8,386 bytes parent folder | download
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
/*
	Description: async stream reader, used to load repository data on startup

	Author: Marco Costalba (C) 2005-2007

	Copyright: See COPYING file that comes with this distribution

*/
#include <QDir>
#include <QTemporaryFile>
#include "git.h"
#include "dataloader.h"

#define GUI_UPDATE_INTERVAL 500
#define READ_BLOCK_SIZE     65535

class UnbufferedTemporaryFile : public QTemporaryFile {
public:
	explicit UnbufferedTemporaryFile(QObject* p) : QTemporaryFile(p) {}
	bool unbufOpen() { return open(QIODevice::ReadOnly | QIODevice::Unbuffered); }
};

DataLoader::DataLoader(Git* g, FileHistory* f) : QProcess(g), git(g), fh(f) {

	canceling = parsing = false;
	isProcExited = true;
	halfChunk = NULL;
	dataFile = NULL;
	loadedBytes = 0;
	guiUpdateTimer.setSingleShot(true);

	connect(git, SIGNAL(cancelAllProcesses()), this, SLOT(on_cancel()));
	connect(&guiUpdateTimer, SIGNAL(timeout()), this, SLOT(on_timeout()));
}

DataLoader::~DataLoader() {

	// avoid a Qt warning in case we are
	// destroyed while still running
	waitForFinished(1000);
}

void DataLoader::on_cancel(const FileHistory* f) {

	if (f == fh)
		on_cancel();
}

void DataLoader::on_cancel() {

	if (!canceling) { // just once
		canceling = true;
		kill(); // SIGKILL (Unix and Mac), TerminateProcess (Windows)
	}
}

bool DataLoader::start(SCList args, SCRef wd, SCRef buf) {

	if (!isProcExited) {
		dbs("ASSERT in DataLoader::start(), called while processing");
		return false;
	}
	isProcExited = false;
	setWorkingDirectory(wd);

	connect(this, SIGNAL(finished(int, QProcess::ExitStatus)),
	        this, SLOT(on_finished(int, QProcess::ExitStatus)));

	if (!createTemporaryFile() || !QGit::startProcess(this, args, buf)) {
		deleteLater();
		return false;
	}
	loadTime.start();
	guiUpdateTimer.start(GUI_UPDATE_INTERVAL);
	return true;
}

void DataLoader::on_finished(int, QProcess::ExitStatus) {

	isProcExited = true;

	if (parsing && guiUpdateTimer.isActive())
		dbs("ASSERT in DataLoader: timer active while parsing");

	if (parsing == guiUpdateTimer.isActive() && !canceling)
		dbs("ASSERT in DataLoader: inconsistent timer");

	if (guiUpdateTimer.isActive()) // no need to wait anymore
		guiUpdateTimer.start(1);
}

void DataLoader::on_timeout() {

	if (canceling) {
		deleteLater();
		return; // we leave with guiUpdateTimer not active
	}
	parsing = true;

	// process could exit while we are processing so save the flag now
	bool lastBuffer = isProcExited;
	loadedBytes += readNewData(lastBuffer);
	emit newDataReady(fh); // inserting in list view is about 3% of total time

	if (lastBuffer) {
		emit loaded(fh, loadedBytes, loadTime.elapsed(), true, "", "");
		deleteLater();

	} else if (isProcExited) { // exited while parsing
		dbs("Exited while parsing!!!!");
		guiUpdateTimer.start(1);
	} else
		guiUpdateTimer.start(GUI_UPDATE_INTERVAL);

	parsing = false;
}

void DataLoader::parseSingleBuffer(const QByteArray& ba) {

	if (ba.size() == 0 || canceling)
		return;

	int ofs = 0, newOfs, bz = ba.size();

	/* Due to unknown reasons randomly first byte
	 * of 'ba' is 0, this seems to happen only when
	 * using QFile::read(), i.e. with temporary file
	 * interface. Until we discover the real reason
	 * workaround this skipping the bogus byte
	 */
	if (ba.at(0) == 0 && bz > 1 && !halfChunk)
		ofs++;

	while (bz - ofs > 0) {

		if (!halfChunk) {

			newOfs = git->addChunk(fh, ba, ofs);
			if (newOfs == -1)
				break; // half chunk detected

			ofs = newOfs;

		} else { // less then 1% of cases with READ_BLOCK_SIZE = 64KB

			int end = ba.indexOf('\0');
			if (end == -1) // consecutives half chunks
				break;

			ofs = end + 1;
			baAppend(&halfChunk, ba.constData(), ofs);
			fh->rowData.append(halfChunk);
			addSplittedChunks(halfChunk);
			halfChunk = NULL;
		}
	}
	// save any remaining half chunk
	if (bz - ofs > 0)
		baAppend(&halfChunk, ba.constData() + ofs,  bz - ofs);
}

void DataLoader::addSplittedChunks(const QByteArray* hc) {

	if (hc->at(hc->size() - 1) != 0) {
		dbs("ASSERT in DataLoader, bad half chunk");
		return;
	}
	// do not assume we have only one chunk in hc
	int ofs = 0;
	while (ofs != -1 && ofs != (int)hc->size())
		ofs = git->addChunk(fh, *hc, ofs);
}

void DataLoader::baAppend(QByteArray** baPtr, const char* ascii, int len) {

	if (*baPtr)
		// we cannot use QByteArray::append(const char*)
		// because 'ascii' is not '\0' terminating
		(*baPtr)->append(QByteArray::fromRawData(ascii, len));
	else
		*baPtr = new QByteArray(ascii, len);
}

// *************** git interface facility dependant code *****************************

#ifdef USE_QPROCESS

ulong DataLoader::readNewData(bool lastBuffer) {

	/*
	   QByteArray copy c'tor uses shallow copy, but there is a deep copy in
	   QProcess::readStdout(), from an internal buffers list to return value.

	   Qt uses a select() to detect new data is ready, copies immediately the
	   data to the heap with a read() and stores the pointer to new data in a
	   pointer list, from qprocess_unix.cpp:

		const int basize = 4096;
		QByteArray *ba = new QByteArray(basize);
		n = ::read(fd, ba->data(), basize);
		buffer->append(ba); // added to a QPtrList<QByteArray> pointer list

	   When we call QProcess::readStdout() data from buffers pointed by the
	   pointer list is memcpy() to the function return value, from qprocess.cpp:

		....
		return buf->readAll(); // memcpy() here
	*/
	QByteArray* ba = new QByteArray(readAllStandardOutput());
	if (lastBuffer)
		ba->append('\0'); // be sure stream is null terminated

	if (ba->size() == 0) {
		delete ba;
		return 0;
	}
	fh->rowData.append(ba);
	parseSingleBuffer(*ba);
	return ba->size();
}

bool DataLoader::createTemporaryFile() { return true; }

#else // temporary file as data exchange facility

ulong DataLoader::readNewData(bool lastBuffer) {

	bool ok = dataFile &&
	         (dataFile->isOpen() || (dataFile->exists() && dataFile->unbufOpen()));

	if (!ok)
		return 0;

	ulong cnt = 0;
	qint64 readPos = dataFile->pos();

	while (true) {
		// this is the ONLY deep copy involved in the whole loading
		// QFile::read() calls standard C read() function when
		// file is open with Unbuffered flag, or fread() otherwise
		QByteArray* ba = new QByteArray();
		ba->resize(READ_BLOCK_SIZE);
		int len = dataFile->read(ba->data(), READ_BLOCK_SIZE);

		if (len <= 0) {
			delete ba;
			break;

		} else if (len < ba->size()) // unlikely
			ba->resize(len);

		// current read position must be updated manually, it's
		// not correctly incremented by read() if the producer
		// process has already finished
		readPos += len;
		dataFile->seek(readPos);

		cnt += len;
		fh->rowData.append(ba);
		parseSingleBuffer(*ba);

		// avoid reading small chunks if data producer is still running
		if (len < READ_BLOCK_SIZE && !lastBuffer)
			break;
	}
	if (lastBuffer) { // be sure stream is null terminated
		QByteArray* zb = new QByteArray(1, '\0');
		fh->rowData.append(zb);
		parseSingleBuffer(*zb);
	}
	return cnt;
}

bool DataLoader::createTemporaryFile() {

	// redirect 'git log' output to a temporary file
	dataFile = new UnbufferedTemporaryFile(this);

#ifndef Q_OS_WIN32
	/*
	   For performance reasons we would like to use a tmpfs filesystem
	   if available, this is normally mounted under '/tmp' in Linux.

	   According to Qt docs, a temporary file is placed in QDir::tempPath(),
	   that should be system's temporary directory. On Unix/Linux systems this
	   is usually /tmp; on Windows this is usually the path in the TEMP or TMP
	   environment variable.

	   But due to a bug in Qt 4.2 QDir::tempPath() is instead set to $HOME/tmp
	   under Unix/Linux, that is not a tmpfs filesystem.

	   So try to manually set the best directory for our temporary file.
	*/
		QDir dir("/tmp");
		bool foundTmpDir = (dir.exists() && dir.isReadable());
		if (foundTmpDir && dir.absolutePath() != QDir::tempPath()) {

			dataFile->setFileTemplate(dir.absolutePath() + "/qt_temp");
			if (!dataFile->open()) { // test for write access

				delete dataFile;
				dataFile = new UnbufferedTemporaryFile(this);
				dbs("WARNING: directory '/tmp' is not writable, "
				    "fallback on Qt default one, there could "
				    "be a performance penalty.");
			} else
				dataFile->close();
		}
#endif
	if (!dataFile->open()) // to read the file name
		return false;

	setStandardOutputFile(dataFile->fileName());
	dataFile->close();
	return true;
}

#endif // USE_QPROCESS