summaryrefslogtreecommitdiffstats
path: root/src/kvirc/module/kvi_modulemanager.cpp
blob: 7adeb9cdda303d3c3f34368db5edbc553dee374e (plain)
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
//=============================================================================
//
//   File : kvi_modulemanager.cpp
//   Creation date : Sat Aug 12 2000 20:32:11 by Szymon Stefanek
//
//   This file is part of the KVirc irc client distribution
//   Copyright (C) 2000-2005 Szymon Stefanek (pragma at kvirc dot net)
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your opinion) any later version.
//
//   This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc. ,51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================
#define __KVIRC__

#define _KVI_MODULEMANAGER_CPP_

#include "kvi_modulemanager.h"
#include "kvi_fileutils.h"
#include "kvi_app.h"
#include "kvi_options.h"
#include "kvi_frame.h"
#include "kvi_console.h"
#include "kvi_locale.h"
#include "kvi_out.h"

#include "kvi_library.h"

#include <tqdir.h>

KviModuleManager * g_pModuleManager = 0;


KviModuleManager::KviModuleManager()
{
	m_pModuleDict = new KviPointerHashTable<const char *,KviModule>(17,false);
	m_pModuleDict->setAutoDelete(false);

	m_pCleanupTimer = new TQTimer(this);
	connect(m_pCleanupTimer,TQT_SIGNAL(timeout()),this,TQT_SLOT(cleanupUnusedModules()));
}

KviModuleManager::~KviModuleManager()
{
	unloadAllModules();
	delete m_pModuleDict;
	delete m_pCleanupTimer;
}


void KviModuleManager::loadModulesByCaps(const char * caps,const char * dir)
{
	KviStr szCapsPath(KviStr::Format,"%s%ccaps%c%s%c",dir,KVI_PATH_SEPARATOR_CHAR,
			KVI_PATH_SEPARATOR_CHAR,caps,KVI_PATH_SEPARATOR_CHAR);

	TQDir d(TQString(szCapsPath.ptr()));

	// FIXME: maybe check timestamps ? (old modules)

	TQStringList sl = d.entryList(TQDir::Files | TQDir::Readable | TQDir::NoSymLinks);
	for(TQStringList::Iterator it = sl.begin();it != sl.end();++it)
	{
		KviStr modname = *it;
		modname.cutToLast(KVI_PATH_SEPARATOR_CHAR);
		getModule((*it).ascii());
	}
}

void KviModuleManager::loadModulesByCaps(const char * caps)
{
	KviStr szDir;
	g_pApp->getLocalKvircDirectory(szDir,KviApp::Plugins);
	loadModulesByCaps(caps,szDir.ptr());
	g_pApp->getGlobalKvircDirectory(szDir,KviApp::Plugins);
	loadModulesByCaps(caps,szDir.ptr());
}

void KviModuleManager::completeModuleNames(const TQString &path,const TQString &word,KviPointerList<TQString> * matches)
{
	TQDir d(path);
#ifdef COMPILE_ON_WINDOWS
	d.setNameFilter("kvi*.dll");
#else
	d.setNameFilter("libkvi*.so");
#endif
	// FIXME: maybe check timestamps ? (old modules)

	TQStringList sl = d.entryList(TQDir::Files | TQDir::Readable | TQDir::NoSymLinks);
	for(TQStringList::Iterator it = sl.begin();it != sl.end();++it)
	{
		TQString * modname = new TQString(*it);
		KviTQString::cutToLast(*modname,KVI_PATH_SEPARATOR_CHAR);
		KviTQString::cutToFirst(*modname,"kvi");
		if(KviTQString::equalCIN(word,*modname,word.length()))
		{
			KviTQString::cutFromLast(*modname,".so");
			if(!modname->isEmpty())
				matches->append(modname);
			else
				delete modname;
		} else delete modname;
	}
}

void KviModuleManager::completeModuleNames(const TQString &word,KviPointerList<TQString> * matches)
{
	TQString szDir;
	// FIXME: Should check for duplicate names here!
	g_pApp->getLocalKvircDirectory(szDir,KviApp::Plugins);
	completeModuleNames(szDir,word,matches);
	g_pApp->getGlobalKvircDirectory(szDir,KviApp::Plugins);
	completeModuleNames(szDir,word,matches);
}

