mainwnd.cpp 17.3 KB
Newer Older
Tobias WEBER's avatar
Tobias WEBER committed
1
2
/**
 * in20 data analysis tool
Tobias WEBER's avatar
Tobias WEBER committed
3
 * @author Tobias Weber <tweber@ill.fr>
Tobias WEBER's avatar
Tobias WEBER committed
4
5
6
7
 * @date 6-Apr-2018
 * @license see 'LICENSE' file
 */

8
9
#define MAX_RECENT_FILES 16

Tobias WEBER's avatar
Tobias WEBER committed
10
#include "mainwnd.h"
Tobias WEBER's avatar
Tobias WEBER committed
11
#include "globals.h"
Tobias WEBER's avatar
Tobias WEBER committed
12
#include "funcs.h"
13
14
#include "libs/file.h"
#include "libs/algos.h"
Tobias WEBER's avatar
Tobias WEBER committed
15
16
#include "libs/helper.h"
#include "libs/str.h"
Tobias WEBER's avatar
Tobias WEBER committed
17

Tobias WEBER's avatar
Tobias WEBER committed
18
#include <QtWidgets/QMessageBox>
19
#include <QtWidgets/QFileDialog>
Tobias WEBER's avatar
Tobias WEBER committed
20
21
22
#include <QtWidgets/QDialog>

#include <iostream>
Tobias WEBER's avatar
Tobias WEBER committed
23

Tobias WEBER's avatar
Tobias WEBER committed
24
25
26
27

using t_real = double;


Tobias WEBER's avatar
Tobias WEBER committed
28
29
MainWnd::MainWnd(QSettings* pSettings)
	: QMainWindow(), m_pSettings(pSettings), 
Tobias WEBER's avatar
Tobias WEBER committed
30
	m_pBrowser(new FileBrowser(this, pSettings)),
31
	m_pWS(new WorkSpace(this, pSettings)),
Tobias WEBER's avatar
Tobias WEBER committed
32
	m_pCLI(new CommandLine(this, pSettings)),
33
	m_pCurPlot(new PlotterDock(this, pSettings))
