OSDN Git Service

Reduce compilation time (2)
[winmerge-jp/winmerge-jp.git] / Src / Environment.cpp
1 /** 
2  * @file  Environment.cpp
3  *
4  * @brief Environment related routines.
5  */
6
7 #include "pch.h"
8 #define POCO_NO_UNWINDOWS 1
9 #include "Environment.h"
10 #include <windows.h>
11 #pragma warning (push)                  // prevent "warning C4091: 'typedef ': ignored on left of 'tagGPFIDL_FLAGS' when no variable is declared"
12 #pragma warning (disable:4091)  // VC bug when using XP enabled toolsets.
13 #include <shlobj.h>
14 #pragma warning (pop)
15 #include <sstream>
16 #include <Poco/Path.h>
17 #include <Poco/Process.h>
18 #include "paths.h"
19 #include "unicoder.h"
20
21 using Poco::Path;
22 using Poco::Process;
23
24 namespace env
25 {
26
27 /**
28  * @brief Temp path.
29  * Static string used by GetTemporaryPath() for storing temp path.
30  */
31 static String strTempPath;
32 static String strProgPath;
33
34 void SetTemporaryPath(const String& path)
35 {
36         strTempPath = paths::AddTrailingSlash(paths::GetLongPath(path));
37         paths::CreateIfNeeded(strTempPath);
38 }
39
40 /** 
41  * @brief Get folder for temporary files.
42  * This function returns system temp folder.
43  * @return Temp path, or empty string if error happened.
44  * @note Temp path is cached after first call.
45  * @todo Should we return `nullptr` for error case?
46  */
47 String GetTemporaryPath()
48 {
49         if (strTempPath.empty())
50         {
51                 strTempPath = GetSystemTempPath();
52                 if (strTempPath.empty())
53                         return strTempPath;
54
55                 paths::CreateIfNeeded(strTempPath);
56         }
57         return strTempPath;
58 }
59
60 /**
61  * @brief Get filename for temporary file.
62  * @param [in] lpPathName Temporary file folder.
63  * @param [in] lpPrefixString Prefix to use for filename.
64  * @param [out] pnerr Error code if error happened.
65  * @return Full path for temporary file or empty string if error happened.
66  */
67 String GetTemporaryFileName(const String& lpPathName, const String& lpPrefixString, int * pnerr /*= nullptr*/)
68 {
69         TCHAR buffer[MAX_PATH] = {0};
70         if (lpPathName.length() > MAX_PATH-14)
71                 return _T(""); // failure
72         int rtn = ::GetTempFileName(lpPathName.c_str(), lpPrefixString.c_str(), 0, buffer);
73         if (rtn == 0)
74         {
75                 int err = GetLastError();
76                 if (pnerr != nullptr)
77                         *pnerr = err;
78                 return _T("");
79         }
80         return buffer;
81 }
82
83 String GetTempChildPath()
84 {
85         String path;
86         do
87         {
88                 path = paths::ConcatPath(GetTemporaryPath(), strutils::format(_T("%08x"), rand()));
89         } while (paths::IsDirectory(path) || !paths::CreateIfNeeded(path));
90         return path;
91 }
92
93 void SetProgPath(const String& path)
94 {
95         strProgPath = paths::AddTrailingSlash(path);
96 }
97
98 String GetProgPath()
99 {
100         if (strProgPath.empty())
101         {
102                 TCHAR temp[MAX_PATH] = {0};
103                 GetModuleFileName(nullptr, temp, MAX_PATH);
104                 strProgPath = paths::GetPathOnly(temp);
105         }
106         return strProgPath;
107 }
108
109 /**
110  * @brief Get Windows directory.
111  * @return Windows directory.
112  */
113 String GetWindowsDirectory()
114 {
115         TCHAR path[MAX_PATH];
116         path[0] = _T('\0');
117         ::GetWindowsDirectory(path, MAX_PATH);
118         return path;
119 }
120
121 /**
122  * @brief Return User's My Documents Folder.
123  * This function returns full path to User's My Documents -folder.
124  * @return Full path to My Documents -folder.
125  */
126 String GetMyDocuments()
127 {
128         TCHAR path[MAX_PATH];
129         path[0] = _T('\0');
130         SHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, 0, path);
131         return path;
132 }
133
134 /**
135  * @brief Return unique string for the instance.
136  * This function formats an unique string for WinMerge instance. The string
137  * is quaranteed to be unique for instance asking it.
138  * @param [in] name Additional name used as part of the string.
139  * @return Unique string for the instance.
140  */
141 String GetPerInstanceString(const String& name)
142 {
143         std::basic_stringstream<TCHAR> stream;
144         stream << name << Process::id();
145         return stream.str();
146 }
147
148 /**
149  * @brief Get system temporary directory.
150  * @return System temporary director.
151  */
152 String GetSystemTempPath()
153 {
154         try
155         {
156                 return ucr::toTString(Path::temp());
157         }
158         catch (...)
159         {
160                 return _T("");
161         }
162 }
163
164 static bool launchProgram(const String& sCmd, WORD wShowWindow)
165 {
166         STARTUPINFO stInfo = { sizeof(STARTUPINFO) };
167         stInfo.dwFlags = STARTF_USESHOWWINDOW;
168         stInfo.wShowWindow = wShowWindow;
169         PROCESS_INFORMATION processInfo;
170         bool retVal = !!CreateProcess(nullptr, (LPTSTR)sCmd.c_str(),
171                 nullptr, nullptr, FALSE, CREATE_DEFAULT_ERROR_MODE, nullptr, nullptr,
172                 &stInfo, &processInfo);
173         if (!retVal)
174                 return false;
175         CloseHandle(processInfo.hThread);
176         CloseHandle(processInfo.hProcess);
177         return true;
178 }
179
180 /**
181  * @brief Load registry keys from .reg file if existing .reg file
182  */
183 bool LoadRegistryFromFile(const String& sRegFilePath)
184 {
185         if (paths::DoesPathExist(sRegFilePath) != paths::IS_EXISTING_FILE)
186                 return false;
187         return launchProgram(_T("reg.exe import \"") + sRegFilePath + _T("\""), SW_HIDE);
188 }
189
190 /** 
191  * @brief Save registry keys to .reg file if existing .reg file
192  */
193 bool SaveRegistryToFile(const String& sRegFilePath, const String& sRegDir)
194 {
195         if (paths::DoesPathExist(sRegFilePath) != paths::IS_EXISTING_FILE)
196                 return false;
197         DeleteFile(sRegFilePath.c_str());
198         return launchProgram(_T("reg.exe export HKCU\\") + sRegDir + _T(" \"") + sRegFilePath + _T("\""), SW_HIDE);
199 }
200
201 }