summaryrefslogtreecommitdiffstats
path: root/src/kile/templates.cpp
blob: 0de603581be7fa0572f22d6de1ba686e905695f0 (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
/*******************************************************************************************
    begin                : Sat Apr 26 2003
    copyright            : (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl)
                               2005 by Holger Danielsson (holger.danielsson@t-online.de)
                               2007 by Michel Ludwig (michel.ludwig@kdemail.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 option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "templates.h"

#include <kapp.h>
#include "kiledebug.h"
#include <kglobal.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kio/job.h>
#include <kio/netaccess.h>
#include <kmessagebox.h>

#include <tqdir.h>
#include <tqfileinfo.h>
#include <tqstringlist.h>
#include <tqregexp.h>

#include "kileinfo.h"

// 2005-08-04: dani
//  - added script support to search existing class files 
//    (classes: Koma, Beamer, Prosper, HA-prosper)
//  - sort items ('Empty Document' will always be the first entry)

// 2006-30-04: tbraun
//  - drag and drop makes no sense here
//  - use the Select mode

namespace KileTemplate {

////////////////////// Info //////////////////////

Info::Info() : type(KileDocument::Undefined)
{
}

bool Info::operator==(const Info ti) const
{
	return name==ti.name;
}

////////////////////// Manager //////////////////////

Manager::Manager(KileInfo* kileInfo, TQObject* tqparent, const char* name) : TQObject(tqparent, name), m_kileInfo(kileInfo)
{
}

Manager::~Manager() {
}

bool Manager::copyAppData(const KURL& src, const TQString& subdir, const TQString& fileName) {
	TQString dir;
	//let saveLocation find and create the appropriate place to
	//store the templates (usually $HOME/.kde/share/apps/kile/templates)
	dir = KGlobal::dirs()->saveLocation("appdata", subdir, true);
	KURL targetURL = KURL::fromPathOrURL(dir);
	targetURL.addPath(fileName);

	//if a directory is found
	if (!dir.isNull()) {
		return KIO::NetAccess::copy(src, targetURL, kapp->mainWidget());
	}
	else {
		KMessageBox::error(0, i18n("Could not find a folder to save %1 to.\nCheck whether you have a .kde folder with write permissions in your home folder.").tqarg(fileName));
		return false;
	}
}

bool Manager::removeAppData(const TQString &file) {
	TQFileInfo fileInfo(file);
	if(fileInfo.exists()) {
		return KIO::NetAccess::del(KURL::fromPathOrURL(file), kapp->mainWidget());
	}
	return true;
}

bool Manager::searchForTemplate(const TQString& name, KileDocument::Type& type) const {
	for (KileTemplate::TemplateListConstIterator i = m_TemplateList.constBegin(); i != m_TemplateList.constEnd(); ++i)
	{
		KileTemplate::Info info = *i;
		if(info.name == name && info.type == type) {
			return true;
		}
	}
	return false;
}

bool Manager::add(const KURL& templateSourceURL, const TQString& name, const KURL& icon) {
	KileDocument::Extensions *extensions = m_kileInfo->extensions();
	KileDocument::Type type = extensions->determineDocumentType(templateSourceURL);
	return add(templateSourceURL, type, name, icon);
}

bool Manager::add(const KURL& templateSourceURL, KileDocument::Type type, const TQString& name, const KURL& icon) {
	KileDocument::Extensions *extensions = m_kileInfo->extensions();
	TQString extension = extensions->defaultExtensionForDocumentType(type);

	return copyAppData(templateSourceURL, "templates", "template_" + name + extension) && copyAppData(icon, "pics", "type_" + name + extension + ".kileicon");
}

bool Manager::remove(Info ti) {
	return removeAppData(ti.path) && removeAppData(ti.icon);
}

bool Manager::replace(const KileTemplate::Info& toBeReplaced, const KURL& newTemplateSourceURL, const TQString& newName, const KURL& newIcon) {
	KileDocument::Type type = m_kileInfo->extensions()->determineDocumentType(newTemplateSourceURL);

	//start by copying the files that belong to the new template to a safe place
	TQString templateTempFile, iconTempFile;

	if(!KIO::NetAccess::download(newTemplateSourceURL, templateTempFile, kapp->mainWidget())) {
		return false;
	}
	if(!KIO::NetAccess::download(newIcon, iconTempFile, kapp->mainWidget())) {
		KIO::NetAccess::removeTempFile(templateTempFile);
		return false;
	}

	//now delete the template that should be replaced
	if(!remove(toBeReplaced)) {
		KIO::NetAccess::removeTempFile(templateTempFile);
		KIO::NetAccess::removeTempFile(iconTempFile);
	}

	//finally, create the new template
	if(!add(KURL::fromPathOrURL(templateTempFile), type, newName, KURL::fromPathOrURL(iconTempFile))) {
		KIO::NetAccess::removeTempFile(templateTempFile);
		KIO::NetAccess::removeTempFile(iconTempFile);
		return false;
	}

	KIO::NetAccess::removeTempFile(templateTempFile);
	KIO::NetAccess::removeTempFile(iconTempFile);

	return true;
}

void Manager::scanForTemplates() {
	KILE_DEBUG() << "===scanForTemplates()===================" << endl;
	TQStringList dirs = KGlobal::dirs()->findDirs("appdata", "templates");
	TQDir templates;
	KileTemplate::Info ti;
	KileDocument::Extensions *extensions = m_kileInfo->extensions();

	m_TemplateList.clear();
	for ( TQValueListIterator<TQString> i = dirs.begin(); i != dirs.end(); ++i)
	{
		templates = TQDir(*i, "template_*");
		for ( uint j = 0; j< templates.count(); ++j)
		{
			ti.path = templates.path() + '/' + templates[j];
			TQFileInfo fileInfo(ti.path);
			ti.name = fileInfo.baseName(true).mid(9); //remove "template_", do it this way to avoid problems with user input!
			ti.type = extensions->determineDocumentType(KURL::fromPathOrURL(ti.path));
			ti.icon = KGlobal::dirs()->findResource("appdata","pics/type_" + ti.name + extensions->defaultExtensionForDocumentType(ti.type) + ".kileicon");
			if (m_TemplateList.contains(ti))
			{
				KILE_DEBUG() << "\tignoring: " << ti.path << endl;
			}
			else
			{
				m_TemplateList.append(ti);
				KILE_DEBUG() << "\tadding: " << ti.name << " " << ti.path << endl;
			}
		}
	}
}

TemplateList Manager::getAllTemplates() const {
	return m_TemplateList;
}

TemplateList Manager::getTemplates(KileDocument::Type type) const {
	if(type == KileDocument::Undefined) 
	{
		return getAllTemplates();
	}

	TemplateList toReturn;
	for (KileTemplate::TemplateListConstIterator i = m_TemplateList.constBegin(); i != m_TemplateList.constEnd(); ++i)
	{
		KileTemplate::Info info = *i;
		if(info.type == type) {
			toReturn.push_back(info);
		}
	}
	return toReturn;
}

}
////////////////////// TemplateItem //////////////////////

// new compare function to make the "Empty (...) Document" items appear at the beginning

TemplateItem::TemplateItem(TQIconView * tqparent, const KileTemplate::Info& info) : TQIconViewItem(tqparent,info.name, TQPixmap(info.icon))
{
	setDragEnabled(false);
	m_info = info;
}

int TemplateItem::compare( TQIconViewItem *i ) const
{
	if ( key() == DEFAULT_EMPTY_CAPTION ) {
		return -1;
	}
	else if ( i->key() == DEFAULT_EMPTY_CAPTION ) {
		return 1;
	}
	else {
		return key().compare( i->key() );
	}
}

////////////////////// TemplateIconView //////////////////////

TemplateIconView::TemplateIconView(TQWidget *tqparent, const char *name, WFlags f) : KIconView(tqparent, name, f), m_templateManager(NULL), m_proc(NULL) {
	setItemsMovable(false);
	setMode(KIconView::Select);
	setResizeMode(TQIconView::Adjust);
	setSelectionMode(TQIconView::Single);
	setResizePolicy(TQScrollView::Default);
	setArrangement(TQIconView::TopToBottom);
	setMinimumHeight(100);
}

TemplateIconView::~TemplateIconView() {
}

void TemplateIconView::setTemplateManager(KileTemplate::Manager *templateManager) {
	m_templateManager = templateManager;
}

void TemplateIconView::fillWithTemplates(KileDocument::Type type) {
	if(!m_templateManager) {
		return;
	}

	clear();

	if(type == KileDocument::LaTeX) {
		searchLaTeXClassFiles();
	}
	else {
		addTemplateIcons(type);
	}
}

void TemplateIconView::searchLaTeXClassFiles()
{
	if(!m_templateManager) return;

	TQString command = "kpsewhich -format=tex scrartcl.cls beamer.cls prosper.cls HA-prosper.sty";

	delete m_proc;

	m_proc = new KProcess(TQT_TQOBJECT(this));
	m_proc->clearArguments();
	m_proc->setUseShell(true);
	(*m_proc) << TQStringList::split(' ', command);
	m_output = TQString();

	connect(m_proc, TQT_SIGNAL(receivedStdout(KProcess*,char*,int)),
	        this,   TQT_SLOT(slotProcessOutput(KProcess*,char*,int)) );
	connect(m_proc, TQT_SIGNAL(receivedStderr(KProcess*,char*,int)),
	        this,   TQT_SLOT(slotProcessOutput(KProcess*,char*,int)) );
	connect(m_proc, TQT_SIGNAL(processExited(KProcess*)),
	        this,   TQT_SLOT(slotProcessExited(KProcess*)) );

	KILE_DEBUG() << "=== NewFileWidget::searchClassFiles() ====================" << endl;
	KILE_DEBUG() << "\texecute: " << command << endl;
	if ( ! m_proc->start(KProcess::NotifyOnExit, KProcess::AllOutput) ) 
	{
		KILE_DEBUG() << "\tstart of shell process failed" << endl;
		addTemplateIcons(KileDocument::LaTeX);
	}
}

void TemplateIconView::slotProcessOutput(KProcess*, char* buf, int len)
{
	m_output += TQString::fromLocal8Bit(buf,len);
}

void TemplateIconView::slotProcessExited(KProcess *proc)
{
	if ( ! proc->normalExit() ) 
		m_output = TQString();

	addTemplateIcons(KileDocument::LaTeX);
	emit classFileSearchFinished();
}

void TemplateIconView::addTemplateIcons(KileDocument::Type type)
{
	if(!m_templateManager) return;

	TQString emptyIcon = KGlobal::dirs()->findResource("appdata", "pics/"+ TQString(DEFAULT_EMPTY_ICON) + ".png" );

	KileTemplate::Info emptyDocumentInfo;
	emptyDocumentInfo.name = DEFAULT_EMPTY_CAPTION;
	emptyDocumentInfo.icon = emptyIcon;
	emptyDocumentInfo.type = type;
	TemplateItem *emp = new TemplateItem(this, emptyDocumentInfo);
	setSelected(emp, true);

	if(type == KileDocument::LaTeX) {
		// disable non standard templates
		TQMap<TQString,bool> map;
		map["Scrartcl"] = false;
		map["Scrbook"]  = false;
		map["Scrreprt"] = false;
		map["Scrlttr2"] = false;
		map["Beamer"]   = false;
		map["Prosper"]  = false;
		map["HA-prosper"] = false;
		
		// split search results and look, which class files are present
		TQStringList list = TQStringList::split("\n",m_output);
		for ( TQStringList::Iterator it=list.begin(); it!=list.end(); ++it ) 
		{
			TQString filename = TQFileInfo(*it).fileName();
			if ( filename=="scrartcl.cls" )
			{
				map["Scrartcl"] = true;
				map["Scrbook"]  = true;
				map["Scrreprt"] = true;
				map["Scrlttr2"] = true;
			}
			else if ( filename=="beamer.cls" )  
				map["Beamer"] = true;
			else if ( filename=="prosper.cls" )
				map["Prosper"] = true;
			else if ( filename=="HA-prosper.sty" )
				map["HA-prosper"] = true;
		}
		
	
		KileTemplate::TemplateList templateList = m_templateManager->getTemplates(KileDocument::LaTeX);
		// insert all standard templates, all user defined templates 
		// and those templates, which have a present class 
		for (KileTemplate::TemplateListIterator i=templateList.begin(); i != templateList.end(); ++i)
		{
			KileTemplate::Info info = *i;
			TQString classname = info.name;
			if ( !map.contains(classname) || map[classname]==true )
			{
				new TemplateItem(this, info);
			}
		}
	}
	else {
		KileTemplate::TemplateList templateList = m_templateManager->getTemplates(type); 
		for (KileTemplate::TemplateListIterator i=templateList.begin(); i != templateList.end(); ++i)
		{
			new TemplateItem(this, *i);
		}
	}

	// sort all items (item for 'Empty Document' will always be the first one)
	sort();
	
	// set the default item, if its given
	for ( TQIconViewItem *item = firstItem(); item; item = item->nextItem() ) {
		if ( static_cast<TemplateItem*>(item)->name() == m_selicon ) {
			setSelected(item, true);
			ensureItemVisible(item);
		}
	}
}

#include "templates.moc"