Tobias WEBER's avatar
Tobias WEBER committed
34
{
Tobias WEBER's avatar
Tobias WEBER committed
35
36
37
	// the command line widget has to be accessible globally for error output
	g_pCLI = m_pCLI;

Tobias WEBER's avatar
Tobias WEBER committed
38
	this->setObjectName("in20");
39
	SetCurrentFile("");
Tobias WEBER's avatar
Tobias WEBER committed
40
	LoadPlugins();
Tobias WEBER's avatar
Tobias WEBER committed
41

Tobias WEBER's avatar
Tobias WEBER committed
42
43
44

	// ------------------------------------------------------------------------
	// Menu Bar
Tobias WEBER's avatar
Tobias WEBER committed
45
46
47
48
49
50
51
52
53
	QMenu *menuFile = new QMenu("File", m_pMenu);
	QMenu *menuView = new QMenu("View", m_pMenu);
	QMenu *menuHelp = new QMenu("Help", m_pMenu);

	// file
	auto *acNew = new QAction(QIcon::fromTheme("document-new"), "New", m_pMenu);
	menuFile->addAction(acNew);
	menuFile->addSeparator();
	auto *acOpen = new QAction(QIcon::fromTheme("document-open"), "Open...", m_pMenu);
54
	m_menuOpenRecent = new QMenu("Open Recent", m_pMenu);
Tobias WEBER's avatar
Tobias WEBER committed
55
	menuFile->addAction(acOpen);
56
57
	m_menuOpenRecent->setIcon(QIcon::fromTheme("document-open-recent"));
	menuFile->addMenu(m_menuOpenRecent);
Tobias WEBER's avatar
Tobias WEBER committed
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
	menuFile->addSeparator();
	auto *acSave = new QAction(QIcon::fromTheme("document-save"), "Save", m_pMenu);
	auto *acSaveAs = new QAction(QIcon::fromTheme("document-save-as"), "Save As...", m_pMenu);
	menuFile->addAction(acSave);
	menuFile->addAction(acSaveAs);
	menuFile->addSeparator();
	auto *acPrefs = new QAction("Preferences...", m_pMenu);
	acPrefs->setMenuRole(QAction::PreferencesRole);
	menuFile->addAction(acPrefs);
	menuFile->addSeparator();
	auto *acQuit = new QAction(QIcon::fromTheme("application-exit"), "Quit", m_pMenu);
	acQuit->setMenuRole(QAction::QuitRole);
	menuFile->addAction(acQuit);

	// view
	menuView->addAction(m_pBrowser->toggleViewAction());
	menuView->addAction(m_pWS->toggleViewAction());
	menuView->addAction(m_pCLI->toggleViewAction());
	menuView->addAction(m_pCurPlot->toggleViewAction());

	// help
	auto *acAbout = new QAction(QIcon::fromTheme("help-about"), "About...", m_pMenu);
	auto *acAboutQt = new QAction(QIcon::fromTheme("help-about"), "About Qt...", m_pMenu);
	acAbout->setMenuRole(QAction::AboutRole);
	acAboutQt->setMenuRole(QAction::AboutQtRole);
	menuHelp->addAction(acAbout);
	menuHelp->addAction(acAboutQt);

	m_pMenu->addMenu(menuFile);
	m_pMenu->addMenu(menuView);
Tobias WEBER's avatar
Tobias WEBER committed
88
89
	if(m_plugin_dlgs.size())
		m_pMenu->addMenu(m_pmenuPluginTools);
Tobias WEBER's avatar
Tobias WEBER committed
90
	m_pMenu->addMenu(menuHelp);
Tobias WEBER's avatar
Tobias WEBER committed
91
	m_pMenu->setNativeMenuBar(m_pSettings ? m_pSettings->value("mainwnd/native_gui", false).toBool() : false);
Tobias WEBER's avatar
Tobias WEBER committed
92
	this->setMenuBar(m_pMenu);
Tobias WEBER's avatar
Tobias WEBER committed
93
94
95
	// ------------------------------------------------------------------------


Tobias WEBER's avatar
Tobias WEBER committed
96
97
98

	// ------------------------------------------------------------------------
	// docks
Tobias WEBER's avatar
Tobias WEBER committed
99
	//this->setStatusBar(m_pStatus);
Tobias WEBER's avatar
Tobias WEBER committed
100
101
	this->setCentralWidget(m_pMDI);
	this->addDockWidget(Qt::LeftDockWidgetArea, m_pBrowser);
Tobias WEBER's avatar
Tobias WEBER committed
102
	this->addDockWidget(Qt::RightDockWidgetArea, m_pWS);
103
	this->addDockWidget(Qt::BottomDockWidgetArea, m_pCLI);
Tobias WEBER's avatar
Tobias WEBER committed
104
	this->addDockWidget(Qt::BottomDockWidgetArea, m_pCurPlot);
Tobias WEBER's avatar
Tobias WEBER committed
105
	// ------------------------------------------------------------------------
Tobias WEBER's avatar
Tobias WEBER committed
106

Tobias WEBER's avatar
Tobias WEBER committed
107
108


109
110
	// ------------------------------------------------------------------------
	// connections
Tobias WEBER's avatar
Tobias WEBER committed
111
	connect(m_pBrowser->GetWidget(), &FileBrowserWidget::TransferFiles, m_pWS->GetWidget(), &WorkSpaceWidget::ReceiveFiles);
Tobias WEBER's avatar
Tobias WEBER committed
112
113
	connect(m_pWS->GetWidget(), &WorkSpaceWidget::PlotDataset, m_pCurPlot->GetWidget(), &Plotter::Plot);
	connect(m_pBrowser->GetWidget(), &FileBrowserWidget::PlotDataset, m_pCurPlot->GetWidget(), &Plotter::Plot);
114
115
116
117
	connect(acNew, &QAction::triggered, this, &MainWnd::NewFile);
	connect(acOpen, &QAction::triggered, this, static_cast<void(MainWnd::*)()>(&MainWnd::OpenFile));
	connect(acSave, &QAction::triggered, this, static_cast<void(MainWnd::*)()>(&MainWnd::SaveFile));
	connect(acSaveAs, &QAction::triggered, this, &MainWnd::SaveFileAs);
Tobias WEBER's avatar
Tobias WEBER committed
118
119
120
121
	//connect(acPrefs, &QAction::triggered, this, ....);	TODO
	//connect(acAbout, &QAction::triggered, this, ....);	TODO
	connect(acAboutQt, &QAction::triggered, this, []() { qApp->aboutQt(); });
	connect(acQuit, &QAction::triggered, this, &QMainWindow::close);
Tobias WEBER's avatar
Tobias WEBER committed
122
123
124
125
126
127
128
129
130

	// link symbol maps of workspace widget and command line parser
	m_pCLI->GetWidget()->GetParserContext().SetWorkspace(m_pWS->GetWidget()->GetWorkspace());

	// connect the "workspace updated" signal from the command line parser
	m_pCLI->GetWidget()->GetParserContext().GetWorkspaceUpdatedSignal().connect([this](const std::string& ident)
	{
		m_pWS->GetWidget()->UpdateList();
	});
131
132
133
	// ------------------------------------------------------------------------


Tobias WEBER's avatar
Tobias WEBER committed
134

Tobias WEBER's avatar
Tobias WEBER committed
135
136
	// ------------------------------------------------------------------------
	// restore settings
Tobias WEBER's avatar
Tobias WEBER committed
137
138
	if(m_pSettings)
	{
139
140
141
		if(m_pSettings->contains("mainwnd/recentsessions"))
			SetRecentFiles(m_pSettings->value("mainwnd/recentsessions").toStringList());

Tobias WEBER's avatar
Tobias WEBER committed
142
143
144
		// restore window state
		if(m_pSettings->contains("mainwnd/geo"))
			this->restoreGeometry(m_pSettings->value("mainwnd/geo").toByteArray());
Tobias WEBER's avatar
Tobias WEBER committed
145
146
		else
			this->resize(800, 600);
Tobias WEBER's avatar
Tobias WEBER committed
147
148
149
		if(m_pSettings->contains("mainwnd/state"))
			this->restoreState(m_pSettings->value("mainwnd/state").toByteArray());
	}
Tobias WEBER's avatar
Tobias WEBER committed
150
	// ------------------------------------------------------------------------
Tobias WEBER's avatar
Tobias WEBER committed
151
152
153
154
155
156



	// ------------------------------------------------------------------------
	// add the built-in function list to the completer
	QStringList lstFuncs;
Tobias WEBER's avatar
Tobias WEBER committed
157
158
159
160
161
162
163
164
165
	for(const auto &pair : g_funcs_real_1arg) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, 1 argument]").c_str()));
	for(const auto &pair : g_funcs_real_2args) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, 2 arguments]").c_str()));
	for(const auto &pair : g_funcs_arr_1arg) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, 1 argument]").c_str()));
	for(const auto &pair : g_funcs_arr_2args) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, 2 arguments]").c_str()));
	for(const auto &pair : g_funcs_gen_0args) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, no arguments]").c_str()));
	for(const auto &pair : g_funcs_gen_1arg) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, 1 argument]").c_str()));
	for(const auto &pair : g_funcs_gen_2args) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, 2 arguments]").c_str()));
	for(const auto &pair : g_funcs_gen_vararg) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [function, variable arguments]").c_str()));
	for(const auto &pair : g_consts_real) lstFuncs.push_back(((pair.first + "###" + std::get<1>(pair.second) + " [constant]").c_str()));