KviModule * KviModuleManager::findModule(const char * modName)
{
	KviModule * m = m_pModuleDict->find(modName);
	if(m)m->updateAccessTime();
	return m;
}

KviModule * KviModuleManager::getModule(const char * modName)
{
	KviModule * m = m_pModuleDict->find(modName);
	if(!m)
	{
		if(!loadModule(modName)) return 0;
		m = m_pModuleDict->find(modName);
	}
	if(m)m->updateAccessTime();
	return m;
}

/*
static bool default_module_cmd_load(KviModule *,KviCommand *)
{
	return true;
}

static bool default_module_cmd_unload(KviModule *m,KviCommand *)
{
	g_pModuleManager->unloadModule(m->name());
	return true;
}
*/

bool KviModuleManager::loadModule(const char * modName)
{
	if(findModule(modName))
	{
		//debug("MODULE %s ALREADY IN CORE MEMORY",modName);
		return true;
	}
	TQString tmp;
	TQString szName;
#ifdef COMPILE_ON_WINDOWS
	KviTQString::appendFormatted(szName,"kvi%s.dll",modName);
#else
	KviTQString::appendFormatted(szName,"libkvi%s.so",modName);
#endif
	szName=szName.lower();

	g_pApp->getLocalKvircDirectory(tmp,KviApp::Plugins,szName);
	if(!KviFileUtils::fileExists(tmp))
	{
		g_pApp->getGlobalKvircDirectory(tmp,KviApp::Plugins,szName);
	}
	
	if(!KviFileUtils::fileExists(tmp)) return false;
	kvi_library_t handle = kvi_library_open(tmp.local8Bit().data());
	if(!handle)
	{
		m_szLastError = kvi_library_error();
		//debug("ERROR IN LOADING MODULE %s (%s): %s",modName,szName.ptr(),kvi_library_error());
		return false;
	}
	KviModuleInfo * info = (KviModuleInfo *)kvi_library_symbol(handle,KVIRC_MODULE_STRUCTURE_SYMBOL);
	if(!info)
	{
		m_szLastError = __tr2qs("No " KVIRC_MODULE_STRUCTURE_SYMBOL " symbol exported: not a kvirc module ?");
		kvi_library_close(handle);
		return false;
	}
	if(!info->szKVIrcVersion)
	{
		m_szLastError = __tr2qs("This module has no version informations: refusing to load it");
		kvi_library_close(handle);
		return false;
	}
	if(!KVI_OPTION_BOOL(KviOption_boolIgnoreModuleVersions))
	{
		if(!kvi_strEqualCS(info->szKVIrcVersion,KVI_VERSION))
		{
			m_szLastError = __tr2qs("This module was compiled for a different KVIrc version and can't be loaded");
			m_szLastError += " (";
			m_szLastError += info->szKVIrcVersion;
			m_szLastError += ")";
			kvi_library_close(handle);
			return false;
		}
	}
	KviModule * module = new KviModule(handle,info,modName,szName.utf8().data());

	// the module is probably up.. the only thing can fail is the init_routine now
	// load the message catalogue if any
	KviStr szDir;
	// it's more probable to have the translations in the global directory
	// try it as first... (yes, catalogue overriding is impossible this way.. but , anybody cares ?)
	g_pApp->getGlobalKvircDirectory(szDir,KviApp::Locale);

	if(!KviLocale::loadCatalogue(modName,szDir.ptr()))
	{
		// try the local directory then
		g_pApp->getLocalKvircDirectory(szDir,KviApp::Locale);
		KviLocale::loadCatalogue(modName,szDir.ptr());
	}

	if(info->init_routine)
	{
		if(!((info->init_routine)(module)))
		{
			m_szLastError = __tr2qs("Failed to execute the init routine");
			//debug("ERROR IN LOADING MODULE %s (%s): failed to execute the init routine",modName,szName.ptr());
			kvi_library_close(handle);
			delete module;
			// kill the message catalogue too then
			KviLocale::unloadCatalogue(modName);
			return false;
		}
	}
	m_pModuleDict->insert(modName,module);

	/*
	registerDefaultCommands(module);
	*/
	module->registerDefaultCommands();

	if(KVI_OPTION_BOOL(KviOption_boolCleanupUnusedModules))
	{
		if(!m_pCleanupTimer->isActive())
		{
			if(KVI_OPTION_UINT(KviOption_uintModuleCleanupTimerInterval) < 30)
				KVI_OPTION_UINT(KviOption_uintModuleCleanupTimerInterval) = 30;
			m_pCleanupTimer->start(KVI_OPTION_UINT(KviOption_uintModuleCleanupTimerInterval) * 1000);
		}
	}
	// be verbose if needed....just make sure that we're not shutting down...
	if(_OUTPUT_VERBOSE && !g_pApp->closingDown())
	{
		if(g_pFrame)g_pFrame->firstConsole()->output(KVI_OUT_VERBOSE,
			__tr2qs("Loaded module '%s' (%s)"),modName,szName.utf8().data());
	}
	return true;
}

