]> git.lyx.org Git - lyx.git/blob - src/support/path.h
another safety belt
[lyx.git] / src / support / path.h
1 // -*- C++ -*-
2 /**
3  * \file path.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS
10  */
11
12 #ifndef PATH_H
13 #define PATH_H
14
15 #include "LString.h"
16 //#include "filetools.h"
17 #include "lyxlib.h"
18 #include <boost/utility.hpp>
19
20 #ifdef __GNUG__
21 #pragma interface
22 #endif
23
24
25 /**
26  * Path - utility closs for stackable working directories
27  *
28  * You can use a local variable of this type to temporarily
29  * change to a directory as the cwd, for example :
30  *
31  * if (blah) {
32  *      Path p("/tmp/blah");
33  *      ...
34  * }
35  *
36  * At the end of p's scope the cwd is reset to its previous value.
37  */
38 class Path : boost::noncopyable {
39 public:
40         /// change to the given directory
41         explicit
42         Path(string const & path)
43                 : popped_(false)
44         {
45                 if (!path.empty()) {
46                         pushedDir_ = lyx::getcwd();
47                         if (pushedDir_.empty() || lyx::chdir(path))
48                                 /* FIXME: throw */;
49                 } else {
50                         popped_ = true;
51                 }
52         }
53
54         /// set cwd to the previous value if needed
55         ~Path()
56         {
57                 if (!popped_) pop();
58         }
59
60         /// set cwd to the previous value if needed
61         int pop();
62 private:
63         /// whether we are in the new cwd or not
64         bool popped_;
65         /// the previous cwd
66         string pushedDir_;
67 };
68
69 // To avoid the wrong usage:
70 // Path("/tmp");   // wrong
71 // Path p("/tmp");  // right
72 // we add this macro:
73 ///
74 #define Path(x) unnamed_Path;
75 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
76
77 #endif // PATH_H