Tobias WEBER's avatar
Tobias WEBER committed
166
167
	m_pCLI->GetWidget()->SetCompleterItems(lstFuncs);
	// ------------------------------------------------------------------------
Tobias WEBER's avatar
Tobias WEBER committed
168
169
170
171
}


MainWnd::~MainWnd()
Tobias WEBER's avatar
Tobias WEBER committed
172
173
174
{
	UnloadPlugins();
}
Tobias WEBER's avatar
Tobias WEBER committed
175
176
177


void MainWnd::showEvent(QShowEvent *pEvt)
Tobias WEBER's avatar
Tobias WEBER committed
178
{
Tobias WEBER's avatar
Tobias WEBER committed
179
	QMainWindow::showEvent(pEvt);
Tobias WEBER's avatar
Tobias WEBER committed
180
181
182
183
184
185
186
}


void MainWnd::closeEvent(QCloseEvent *pEvt)
{
	if(m_pSettings)
	{
187
188
189
190
191
		// remove superfluous entries and save the recent files list
		while(m_recentFiles.size() > MAX_RECENT_FILES)
			m_recentFiles.pop_front();
		m_pSettings->setValue("mainwnd/recentsessions", m_recentFiles);

Tobias WEBER's avatar
Tobias WEBER committed
192
193
194
195
196
197
198
		// save window state
		m_pSettings->setValue("mainwnd/geo", this->saveGeometry());
		m_pSettings->setValue("mainwnd/state", this->saveState());
	}

	QMainWindow::closeEvent(pEvt);
}
Tobias WEBER's avatar
Tobias WEBER committed
199
200
201
202
203
204



