1 /**
2  * \file LayoutFileList.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 
12 #include <config.h>
13 
14 #include "LayoutFile.h"
15 #include "Counters.h"
16 #include "Floating.h"
17 #include "FloatList.h"
18 #include "Lexer.h"
19 #include "TextClass.h"
20 
21 #include "frontends/alert.h"
22 
23 #include "support/debug.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/gettext.h"
27 #include "support/lassert.h"
28 #include "support/lstrings.h"
29 
30 #include "support/regex.h"
31 #include "support/TempFile.h"
32 
33 #include <fstream>
34 
35 using namespace std;
36 using namespace lyx::support;
37 
38 namespace lyx {
39 
40 
41 
LayoutFile(string const & fn,string const & cln,string const & desc,string const & prereq,string const & category,bool texclassavail)42 LayoutFile::LayoutFile(string const & fn, string const & cln,
43 		       string const & desc, string const & prereq,
44 		       string const & category, bool texclassavail)
45 {
46 	name_ = onlyFileName(fn);
47 	path_ = fn.rfind('/') == string::npos ? string() : onlyPath(fn);
48 	latexname_ = cln;
49 	description_ = desc;
50 	prerequisites_ = prereq;
51 	category_ = category;
52 	tex_class_avail_ = texclassavail;
53 }
54 
55 
~LayoutFileList()56 LayoutFileList::~LayoutFileList()
57 {
58 	ClassMap::const_iterator it = classmap_.begin();
59 	ClassMap::const_iterator en = classmap_.end();
60 	for (; it != en; ++it) {
61 		delete it->second;
62 	}
63 }
64 
65 
get()66 LayoutFileList & LayoutFileList::get()
67 {
68 	static LayoutFileList baseclasslist;
69 	return baseclasslist;
70 }
71 
72 
haveClass(string const & classname) const73 bool LayoutFileList::haveClass(string const & classname) const
74 {
75 	ClassMap::const_iterator it = classmap_.begin();
76 	ClassMap::const_iterator en = classmap_.end();
77 	for (; it != en; ++it) {
78 		if (it->first == classname)
79 			return true;
80 	}
81 	return false;
82 }
83 
84 
operator [](string const & classname) const85 LayoutFile const & LayoutFileList::operator[](string const & classname) const
86 {
87 	LATTEST(haveClass(classname));
88 	// safe to continue, since we will make an empty LayoutFile
89 	return *classmap_[classname];
90 }
91 
92 
operator [](string const & classname)93 LayoutFile & LayoutFileList::operator[](string const & classname)
94 {
95 	LATTEST(haveClass(classname));
96 	// safe to continue, since we will make an empty LayoutFile
97 	return *classmap_[classname];
98 }
99 
100 
101 // Reads LyX textclass definitions according to textclass config file
read()102 bool LayoutFileList::read()
103 {
104 	bool success = false;
105 	Lexer lex;
106 	FileName const real_file = libFileSearch("", "textclass.lst");
107 	LYXERR(Debug::TCLASS, "Reading textclasses from `" << real_file << "'.");
108 
109 	if (real_file.empty()) {
110 		LYXERR0("LayoutFileList::Read: unable to find textclass file  "
111 		    << "`textclass.lst'.");
112 	} else if (!lex.setFile(real_file)) {
113 		LYXERR0("LayoutFileList::Read: lyxlex was not able to set file: "
114 		       << real_file << '.');
115 	} else if (!lex.isOK()) {
116 		LYXERR0("LayoutFileList::Read: unable to open textclass file  `"
117 		       << makeDisplayPath(real_file.absFileName(), 1000)
118 		       << "'\nCheck your installation.");
119 	} else {
120 		// we have a file we can read.
121 		bool finished = false;
122 		LYXERR(Debug::TCLASS, "Starting parsing of textclass.lst");
123 		while (lex.isOK() && !finished) {
124 			LYXERR(Debug::TCLASS, "\tline by line");
125 			switch (lex.lex()) {
126 			case Lexer::LEX_FEOF:
127 				finished = true;
128 				break;
129 			default:
130 				string const fname = lex.getString();
131 				LYXERR(Debug::TCLASS, "Fname: " << fname);
132 				if (!lex.next())
133 					break;
134 				string const clname = lex.getString();
135 				LYXERR(Debug::TCLASS, "Clname: " << clname);
136 				if (!lex.next())
137 					break;
138 				string const desc = lex.getString();
139 				LYXERR(Debug::TCLASS, "Desc: " << desc);
140 				if (!lex.next())
141 					break;
142 				bool avail = lex.getBool();
143 				LYXERR(Debug::TCLASS, "Avail: " << avail);
144 				if (!lex.next())
145 					break;
146 				string const prereq = lex.getString();
147 				LYXERR(Debug::TCLASS, "Prereq: " << prereq);
148 				if (!lex.next())
149 					break;
150 				string const category = lex.getString();
151 				LYXERR(Debug::TCLASS, "Category: " << category);
152 				// This code is run when we have
153 				// fname, clname, desc, prereq, and avail
154 				LayoutFile * tmpl = new LayoutFile(fname, clname, desc, prereq, category, avail);
155 				if (lyxerr.debugging(Debug::TCLASS)) {
156 					// only system layout files are loaded here so no
157 					// buffer path is needed.
158 					tmpl->load();
159 				}
160 				classmap_[fname] = tmpl;
161 			} // end of switch
162 		} // end of while loop
163 		LYXERR(Debug::TCLASS, "End parsing of textclass.lst");
164 		success = true;
165 	} // end of else
166 
167 	// LyX will start with an empty classmap_. This is OK because
168 	// (a) we will give the user a chance to reconfigure (see bug 2829) and
169 	// (b) even if that fails, we can use addEmptyClass() to get some basic
170 	// functionality.
171 	if (classmap_.empty())
172 		LYXERR0("LayoutFileList::Read: no textclasses found!");
173 	return success;
174 }
175 
176 
classList() const177 std::vector<LayoutFileIndex> LayoutFileList::classList() const
178 {
179 	std::vector<LayoutFileIndex> cl;
180 	ClassMap::const_iterator it = classmap_.begin();
181 	ClassMap::const_iterator en = classmap_.end();
182 	for (; it != en; ++it)
183 		cl.push_back(it->first);
184 	return cl;
185 }
186 
187 
reset(LayoutFileIndex const & classname)188 void LayoutFileList::reset(LayoutFileIndex const & classname)
189 {
190 	LATTEST(haveClass(classname));
191 	// safe to continue, since we will make an empty LayoutFile
192 	LayoutFile * tc = classmap_[classname];
193 	LayoutFile * tmpl =
194 		new LayoutFile(tc->name(), tc->latexname(), tc->description(),
195 		               tc->prerequisites(), tc->category(),
196 			       tc->isTeXClassAvailable());
197 	classmap_[classname] = tmpl;
198 	delete tc;
199 }
200 
201 
202 namespace {
203 
204 string layoutpost =
205 		"Columns      1\n"
206 		"Sides        1\n"
207 		"SecNumDepth  2\n"
208 		"TocDepth     2\n"
209 		"DefaultStyle	Standard\n\n"
210 		"Style Standard\n"
211 		"	Category              MainText\n"
212 		"	Margin                Static\n"
213 		"	LatexType             Paragraph\n"
214 		"	LatexName             dummy\n"
215 		"	ParIndent             MM\n"
216 		"	ParSkip               0.4\n"
217 		"	Align                 Block\n"
218 		"	AlignPossible         Block, Left, Right, Center\n"
219 		"	LabelType             No_Label\n"
220 		"End\n";
221 
222 }
223 
224 
addEmptyClass(string const & textclass)225 LayoutFileIndex LayoutFileList::addEmptyClass(string const & textclass)
226 {
227 	// FIXME This could be simplified a bit to call TextClass::read(string, ReadType).
228 
229 	TempFile tempfile("basicXXXXXX.layout");
230 	FileName const tempLayout = tempfile.name();
231 	ofstream ofs(tempLayout.toFilesystemEncoding().c_str());
232 	// This writes a very basic class, but it also attempts to include
233 	// stdclass.inc. That would give us something moderately usable.
234 	ofs << "# This layout is automatically generated\n"
235 	       "# \\DeclareLaTeXClass{" << textclass << "}\n\n"
236 	       "Format " << LAYOUT_FORMAT << "\n"
237 	       "Input stdclass.inc\n\n"
238 	    << layoutpost;
239 	ofs.close();
240 
241 	// We do not know if a LaTeX class is available for this document, but setting
242 	// the last parameter to true will suppress a warning message about missing
243 	// tex class.
244 	LayoutFile * tc = new LayoutFile(textclass, textclass,
245 			"Unknown text class " + textclass, textclass + ".cls", "", true);
246 
247 	if (!tc->load(tempLayout.absFileName())) {
248 		// The only way this happens is because the hardcoded layout file
249 		// above is wrong or stdclass.inc cannot be found. So try again
250 		// without stdclass.inc and without stdinsets.inc.
251 		ofstream ofs2(tempLayout.toFilesystemEncoding().c_str());
252 		ofs2 << "# This layout is automatically generated\n"
253 		        "# \\DeclareLaTeXClass{" << textclass << "}\n\n"
254 		        "Format " << LAYOUT_FORMAT << "\n"
255 		        "Provides stdinsets 1\n"
256 		     << layoutpost;
257 		ofs2.close();
258 		if (!tc->load(tempLayout.absFileName())) {
259 			// This can only happen if the hardcoded file above is wrong
260 			// or there is some weird filesystem error.
261 			LATTEST(false); // We will get an empty layout or something.
262 		}
263 	}
264 
265 	classmap_[textclass] = tc;
266 	return textclass;
267 }
268 
269 
addLocalLayout(string const & textclass,string const & path,string const & oldpath)270 LayoutFileIndex  LayoutFileList::addLocalLayout(
271 	string const & textclass, string const & path, string const & oldpath)
272 {
273 	// FIXME  There is a bug here: 4593
274 	//
275 	// only check for textclass.layout file, .cls can be anywhere in $TEXINPUTS
276 	// NOTE: latex class name is defined in textclass.layout, which can be
277 	// different from textclass
278 	string fullName = addName(path, textclass + ".layout");
279 
280 	FileName layout_file(fullName);
281 	bool moved = false;
282 
283 	if (!layout_file.exists()) {
284 		if (oldpath.empty())
285 			return string();
286 		// The document has been moved to a different directory.
287 		// However, oldpath always points to the right spot, unless
288 		// the user also moved the layout file.
289 		fullName = addName(oldpath, textclass + ".layout");
290 		layout_file.set(fullName);
291 		layout_file.refresh();
292 		if (!layout_file.exists())
293 			return string();
294 		moved = true;
295 	}
296 
297 	LYXERR(Debug::TCLASS, "Adding class " << textclass << " from directory " << path);
298 	// Read .layout file and get description, real latex classname etc
299 	//
300 	// This is a C++ version of function processLayoutFile in configure.py,
301 	// which uses the following regex
302 	//     \Declare(LaTeX|DocBook)Class\s*(\[([^,]*)(,.*)*\])*\s*{(.*)}
303 	ifstream ifs(layout_file.toFilesystemEncoding().c_str());
304 	static regex const reg("^\\s*#\\s*\\\\Declare(LaTeX|DocBook)Class\\s*"
305 		"(?:\\[([^,]*)(?:,.*)*\\])*\\s*\\{(.*)\\}\\s*");
306 	static regex const catreg("^\\s*#\\s*\\\\DeclareCategory\\{(.*)\\}\\s*");
307 	string line;
308 	string class_name;
309 	string class_prereq;
310 	string category;
311 	bool have_declaration = false;
312 	while (getline(ifs, line)) {
313 		// look for the \DeclareXXXClass line
314 		smatch sub;
315 		if (regex_match(line, sub, reg)) {
316 			// returns: whole string, classtype (not used here), class name, description
317 			// LASSERT: Why would this fail?
318 			LASSERT(sub.size() == 4, /**/);
319 			// now, create a TextClass with description containing path information
320 			class_name = (sub.str(2) == "" ? textclass : sub.str(2));
321 			class_prereq = class_name + ".cls";
322 			have_declaration = true;
323 		}
324 		else if (regex_match(line, sub, catreg)) {
325 			category = sub.str(1);
326 		}
327 		if (have_declaration && !category.empty())
328 			break;
329 	}
330 
331 	if (!have_declaration)
332 		return string();
333 
334 	LayoutFile * tmpl =
335 		new LayoutFile(addName(moved ? oldpath : path, textclass),
336 			class_name, textclass, class_prereq, category, true);
337 	//FIXME: The prerequisites are available from the layout file and
338 	//       can be extracted from the above regex, but for now this
339 	//       field is simply set to class_name + ".cls"
340 	// This textclass is added on request so it will definitely be
341 	// used. Load it now because other load() calls may fail if they
342 	// are called in a context without buffer path information.
343 	tmpl->load(moved ? oldpath : path);
344 	// There will be only one textclass with this name, even if different
345 	// layout files are loaded from different directories.
346 	if (haveClass(textclass)) {
347 		// Unconditionally issuing the warning may be confusing when
348 		// saving the document with a different name, as it is exactly
349 		// the same textclass that is being re-established.
350 		LYXERR(Debug::TCLASS, "Existing textclass " << textclass << " is redefined by " << fullName);
351 		delete classmap_[textclass];
352 	}
353 	classmap_[textclass] = tmpl;
354 	return removeExtension(fullName);
355 }
356 
357 
load(string const & name,string const & buf_path)358 bool LayoutFileList::load(string const & name, string const & buf_path)
359 {
360 	if (!haveClass(name)) {
361 		LYXERR0("Document class \"" << name << "\" does not exist.");
362 		return false;
363 	}
364 
365 	LayoutFile * tc = classmap_[name];
366 	return tc->load(buf_path);
367 }
368 
369 
defaultBaseclass()370 LayoutFileIndex defaultBaseclass()
371 {
372 	if (LayoutFileList::get().haveClass("article"))
373 		return string("article");
374 	if (LayoutFileList::get().empty())
375 		// we'll call it that, since this gives the user a chance to
376 		// have a functioning document when things improve.
377 		return string("article");
378 	return LayoutFileList::get().classList().front();
379 }
380 
381 } // namespace lyx
382