src/relpipe-out-chart.cpp
author František Kučera <franta-hg@frantovo.cz>
Sun, 30 Sep 2018 18:34:34 +0200
branchv_0
changeset 19 ac70c7af6a9b
parent 18 16784291982f
child 20 b13e7ed9eea3
permissions -rw-r--r--
code clean-up, exit code

#include <iostream>

#include <QApplication>
#include <QThread>

#include <relpipe/cli/CLI.h>
#include <relpipe/cli/RelpipeCLIException.h>
#include <relpipe/reader/Factory.h>
#include <relpipe/reader/RelationalReader.h>
#include <relpipe/reader/RelpipeReaderException.h>

#include "RelpipeChartMainWindow.h"
#include "QtRelationalReaderStringHadler.h"

using namespace relpipe::cli;
using namespace relpipe::reader;

class RelationalReaderThread : public QThread {
private:
	std::shared_ptr<RelationalReader> reader;
public:

	// TODO: better background thread; lambda?

	RelationalReaderThread(std::shared_ptr<RelationalReader> reader) :
	reader(reader) {
		setTerminationEnabled(true);
	}

	void run() {
		try {
			reader->process();
		} catch (RelpipeReaderException& e) {
			// TODO: handle exception, show error dialog
			std::wcerr << L"RelpipeReaderException: " << e.getMessge() << std::endl;
		}
	}
};

int main(int argc, char**argv) {
	CLI cli(argc, argv);
	// TODO: argument name collisions? Filter arguments? Use prefix for Qt? Qt: -title, -style, -geometry
	QApplication app(argc, argv);

	std::shared_ptr<RelationalReader> reader(Factory::create(std::cin));
	int resultCode = CLI::EXIT_CODE_UNEXPECTED_ERROR;

	RelpipeChartMainWindow window;
	window.show();

	QtRelationalReaderStringHadler handler(&app, &window);
	reader->addHandler(&handler);

	// Start background thread
	RelationalReaderThread t(reader);
	t.start();
	// ---

	int qtResultCode = app.exec();

	if (qtResultCode == 0) {
		resultCode = CLI::EXIT_CODE_SUCCESS;
	} else {
		// TODO: report and log Qt errors if any
	}

	if (t.isRunning()) {
		std::wcerr << L"Background RelationalReader thread is still running → terminate()" << std::endl;
		t.terminate();
		std::wcerr << L"Background RelationalReader thread was terminated → wait()" << std::endl;
		t.wait();
		std::wcerr << L"Background RelationalReader thread wait() finished" << std::endl;
	}

	return resultCode;
}