/**
 * File -> New
 */
205
void MainWnd::NewFile()
Tobias WEBER's avatar
Tobias WEBER committed
206
{
207
	SetCurrentFile("");
Tobias WEBER's avatar
Tobias WEBER committed
208
209
	m_pWS->GetWidget()->GetWorkspace()->clear();
	m_pWS->GetWidget()->UpdateList();
Tobias WEBER's avatar
Tobias WEBER committed
210
211
212
213
214
215
}


/**
 * File -> Open
 */
216
void MainWnd::OpenFile()
Tobias WEBER's avatar
Tobias WEBER committed
217
{
218
	QString dirLast = m_pSettings->value("mainwnd/sessiondir", "").toString();
Tobias WEBER's avatar
Tobias WEBER committed
219

220
221
222
223
224
225
	QString filename = QFileDialog::getOpenFileName(this, "Open File", dirLast, "IN20 Files (*.in20 *.IN20)");
	if(filename=="" || !QFile::exists(filename))
		return;

	if(OpenFile(filename))
		m_pSettings->setValue("mainwnd/sessiondir", QFileInfo(filename).path());
Tobias WEBER's avatar
Tobias WEBER committed
226
227
228
229
230
231
}


/**
 * File -> Save
 */
232
void MainWnd::SaveFile()
Tobias WEBER's avatar
Tobias WEBER committed
233
{
234
235
236
237
	if(m_curFile == "")
		SaveFileAs();
	else
		SaveFile(m_curFile);
Tobias WEBER's avatar
Tobias WEBER committed
238
239
240
241
242
243
}


/**
 * File -> Save As
 */
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
void MainWnd::SaveFileAs()
{
	QString dirLast = m_pSettings->value("mainwnd/sessiondir", "").toString();

	QString filename = QFileDialog::getSaveFileName(this, "Save File", dirLast, "IN20 Files (*.in20 *.IN20)");
	if(filename=="")
		return;

	if(SaveFile(filename))
		m_pSettings->setValue("mainwnd/sessiondir", QFileInfo(filename).path());
}


/**
 * load File
 */