/*
void KviModuleManager::registerDefaultCommands(KviModule * module)
{
	// Register the default commands
	module->registerCommand("load",default_module_cmd_load);
	module->registerCommand("unload",default_module_cmd_unload);
}
*/
bool KviModuleManager::unloadModule(const char * modName)
{
	return unloadModule(findModule(modName));
}

bool KviModuleManager::unloadModule(KviModule * module)
{
	if(!module)return false;
	moduleAboutToUnload(module);

	if(module->moduleInfo()->cleanup_routine)
	{
		(module->moduleInfo()->cleanup_routine)(module);
	}
	KviStr szModName = module->name();
	kvi_library_close(module->handle());
	//debug("Closing module %s, dlclose returns %d",szModName.ptr(),dlclose(module->handle()));

	m_pModuleDict->remove(szModName.ptr());
	delete module;

	// unload the message catalogues, if any
	KviLocale::unloadCatalogue(szModName.ptr());

	if(m_pModuleDict->isEmpty())
	{
		if(m_pCleanupTimer->isActive())m_pCleanupTimer->stop();
	}

	if(_OUTPUT_VERBOSE && !g_pApp->closingDown())
	{
		if(g_pFrame)g_pFrame->firstConsole()->output(KVI_OUT_VERBOSE,
			__tr2qs("Unloaded module '%s'"),szModName.ptr());
	}
	return true;
}

bool KviModuleManager::hasLockedModules()
{
	KviPointerHashTableIterator<const char *,KviModule> it(*m_pModuleDict);
	while(KviModule * m = it.current())
	{
		if(m->isLocked())return true;
		++it;
	}
	return false;
}


void KviModuleManager::cleanupUnusedModules()
{
	KviPointerHashTableIterator<const char *,KviModule> it(*m_pModuleDict);

	KviPointerList<KviModule> lModulesToUnload;
	lModulesToUnload.setAutoDelete(false);

	while(it.current())
	{
		if(it.current()->secondsSinceLastAccess() > KVI_OPTION_UINT(KviOption_uintModuleCleanupTimeout))
		{
			if(it.current()->moduleInfo()->can_unload)
			{
				if((it.current()->moduleInfo()->can_unload)(it.current()))
					lModulesToUnload.append(it.current());
				else {
					// the module don't want to be unloaded
					// keep it memory for a while
					it.current()->updateAccessTime();
				}
			} else {
				if(!(it.current()->isLocked()))
					lModulesToUnload.append(it.current());
			}
		}
		++it;
	}
	
	for(KviModule * pModule = lModulesToUnload.first();pModule;pModule = lModulesToUnload.next())
		unloadModule(pModule);
}

void KviModuleManager::unloadAllModules()
{
	KviPointerHashTableIterator<const char *,KviModule> it(*m_pModuleDict);

	KviPointerList<KviModule> lModulesToUnload;
	lModulesToUnload.setAutoDelete(false);
	while(KviModule * pModule = it.current())
	{
		lModulesToUnload.append(pModule);
		++it;
	}

	for(KviModule * pModule = lModulesToUnload.first();pModule;pModule = lModulesToUnload.next())
		unloadModule(pModule);
}