summaryrefslogtreecommitdiffstats
path: root/src/kile/quickpreview.cpp
blob: 8152ee0196634c4e537103d295841f447bb4ee0e (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
/***************************************************************************
    date                 : Feb 15 2007
    version              : 0.34
    copyright            : (C) 2005-2007 by Holger Danielsson
    email                : holger.danielsson@versanet.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 "quickpreview.h"
#include "kiletool_enums.h"
#include "kiledocmanager.h"
#include "kilelogwidget.h"

#include <tqtextstream.h>
#include <tqtextcodec.h>
#include <tqfile.h>
#include <tqfileinfo.h>
#include <tqdir.h>
#include <tqmap.h>

#include "kiledebug.h"
#include <ktempdir.h>
#include <klocale.h>
#include <kconfig.h>
#include <kileconfig.h>
#include <kate/document.h>

namespace KileTool
{

QuickPreview::QuickPreview(KileInfo *ki) : m_ki(ki), m_tempfile(TQString()), m_running(0)
{
	m_taskList << i18n("LaTeX ---> DVI")
	           << i18n("LaTeX ---> DVI (KDVI)")
	           << i18n("LaTeX ---> PS")
	           << i18n("LaTeX ---> PS (KGhostView)")
	           << i18n("PDFLaTeX ---> PDF")
	           << i18n("PDFLaTeX ---> PDF (KGhostView)")
	           << i18n("PDFLaTeX ---> PDF (KPDF)")
	           ;
}

QuickPreview::~QuickPreview() 
{
	removeTempFiles(true);
}

//////////////////// quick preview ////////////////////

// compile and view current selection (singlemode and mastermode)

void QuickPreview::previewSelection(Kate::Document *doc, bool previewInWidgetConfig)
{
	if ( doc->hasSelection() ) 
	{
		if ( previewInWidgetConfig && KileConfig::selPreviewInWidget() )
		{
			m_ki->previewWidget()->showActivePreview( doc->selection(),m_ki->getName(doc),doc->selStartLine(),KileTool::qpSelection );
		}
		else
		{	
			run( doc->selection(),m_ki->getName(doc),doc->selStartLine() );
			doc->clearSelection();
		}
	} 
	else 
	{
		showError( i18n("There is no selection to compile.") );
	}
}

// compile and view current environment (singlemode and mastermode)

void QuickPreview::previewEnvironment(Kate::Document *doc)
{
	uint row,col;
	TQString envname;
	TQString text = m_ki->editorExtension()->getEnvironmentText(row,col,envname);
	if ( text != TQString() )
	{
		if ( m_ki->latexCommands()->isMathModeEnv(envname)  )
			text = '$' + text + '$';
		else if ( m_ki->latexCommands()->isDisplaymathModeEnv(envname) )
			text = "\\[" + text + "\\]";

		if ( KileConfig::envPreviewInWidget() )
			m_ki->previewWidget()->showActivePreview( text,m_ki->getName(doc),row,KileTool::qpEnvironment );
		else
			run( text,m_ki->getName(doc),row );
	}
	else
	{
		showError( i18n("There is no surrounding environment.") );
	}
}

// compile and view current subdocument (only mastermode)

void QuickPreview::previewSubdocument(Kate::Document *doc)
{
	// this mode is only useful with a master document
	if ( !m_ki->docManager()->activeProject() && m_ki->getSinglemode() ) 
	{
		showError( i18n("This job is only useful with a master document.") );
		return;
	}

	// the current document should not be the master document
	TQString filename = doc->url().path();
	if ( filename == m_ki->getCompileName() ) 
	{
		showError( i18n("This is not a subdocument, but the master document.") );
		return;
	}

	run( doc->text(),m_ki->getName(doc),0 );
}

// compile and view current mathgroup (singlemode and mastermode)

void QuickPreview::previewMathgroup(Kate::Document *doc)
{
	uint row,col;
	TQString text = m_ki->editorExtension()->getMathgroupText(row,col);
	if ( text != TQString() )
	{
		if ( KileConfig::mathgroupPreviewInWidget() )
			m_ki->previewWidget()->showActivePreview( text,m_ki->getName(doc),row,KileTool::qpMathgroup );
		else
			run( text,m_ki->getName(doc),row );
	}
	else
	{
		showError( i18n("There is no surrounding mathgroup.") );
	}

}

//////////////////// run quick preview ////////////////////

void QuickPreview::getTaskList(TQStringList &tasklist)
{
	tasklist.clear();
	tasklist << "Tool/ViewDVI/Embedded Viewer=" + m_taskList[0]
	         << "Tool/ViewDVI/KDVI Unique="     + m_taskList[1]
	         << "Tool/ViewPS/Embedded Viewer="  + m_taskList[2]
	         << "Tool/ViewPS/KGhostView="       + m_taskList[3]
	         << "Tool/ViewPDF/Embedded Viewer=" + m_taskList[4]
	         << "Tool/ViewPDF/KGhostView="      + m_taskList[5]
	         << "Tool/ViewPDF/KPDF="            + m_taskList[6]
	         ;
}

bool QuickPreview::isRunning()
{
	return ( m_running > 0 );
}

bool QuickPreview::run(const TQString &text,const TQString &textfilename,int startrow) 
{
	// define possible tools
	TQMap <TQString,TQString> map;
	map[m_taskList[0]] = "PreviewLaTeX,,,ViewDVI,Embedded Viewer,dvi"; 
	map[m_taskList[1]] = "PreviewLaTeX,,,ViewDVI,KDVI Unique,dvi";
	map[m_taskList[2]] = "PreviewLaTeX,DVItoPS,Default,ViewPS,Embedded Viewer,ps";
	map[m_taskList[3]] = "PreviewLaTeX,DVItoPS,Default,ViewPS,KGhostView,ps";
	map[m_taskList[4]] = "PreviewPDFLaTeX,,,ViewPDF,KPDF (embedded),pdf"; 
	map[m_taskList[5]] = "PreviewPDFLaTeX,,,ViewPDF,KGhostView,pdf";
	map[m_taskList[6]] = "PreviewPDFLaTeX,,,ViewPDF,KPDF,pdf";

	TQString previewtask = KileConfig::previewTask();
	if ( ! map.contains(previewtask) ) 
	{
		showError(TQString(i18n("Could not run QuickPreview:\nunknown task '%1'").tqarg(previewtask)));
		return false;
	}

	return run (text, textfilename, startrow, map[previewtask]);
}

bool QuickPreview::run(const TQString &text,const TQString &textfilename,int startrow,const TQString &spreviewlist) 
{
	KILE_DEBUG() << "==QuickPreview::run()=========================="  << endl;
	m_ki->logWidget()->clear();
	if ( m_running > 0 )
	{
		showError( i18n("There is already a preview running, which you have to finish to run this one.") );
		return false;
	}
	
	// check if there is something to compile
	if ( text.isEmpty() ) 
	{
		showError(i18n("There is nothing to compile and preview."));
		return false;
	}
	
	// create the name of a temporary file or delete already existing temporary files
	if ( m_tempfile.isEmpty() ) 
	{
		m_tempfile =  KTempDir(TQString()).name() + "preview.tex";
		KILE_DEBUG() << "\tdefine tempfile: " << m_tempfile << endl;
	} 
	else 
	{
		removeTempFiles();
	}
	
	// create the temporary file with preamble and text
	int preamblelines = createTempfile(text);
	if ( preamblelines == 0 )
		return false;
	
	TQStringList previewlist = TQStringList::split(",",spreviewlist,true);
	
	// create preview tools 
	KILE_DEBUG() << "\tcreate latex tool for QuickPreview: "  << previewlist[pvLatex] << endl;
	KileTool::PreviewLaTeX *latex = (KileTool::PreviewLaTeX  *)m_ki->toolFactory()->create(previewlist[pvLatex],false);
	if ( !latex ) 
	{
		showError(TQString(i18n("Could not run '%1' for QuickPreview.").tqarg("LaTeX")));
		return false;
	}
	
	KileTool::Base *dvips = 0L;
	if ( ! previewlist[1].isEmpty() ) 
	{
		TQString dvipstool = previewlist[pvDvips] + " (" + previewlist[pvDvipsCfg] + ')';
		KILE_DEBUG() << "\tcreate dvips tool for QuickPreview: "  << previewlist[pvDvips] << endl;
		dvips = m_ki->toolFactory()->create(previewlist[pvDvips]);
		if ( !dvips ) 
		{
			showError(TQString(i18n("Could not run '%1' for QuickPreview.").tqarg(dvipstool)));
			return false;
		}
	} 

	KileTool::Base *viewer = 0L;
	if ( !previewlist[pvViewer].isEmpty() ) 
	{
		TQString viewertool = previewlist[pvViewer] + " (" + previewlist[pvViewerCfg] + ')';
		KILE_DEBUG() << "\tcreate viewer for QuickPreview: "  << viewertool << endl;
		viewer = m_ki->toolFactory()->create(previewlist[pvViewer],false);
		if ( !viewer ) 
		{
			showError(TQString(i18n("Could not run '%1' for QuickPreview.").tqarg(viewertool)));
			return false;
		}
	} 
	
	// set value of texinput path (only for QuickPreview tools)
	TQString texinputpath = KileConfig::teXPaths();
	TQString inputdir = TQFileInfo(m_ki->getCompileName()).dirPath(true);
	if ( ! texinputpath.isEmpty() )
		inputdir += ':' + texinputpath;
 	KileConfig::setPreviewTeXPaths(inputdir);
	KILE_DEBUG() << "\tQuickPreview: inputdir is '" << inputdir << "'" << endl;
	
	// prepare tools: previewlatex
	TQString filepath = m_tempfile.left( m_tempfile.length()-3 ); 
	latex->setPreviewInfo(textfilename,startrow,preamblelines+1);
	latex->setSource(m_tempfile);
	latex->prepareToRun();
	latex->setQuickie();
	if ( m_ki->toolManager()->run(latex) != KileTool::Running )
		return false;

	connect(latex, TQT_SIGNAL(destroyed()), this, TQT_SLOT(toolDestroyed()));
	m_running++;

	// dvips
	if ( dvips )
	{
		dvips->setSource( filepath + "dvi" );
		dvips->setQuickie();
		if ( m_ki->toolManager()->run(dvips,previewlist[pvDvipsCfg])  != KileTool::Running )
			return false;

		connect(dvips, TQT_SIGNAL(destroyed()), this, TQT_SLOT(toolDestroyed()));
		m_running++;
	}

	// viewer
	if ( viewer )
	{
		connect(viewer, TQT_SIGNAL(destroyed()), this, TQT_SLOT(toolDestroyed()));
		viewer->setSource( filepath + previewlist[pvExtension] );
		viewer->setQuickie();
		if ( m_ki->toolManager()->run(viewer,previewlist[pvViewerCfg]) != KileTool::Running )
			return false;
	}

	return true;	
}

void QuickPreview::toolDestroyed()
{
	KILE_DEBUG() << "\tQuickPreview: tool destroyed" << endl;
	if ( m_running > 0 )
		m_running--;
}

TQString QuickPreview::getPreviewFile(const TQString &extension) 
{
	if (m_tempfile.length () < 3) 
		return TQString();

	TQString filepath = m_tempfile.left(m_tempfile.length () - 3); 
	return filepath + extension;
} 

//////////////////// tempfile ////////////////////

int QuickPreview::createTempfile(const TQString &text)
{
	// determine main document to read the preamble
	TQString filename = m_ki->getCompileName();
	if ( filename.isEmpty() ) 
	{
		showError(i18n("Could not determine the main document."));
		return 0;
	}
	
	// open to read
	TQFile fin( filename );
	if ( !fin.exists() || !fin.open(IO_ReadOnly) ) 
	{
		showError(i18n("Could not read the preamble."));
		return 0;
	}
	KILE_DEBUG() << "\tcreate a temporary file: "  << m_tempfile << endl;
	
	// use a textstream
	TQTextStream preamble(&fin);

	// create the temporary file 
	TQFile tempfile(m_tempfile);
	if ( ! tempfile.open( IO_WriteOnly ) ) 
	{
		showError(i18n("Could not create a temporary file."));
		return 0;
	}
	TQTextStream stream( &tempfile );
	
	// set the encoding according to the original file (tbraun)
	if(m_ki->activeTextDocument())
	{
		TQTextCodec *codec = TQTextCodec::codecForName(m_ki->activeTextDocument()->encoding().ascii());
	 if ( codec )
		stream.setCodec(codec); 
	}
	// write the whole preamble into this temporary file
	TQString textline;
	int preamblelines = 0;
	bool begindocumentFound = false;
	while ( ! preamble.eof() ) 
	{
		textline = preamble.readLine();
		if ( textline.find("\\begin{document}") >= 0 ) 
		{
			begindocumentFound = true;
			break;
		}
		stream << textline << "\n";
		preamblelines++;
	}

	// look if we found '\begin{document}' to finish the preamble
	if ( ! begindocumentFound ) 
	{
		tempfile.close();
		showError(i18n("Could not find a '\\begin{document}' command."));
		return 0;
	}

	// add the text to compile
	stream << "\\pagestyle{empty}\n";
	stream << "\\begin{document}\n";
	stream << text;
	stream << "\n\\end{document}\n";
	tempfile.close();
	
	return preamblelines;
}

void QuickPreview::removeTempFiles(bool rmdir)
{
	if ( m_tempfile.isEmpty() ) 
		return;
		
	TQFileInfo fi(m_tempfile);
	TQString tempdir = fi.dirPath(true) + '/';
	
	TQDir dir = fi.dir(true); 
	if ( dir.exists() ) 
	{
		TQStringList list = dir.entryList(fi.baseName()+".*");
		for ( TQStringList::Iterator it=list.begin(); it!=list.end(); ++it ) 
		{
			TQFile::remove( tempdir + (*it) );
			// KILE_DEBUG() << "\tremove temporary file: " << tempdir + (*it) << endl;
		}
		
		if ( rmdir )
			dir.rmdir(tempdir);
	}
}

//////////////////// error messages ////////////////////

void QuickPreview::showError(const TQString &text)
{
	m_ki->logWidget()->printMsg( KileTool::Error, text, i18n("QuickPreview") );
}

}

#include "quickpreview.moc"