bool MainWnd::OpenFile(const QString &file)
Tobias WEBER's avatar
Tobias WEBER committed
261
{
Tobias WEBER's avatar
Tobias WEBER committed
262
263
	static const std::string basename = "in20/";

264
265
	if(file=="" || !QFile::exists(file))
		return false;
Tobias WEBER's avatar
Tobias WEBER committed
266

Tobias WEBER's avatar
Tobias WEBER committed
267
268

	// load xml
269
	tl2::Prop<std::string> prop;
Tobias WEBER's avatar
Tobias WEBER committed
270
	prop.SetSeparator('/');
271
	if(!prop.Load(file.toStdString(), tl2::PropType::XML))
Tobias WEBER's avatar
Tobias WEBER committed
272
273
274
275
276
277
	{
		QMessageBox::critical(this, "Error", "Could not open session.");	
		return false;
	}

	// check format and version
Tobias WEBER's avatar
Tobias WEBER committed
278
279
280
	auto optFmt = prop.QueryOpt<std::string>(basename + "format");
	auto optVer = prop.QueryOpt<std::string>(basename + "version");
	auto optTime = prop.QueryOpt<t_real>(basename + "timestamp");
Tobias WEBER's avatar
Tobias WEBER committed
281
282
283
284
285
286
	if(!optFmt || *optFmt != "session")
	{
		QMessageBox::critical(this, "Error", "Not a session file. Ignoring.");
		return false;
	}
	if(optVer && optTime)
287
		print_out("Loading session file version ", *optVer, ", dated ", tl2::epoch_to_str(*optTime), ".");
Tobias WEBER's avatar
Tobias WEBER committed
288
289


Tobias WEBER's avatar
Tobias WEBER committed
290
291
	m_pWS->GetWidget()->GetWorkspace()->clear();
	m_pWS->GetWidget()->LoadWorkspace(basename, prop);
Tobias WEBER's avatar
Tobias WEBER committed
292

293
294
295
296
297
298
299
300
301
302
303
304

	SetCurrentFile(file);
	AddRecentFile(file);
	return true;
}


/**
 * save File
 */
