summaryrefslogtreecommitdiffstats
path: root/tdeprint/lpr/kmlprmanager.cpp
blob: 157105e603c57da9d5a28fb8c171fa98ecd2d21d (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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
 *  This file is part of the KDE libraries
 *  Copyright (c) 2001 Michael Goffioul <tdeprint@swing.be>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License version 2 as published by the Free Software Foundation.
 *
 *  This library 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
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 **/

#include "kmlprmanager.h"
#include "printcapreader.h"
#include "printcapentry.h"
#include "lpchelper.h"
#include "matichandler.h"
#include "apshandler.h"
#include "lprngtoolhandler.h"
#include "lprsettings.h"
#include "driver.h"
#include "editentrydialog.h"

#include <tqfileinfo.h>
#include <tqptrlist.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <kprinter.h>
#include <kprocess.h>
#include <tdeaction.h>
#include <kmessagebox.h>
#include <klibloader.h>

#include <stdlib.h>
#include <unistd.h>

KMLprManager::KMLprManager(TQObject *parent, const char *name, const TQStringList & /*args*/)
: KMManager(parent,name)
{
	m_handlers.setAutoDelete(true);
	m_handlerlist.setAutoDelete(false);
	m_entries.setAutoDelete(true);

	m_lpchelper = new LpcHelper(this);
	m_currentprinter = 0;

	setHasManagement(getuid() == 0);
	setPrinterOperationMask(
		KMManager::PrinterEnabling |
		KMManager::PrinterConfigure |
		KMManager::PrinterTesting |
		KMManager::PrinterCreation |
		KMManager::PrinterRemoval |
		KMManager::PrinterTesting
	);

	initHandlers();
}

void KMLprManager::listPrinters()
{
	TQFileInfo	fi(LprSettings::self()->printcapFile());

	if (m_lpchelper)
		m_lpchelper->updateStates();

	// update only if needed
	if (!m_updtime.isValid() || m_updtime < fi.lastModified())
	{
		// cleanup previous entries
		m_entries.clear();
		// notify handlers
		TQPtrListIterator<LprHandler>	hit(m_handlerlist);
		for (; hit.current(); ++hit)
			hit.current()->reset();

		// try to open the printcap file and parse it
		PrintcapReader	reader;
		TQFile	f(fi.absFilePath());
		PrintcapEntry	*entry;
		if (f.exists() && f.open(IO_ReadOnly))
		{
			reader.setPrintcapFile(&f);
			while ((entry = reader.nextEntry()) != NULL)
			{
				TQPtrListIterator<LprHandler>	it(m_handlerlist);
				for (; it.current(); ++it)
					if (it.current()->validate(entry))
					{
						KMPrinter	*prt = it.current()->createPrinter(entry);
						checkPrinterState(prt);
						prt->setOption("kde-lpr-handler", it.current()->name());
						addPrinter(prt);
						break;
					}
				m_entries.insert(entry->name, entry);
			}
		}

		// save update time
		m_updtime = fi.lastModified();
	}
	else
	{
		TQPtrListIterator<KMPrinter>	it(m_printers);
		for (; it.current(); ++it)
			if (!it.current()->isSpecial())
			{
				it.current()->setDiscarded(false);
				checkPrinterState(it.current());
			}
	}
}

void KMLprManager::insertHandler(LprHandler *handler)
{
    m_handlers.insert(handler->name(), handler);
    m_handlerlist.append(handler);
    kdDebug() << "Handler: " << handler->name() << endl;
}

void KMLprManager::initHandlers()
{
	m_handlers.clear();
	m_handlerlist.clear();

	insertHandler(new MaticHandler(this));
	insertHandler(new ApsHandler(this));
	insertHandler(new LPRngToolHandler(this));

	// now load external handlers
	TQStringList	l = TDEGlobal::dirs()->findAllResources("data", "tdeprint/lpr/*.la");
	for (TQStringList::ConstIterator it=l.begin(); it!=l.end(); ++it)
	{
		KLibrary	*library = KLibLoader::self()->library(TQFile::encodeName(*it));
		if (library)
		{
			kdDebug() << "loading external handler from " << *it << endl;
			LprHandler*(*func)(KMManager*) = (LprHandler*(*)(KMManager*))(library->symbol("create_handler"));
			if (func)
				insertHandler(func(this));
			else
				kdDebug() << "couldn't find the symbol 'create_handler'" << endl;
		}
	}

	// default handler
	insertHandler(new LprHandler("default", this));
}

LprHandler* KMLprManager::findHandler(KMPrinter *prt)
{
	TQString	handlerstr(prt->option("kde-lpr-handler"));
	LprHandler	*handler(0);
	if (handlerstr.isEmpty() || (handler = m_handlers.find(handlerstr)) == NULL)
	{
		return NULL;
	}
	return handler;
}

PrintcapEntry* KMLprManager::findEntry(KMPrinter *prt)
{
	PrintcapEntry	*entry = m_entries.find(prt->printerName());
	if (!entry)
	{
		return NULL;
	}
	return entry;
}

bool KMLprManager::completePrinter(KMPrinter *prt)
{
	LprHandler	*handler = findHandler(prt);
	PrintcapEntry	*entry = findEntry(prt);
	if (handler && entry)
		return handler->completePrinter(prt, entry, false);
	return false;
}

bool KMLprManager::completePrinterShort(KMPrinter *prt)
{
	LprHandler	*handler = findHandler(prt);
	PrintcapEntry	*entry = findEntry(prt);
	if (!handler || !entry)
		return false;

	return handler->completePrinter(prt, entry, true);
}

void KMLprManager::checkPrinterState(KMPrinter *prt)
{
	if (m_lpchelper)
	{
		KMPrinter::PrinterState	st = m_lpchelper->state(prt);
		prt->setState(st);
		prt->setAcceptJobs(!(st & KMPrinter::Rejecting));
	}
	else
	{
		prt->setState(KMPrinter::Idle);
		prt->setAcceptJobs(true);
	}
}

DrMain* KMLprManager::loadPrinterDriver(KMPrinter *prt, bool config)
{
	if (!prt)
		return NULL;

	LprHandler	*handler = findHandler(prt);
	PrintcapEntry	*entry = findEntry(prt);
	if (handler && entry)
	{
		DrMain	*driver = handler->loadDriver(prt, entry, config);
		if (driver)
			driver->set("handler", handler->name());
		return driver;
	}
	return NULL;
}

DrMain* KMLprManager::loadFileDriver(const TQString& filename)
{
	int	p = filename.find('/');
	TQString	handler_str = (p != -1 ? filename.left(p) : TQString::fromLatin1("default"));
	LprHandler	*handler = m_handlers.find(handler_str);
	if (handler)
	{
		DrMain	*driver = handler->loadDbDriver(filename);
		if (driver)
			driver->set("handler", handler->name());
		return driver;
	}
	return NULL;
}

bool KMLprManager::enablePrinter(KMPrinter *prt, bool state)
{
	TQString	msg;
	if (!m_lpchelper->enable(prt, state, msg))
	{
		setErrorMsg(msg);
		return false;
	}
	return true;
}

bool KMLprManager::startPrinter(KMPrinter *prt, bool state)
{
	TQString	msg;
	if (!m_lpchelper->start(prt, state, msg))
	{
		setErrorMsg(msg);
		return false;
	}
	return true;
}

bool KMLprManager::savePrinterDriver(KMPrinter *prt, DrMain *driver)
{
	LprHandler	*handler = findHandler(prt);
	PrintcapEntry	*entry = findEntry(prt);
	if (handler && entry)
	{
		bool	mustSave(false);
		if (handler->savePrinterDriver(prt, entry, driver, &mustSave))
		{
			if (mustSave)
				return savePrintcapFile();
			return true;
		}
	}
	return false;
}

bool KMLprManager::savePrintcapFile()
{
	if (!LprSettings::self()->isLocalPrintcap())
	{
		setErrorMsg(i18n("The printcap file is a remote file (NIS). It cannot be written."));
		return false;
	}
	TQFile	f(LprSettings::self()->printcapFile());
	if (f.open(IO_WriteOnly))
	{
		TQTextStream	t(&f);
		TQDictIterator<PrintcapEntry>	it(m_entries);
		for (; it.current(); ++it)
		{
			it.current()->writeEntry(t);
		}
		return true;
	}
	else
	{
		setErrorMsg(i18n("Unable to save printcap file. Check that "
		                 "you have write permissions for that file."));
		return false;
	}
}

bool KMLprManager::createPrinter(KMPrinter *prt)
{
	// remove existing printcap entry
	PrintcapEntry	*oldEntry = m_entries.find(prt->printerName());

	// look for the handler and re-create entry
	LprHandler	*handler(0);
	// To look for the handler, either we base ourselves
	// on the driver (1: new printer, 2: modifying driver)
	// or we use the handler of the existing printer
	// (modifying something else, handler stays the same)
	if (prt->driver())
		handler = m_handlers.find(prt->driver()->get("handler"));
	else if (oldEntry)
		handler = findHandler(prt);
	else
		handler = m_handlers.find("default");
	if (!handler)
	{
		setErrorMsg(i18n("Internal error: no handler defined."));
		return false;
	}
	prt->setOption("kde-lpr-handler", handler->name());

	// we reload the driver if the printer object doesn't have one
	// and there's an old entry (sometimes needed to keep the backend
	// like in Foomatic)
	if (!prt->driver() && oldEntry)
		prt->setDriver(handler->loadDriver(prt, oldEntry, true));

	TQString	sd = LprSettings::self()->baseSpoolDir();
	if (sd.isEmpty())
	{
		setErrorMsg(i18n("Couldn't determine spool directory. See options dialog."));
		return false;
	}
	sd.append("/").append(prt->printerName());
	if (!TDEStandardDirs::makeDir(sd, 0755))
	{
		setErrorMsg(i18n("Unable to create the spool directory %1. Check that you "
		                 "have the required permissions for that operation.").arg(sd));
		return false;
	}
	PrintcapEntry	*entry = handler->createEntry(prt);
	if (!entry)
		return false;	// error should be set in the handler
	// old entry can be removed now
	m_entries.remove(prt->printerName());
	entry->name = prt->printerName();
	entry->addField("sh", Field::Boolean);
	entry->addField("mx", Field::Integer, "0");
	entry->addField("sd", Field::String, sd);
	if (!prt->option("kde-aliases").isEmpty())
		entry->aliases += TQStringList::split("|", prt->option("kde-aliases"), false);

	// insert the new entry and save printcap file
	m_entries.insert(prt->printerName(), entry);
	bool	result = savePrintcapFile();
	if (result)
	{
		if (prt->driver())
		{
			result = handler->savePrinterDriver(prt, entry, prt->driver());
		}

		// in case of LPRng, we need to tell the daemon about new printer
		if (LprSettings::self()->mode() == LprSettings::LPRng)
		{
			TQString	msg;
			if (!m_lpchelper->restart(msg))
			{
				setErrorMsg(i18n("The printer has been created but the print daemon "
				                 "could not be restarted. %1").arg(msg));
				return false;
			}
		}
	}
	return result;
}

bool KMLprManager::removePrinter(KMPrinter *prt)
{
	LprHandler	*handler = findHandler(prt);
	PrintcapEntry	*entry = findEntry(prt);
	if (handler && entry)
	{
		if (handler->removePrinter(prt, entry))
		{
			TQString	sd = entry->field("sd");
			// first try to save the printcap file, and if
			// successful, remove the spool directory
			m_entries.take(prt->printerName());
			bool	status = savePrintcapFile();
			if (status)
			{
				// printcap file saved, entry can be deleted now
				delete entry;
				status =  (::system(TQFile::encodeName("rm -rf " + TDEProcess::quote(sd))) == 0);
				if (!status)
					setErrorMsg(i18n("Unable to remove spool directory %1. "
					                 "Check that you have write permissions "
					                 "for that directory.").arg(sd));
				return status;
			}
			else
				// push back the non-removed entry
				m_entries.insert(prt->printerName(), entry);
		}
	}
	return false;
}

TQString KMLprManager::driverDbCreationProgram()
{
	return TQString::fromLatin1("make_driver_db_lpr");
}

TQString KMLprManager::driverDirectory()
{
	TQPtrListIterator<LprHandler>	it(m_handlerlist);
	TQString	dbDirs;
	for (; it.current(); ++it)
	{
		TQString	dir = it.current()->driverDirectory();
		if (!dir.isEmpty())
			dbDirs.append(dir).append(":");
	}
	if (!dbDirs.isEmpty())
		dbDirs.truncate(dbDirs.length()-1);
	return dbDirs;
}

TQString KMLprManager::printOptions(KPrinter *prt)
{
	KMPrinter	*mprt = findPrinter(prt->printerName());
	TQString	opts;
	if (mprt)
	{
		LprHandler	*handler = findHandler(mprt);
		if (handler)
			return handler->printOptions(prt);
	}
	return TQString::null;
}

void KMLprManager::createPluginActions(TDEActionCollection *coll)
{
	TDEAction	*act = new TDEAction(i18n("&Edit printcap Entry..."), "tdeprint_report", 0, this, TQT_SLOT(slotEditPrintcap()), coll, "plugin_editprintcap");
	act->setGroup("plugin");
}

void KMLprManager::validatePluginActions(TDEActionCollection *coll, KMPrinter *prt)
{
	m_currentprinter = prt;
	// FIXME: disabled until completion
	coll->action("plugin_editprintcap")->setEnabled(0 && hasManagement() && prt && !prt->isSpecial());
}

void KMLprManager::slotEditPrintcap()
{
	if (!m_currentprinter ||
	    KMessageBox::warningContinueCancel(NULL,
	    i18n("Editing a printcap entry manually should only be "
		 "done by confirmed system administrator. This may "
		 "prevent your printer from working. Do you want to "
		 "continue?"), TQString::null, KStdGuiItem::cont(),
	    "editPrintcap") == KMessageBox::Cancel)
		return;

	PrintcapEntry	*entry = findEntry(m_currentprinter);
	EditEntryDialog	dlg(entry, NULL);
	if (dlg.exec())
	{
	}
}

TQString KMLprManager::stateInformation()
{
	return i18n("Spooler type: %1").arg(LprSettings::self()->mode() == LprSettings::LPR ? "LPR (BSD compatible)" : "LPRng");
}

#include "kmlprmanager.moc"