bool MainWnd::SaveFile(const QString &file)
{
Tobias WEBER's avatar
Tobias WEBER committed
305
306
	static const std::string basename = "in20/";

307
308
309
	if(file=="")
		return false;

Tobias WEBER's avatar
Tobias WEBER committed
310
311
312
	std::unordered_map<std::string, std::string> sessionmap;

	// set format and version
Tobias WEBER's avatar
Tobias WEBER committed
313
314
	sessionmap[basename + "format"] = "session";
	sessionmap[basename + "version"] = PROGRAM_VERSION;
315
	sessionmap[basename + "timestamp"] = tl2::var_to_str(tl2::epoch<t_real>());
Tobias WEBER's avatar
Tobias WEBER committed
316
317


Tobias WEBER's avatar
Tobias WEBER committed
318
319
	// save workspace variables
	m_pWS->GetWidget()->SaveWorkspace(basename, sessionmap);
Tobias WEBER's avatar
Tobias WEBER committed
320
321


322
	tl2::Prop<std::string> prop;
Tobias WEBER's avatar
Tobias WEBER committed
323
	prop.SetSeparator('/');
Tobias WEBER's avatar
Tobias WEBER committed
324
325
	prop.Add(sessionmap);

326
	if(!prop.Save(file.toStdString(), tl2::PropType::XML))
Tobias WEBER's avatar
Tobias WEBER committed
327
328
329
330
	{
		QMessageBox::critical(this, "Error", "Could not save session.");	
		return false;
	}
331
332
333
334

	SetCurrentFile(file);
	AddRecentFile(file);
	return true;
Tobias WEBER's avatar
Tobias WEBER committed
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

/**
 * add a file to the recent files menu
 */
void MainWnd::AddRecentFile(const QString &file)
{
	for(const auto &recentfile : m_recentFiles)
	{
		// file already in list?
		if(recentfile == file)
			return;
	}

	m_recentFiles.push_back(file);
	RebuildRecentFiles();
}


/**
 * set the recent file menu
 */
void MainWnd::SetRecentFiles(const QStringList &files)
{
	m_recentFiles = files;
	RebuildRecentFiles();
}


/**
 * create the "recent files" sub-menu
 */
void MainWnd::RebuildRecentFiles()
{
	m_menuOpenRecent->clear();

	std::size_t num_recent_files = 0;
	for(auto iter = m_recentFiles.rbegin(); iter != m_recentFiles.rend(); ++iter)
	{
		QString filename = *iter;
		auto *acFile = new QAction(QIcon::fromTheme("document"), filename, m_pMenu);

		connect(acFile, &QAction::triggered, [this, filename]() { this->OpenFile(filename); });
		m_menuOpenRecent->addAction(acFile);

		if(++num_recent_files >= MAX_RECENT_FILES)
			break;
	}
}


/**
 * remember current file and set window title
 */
void MainWnd::SetCurrentFile(const QString &file)
{
	static const QString title("IN20 Tool");
	m_curFile = file;

	if(m_curFile == "")
		this->setWindowTitle(title);
Tobias WEBER's avatar
Tobias WEBER committed
397
	else
398
399
		this->setWindowTitle(title + " -- " + m_curFile);
}
Tobias WEBER's avatar
Tobias WEBER committed
400
401
402
403
404
405
406
407



/**
 * looks for and loads plugin tools
 */
void MainWnd::LoadPlugins()
{
Tobias WEBER's avatar
Tobias WEBER committed
408
409
	m_pmenuPluginTools = new QMenu("Tools", m_pMenu);

410
411
	std::vector<QString> plugindirs{{ "plugins", "../plugins",
		qApp->applicationDirPath()+"/plugins", qApp->applicationDirPath()+"/../plugins" }};
Tobias WEBER's avatar
Tobias WEBER committed
412
	for(const auto& plugindir : plugindirs)
Tobias WEBER's avatar
Tobias WEBER committed
413
	{
Tobias WEBER's avatar
Tobias WEBER committed
414
		print_out("Looking for plugins in \"", plugindir.toStdString(), "\"...");
Tobias WEBER's avatar
Tobias WEBER committed
415

Tobias WEBER's avatar
Tobias WEBER committed
416
417
		QDirIterator iter(plugindir, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
		while(iter.hasNext())
Tobias WEBER's avatar
Tobias WEBER committed
418
		{
Tobias WEBER's avatar
Tobias WEBER committed
419
			std::string dllfile = iter.next().toStdString();
Tobias WEBER's avatar
Tobias WEBER committed
420
			std::string fileext = tl2::get_fileext(dllfile, true);
Tobias WEBER's avatar
Tobias WEBER committed
421
422
			std::string rawfile = tl2::get_file_nodir(dllfile, false);
			if(rawfile == "." || rawfile == "..")
Tobias WEBER's avatar
Tobias WEBER committed
423
424
				continue;

Tobias WEBER's avatar
Tobias WEBER committed
425
			if(fileext == "so" || fileext == "dll" || fileext == "dylib")
Tobias WEBER's avatar
Tobias WEBER committed
426
			{
Tobias WEBER's avatar
Tobias WEBER committed
427
				try
Tobias WEBER's avatar
Tobias WEBER committed
428
				{
Tobias WEBER's avatar
Tobias WEBER committed
429
430
431
432
433
434
					auto dll = std::make_shared<boost::dll::shared_library>(dllfile);
					if(!dll || !dll->is_loaded())
					{
						print_err("Could not load plugin \"", dllfile, "\".");
						continue;
					}
Tobias WEBER's avatar
Tobias WEBER committed
435

Tobias WEBER's avatar
Tobias WEBER committed
436
437
438
439
440
					if(!dll->has("tl_descr") || !dll->has("tl_init") || !dll->has("tl_create") || !dll->has("tl_destroy"))
					{
						print_err("Not a valid plugin: \"", dllfile, "\".");
						continue;
					}
Tobias WEBER's avatar
Tobias WEBER committed
441
442


Tobias WEBER's avatar
Tobias WEBER committed
443
444
					PluginDlg plugin;
					plugin.dll = dll;
Tobias WEBER's avatar
Tobias WEBER committed
445

Tobias WEBER's avatar
Tobias WEBER committed
446
447
448
449
450
					// plugin functions
					plugin.f_descr = dll->get<PluginDlg::t_descr>("tl_descr");
					plugin.f_init = dll->get<PluginDlg::t_init>("tl_init");
					plugin.f_create = dll->get<PluginDlg::t_create>("tl_create");
					plugin.f_destroy = dll->get<PluginDlg::t_destroy>("tl_destroy");
Tobias WEBER's avatar
Tobias WEBER committed
451

Tobias WEBER's avatar
Tobias WEBER committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
					// plugin descriptors
					{
						std::vector<std::string> vecdescr;
						tl2::get_tokens<std::string, std::string>(plugin.f_descr(), ";", vecdescr);

						plugin.name = vecdescr[1];
						plugin.descr = vecdescr[2];

						// only accept dialog plugins
						if(vecdescr[0] != "dlg")
							continue;

						// skip plugin if another one with the same name is already registered
						if(std::find_if(m_plugin_dlgs.begin(), m_plugin_dlgs.end(),
							[&plugin](const PluginDlg& otherplugin) -> bool
							{
								return otherplugin.name == plugin.name;
							}) != m_plugin_dlgs.end())
							continue;

						// add menu item
Tobias WEBER's avatar
Tobias WEBER committed
473
						auto *acTool = new QAction((plugin.name + "...").c_str(), m_pMenu);
Tobias WEBER's avatar
Tobias WEBER committed
474
475
476
477
478
479
480
						acTool->setToolTip(plugin.descr.c_str());
						m_pmenuPluginTools->addAction(acTool);
						const std::size_t pluginNr = m_plugin_dlgs.size();
						connect(acTool, &QAction::triggered, this, [this, pluginNr]()
						{
							if(pluginNr >= m_plugin_dlgs.size())
							{
Tobias WEBER's avatar
Tobias WEBER committed
481
								print_err("Invalid tool plugin number ", pluginNr, ".");
Tobias WEBER's avatar
Tobias WEBER committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
								return;
							}

							// get plugin corresponding to this menu item
							auto& plugin = m_plugin_dlgs[pluginNr];
							if(!plugin.inited)
								plugin.inited = plugin.f_init();

							if(plugin.inited && !plugin.dlg)
								plugin.dlg = plugin.f_create(this);

							if(plugin.dlg)
							{
								plugin.dlg->show();
								plugin.dlg->activateWindow();
								plugin.dlg->raise();
								plugin.dlg->setFocus();
							}
						});

						print_out("Tool plugin ", dll->location(), " loaded. ",
							"name: \"", plugin.name, "\", ",
Tobias WEBER's avatar
Tobias WEBER committed
504
							"description: \"", plugin.descr, "\".");
Tobias WEBER's avatar
Tobias WEBER committed
505
506
507
508
509

						m_plugin_dlgs.emplace_back(std::move(plugin));
					}
				}
				catch(const std::exception& ex)
Tobias WEBER's avatar
Tobias WEBER committed
510
				{
Tobias WEBER's avatar
Tobias WEBER committed
511
512
513
514
515
516
517
518
					print_err("Error loading plugin \"", dllfile, "\": ", ex.what(), ".");
				}
			} // dialog plugins in so libraries
			else if(fileext == "py")
			{
				std::ifstream ifstr(dllfile);
				if(!ifstr)
					continue;
Tobias WEBER's avatar
Tobias WEBER committed
519

Tobias WEBER's avatar
Tobias WEBER committed
520
				PluginScr plugin;
Tobias WEBER's avatar
Tobias WEBER committed
521
				plugin.filename = dllfile;
Tobias WEBER's avatar
Tobias WEBER committed
522
				bool bHasName = false;
Tobias WEBER's avatar
Tobias WEBER committed
523

Tobias WEBER's avatar
Tobias WEBER committed
524
525
526
527
528
529
				std::string line;
				while(std::getline(ifstr, line))
				{
					tl2::trim(line);
					// looking for plugin descriptors in header comments
					if(line.size()==0 || line[0]!='#')
530
531
						continue;

Tobias WEBER's avatar
Tobias WEBER committed
532
					if(line.find("__ident__") != std::string::npos)
Tobias WEBER's avatar
Tobias WEBER committed
533
					{
Tobias WEBER's avatar
Tobias WEBER committed
534
535
536
537
538
539
540
541
542
543
544
545
						std::tie(std::ignore, plugin.name) = tl2::split_first<std::string>(line, ":", true, false);
						bHasName = true;
					}
					else if(line.find("__descr__") != std::string::npos)
					{
						std::tie(std::ignore, plugin.descr) = tl2::split_first<std::string>(line, ":", true, false);
					}
				}

				// not a recognised script plugin
				if(!bHasName)
					continue;
Tobias WEBER's avatar
Tobias WEBER committed
546

Tobias WEBER's avatar
Tobias WEBER committed
547
548
549
550
551
552
553
				// skip plugin if another one with the same name is already registered
				if(std::find_if(m_plugin_scr.begin(), m_plugin_scr.end(),
					[&plugin](const PluginScr& otherplugin) -> bool
					{
						return otherplugin.name == plugin.name;
					}) != m_plugin_scr.end())
					continue;
Tobias WEBER's avatar
Tobias WEBER committed
554
555


Tobias WEBER's avatar
Tobias WEBER committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
				// add menu item
				auto *acTool = new QAction((plugin.name + "...").c_str(), m_pMenu);
				acTool->setToolTip(plugin.descr.c_str());
				m_pmenuPluginTools->addAction(acTool);
				const std::size_t pluginNr = m_plugin_scr.size();
				connect(acTool, &QAction::triggered, this, [this, pluginNr]()
				{
					if(pluginNr >= m_plugin_scr.size())
					{
						print_err("Invalid script plugin number ", pluginNr, ".");
						return;
					}

					// get plugin corresponding to this menu item
					auto& plugin = m_plugin_scr[pluginNr];

					std::string interp = "python";
					std::system((interp + std::string{" "} + plugin.filename).c_str());
				});


				print_out("Script plugin \"", plugin.filename, "\" loaded. ",
Tobias WEBER's avatar
Tobias WEBER committed
578
					"name: \"", plugin.name, "\", ",
Tobias WEBER's avatar
Tobias WEBER committed
579
					"description: \"", plugin.descr, "\".");
Tobias WEBER's avatar
Tobias WEBER committed
580
581
582

				m_plugin_scr.emplace_back(std::move(plugin));
			} // py script plugins
Tobias WEBER's avatar
Tobias WEBER committed
583
		}
Tobias WEBER's avatar
Tobias WEBER committed
584
585
586
587
588
589
590
591
592
593
594
595
596
	}
}


/**
 * unloads plugins
 */
void MainWnd::UnloadPlugins()
{
	for(auto &plugin : m_plugin_dlgs)
	{
		// remove dialogs
		if(plugin.dlg && plugin.f_destroy)
Tobias WEBER's avatar
Tobias WEBER committed
597
		{
Tobias WEBER's avatar
Tobias WEBER committed
598
599
			plugin.f_destroy(plugin.dlg);
			plugin.dlg = nullptr;
Tobias WEBER's avatar
Tobias WEBER committed
600
		}
Tobias WEBER's avatar
Tobias WEBER committed
601
602

		plugin.inited = false;
Tobias WEBER's avatar
Tobias WEBER committed
603
	}
Tobias WEBER's avatar
Tobias WEBER committed
604
605

	m_plugin_dlgs.clear();
606
}