OSDN Git Service

Fixed a regression in d92fb7fbcc34b7bf6b1649befab1d9eafec13684: We must not close...
[lamexp/LameXP.git] / src / Tool_Abstract.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Tool_Abstract.h"
23
24 #include "Global.h"
25
26 #include <QProcess>
27 #include <QMutex>
28 #include <QMutexLocker>
29 #include <QLibrary>
30 #include <QProcessEnvironment>
31 #include <QDir>
32
33 /*
34  * Win32 API definitions
35  */
36 typedef HANDLE (WINAPI *CreateJobObjectFun)(__in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCSTR lpName);
37 typedef BOOL (WINAPI *SetInformationJobObjectFun)(__in HANDLE hJob, __in JOBOBJECTINFOCLASS JobObjectInformationClass, __in_bcount(cbJobObjectInformationLength) LPVOID lpJobObjectInformation, __in DWORD cbJobObjectInformationLength);
38 typedef BOOL (WINAPI *AssignProcessToJobObjectFun)(__in HANDLE hJob, __in HANDLE hProcess);
39
40 /*
41  * Static vars
42  */
43 quint64 AbstractTool::m_lastLaunchTime = 0ui64;
44 QMutex *AbstractTool::m_mutex_startProcess = NULL;
45 HANDLE AbstractTool::m_handle_jobObject = NULL;
46 unsigned int AbstractTool::m_jobObjRefCount = 0U;
47
48 /*
49  * Const
50  */
51 static const DWORD START_DELAY = 333; //in milliseconds
52 static const quint64 START_DELAY_NANO = START_DELAY * 1000 * 10; //in 100-nanosecond intervals
53
54 /*
55  * Constructor
56  */
57 AbstractTool::AbstractTool(void)
58 {
59         static CreateJobObjectFun CreateJobObjectPtr = NULL;
60         static SetInformationJobObjectFun SetInformationJobObjectPtr = NULL;
61
62         if(!m_mutex_startProcess)
63         {
64                 m_mutex_startProcess = new QMutex();
65         }
66
67         QMutexLocker lock(m_mutex_startProcess);
68
69         if(m_jobObjRefCount < 1U)
70         {
71                 if(!CreateJobObjectPtr || !SetInformationJobObjectPtr)
72                 {
73                         QLibrary Kernel32Lib("kernel32.dll");
74                         CreateJobObjectPtr = (CreateJobObjectFun) Kernel32Lib.resolve("CreateJobObjectA");
75                         SetInformationJobObjectPtr = (SetInformationJobObjectFun) Kernel32Lib.resolve("SetInformationJobObject");
76                 }
77                 if(CreateJobObjectPtr && SetInformationJobObjectPtr)
78                 {
79                         HANDLE jobObject = CreateJobObjectPtr(NULL, NULL);
80                         if((jobObject != NULL) && (jobObject != INVALID_HANDLE_VALUE))
81                         {
82                                 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
83                                 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
84                                 memset(&jobExtendedLimitInfo.BasicLimitInformation, 0, sizeof(JOBOBJECT_BASIC_LIMIT_INFORMATION));
85                                 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
86                                 if(SetInformationJobObjectPtr(jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)))
87                                 {
88                                         m_handle_jobObject = jobObject;
89                                         m_jobObjRefCount = 1U;
90                                 }
91                                 else
92                                 {
93                                         qWarning("Failed to set job object information!");
94                                         CloseHandle(jobObject);
95                                 }
96                         }
97                 }
98         }
99         else
100         {
101                 m_jobObjRefCount++;
102         }
103
104         m_firstLaunch = true;
105 }
106
107 /*
108  * Destructor
109  */
110 AbstractTool::~AbstractTool(void)
111 {
112         QMutexLocker lock(m_mutex_startProcess);
113
114         if(m_jobObjRefCount >= 1U)
115         {
116                 m_jobObjRefCount--;
117                 if((m_jobObjRefCount < 1U) && m_handle_jobObject)
118                 {
119                         CloseHandle(m_handle_jobObject);
120                         m_handle_jobObject = NULL;
121                 }
122         }
123 }
124
125 /*
126  * Initialize and launch process object
127  */
128 bool AbstractTool::startProcess(QProcess &process, const QString &program, const QStringList &args)
129 {
130         static AssignProcessToJobObjectFun AssignProcessToJobObjectPtr = NULL;
131         
132         QMutexLocker lock(m_mutex_startProcess);
133
134         if(currentTime() <= m_lastLaunchTime)
135         {
136                 Sleep(START_DELAY);
137         }
138
139         emit messageLogged(commandline2string(program, args) + "\n");
140
141         QProcessEnvironment env = process.processEnvironment();
142         if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
143         env.insert("TEMP", QDir::toNativeSeparators(lamexp_temp_folder2()));
144         env.insert("TMP", QDir::toNativeSeparators(lamexp_temp_folder2()));
145         process.setProcessEnvironment(env);
146         
147         if(!AssignProcessToJobObjectPtr)
148         {
149                 QLibrary Kernel32Lib("kernel32.dll");
150                 AssignProcessToJobObjectPtr = (AssignProcessToJobObjectFun) Kernel32Lib.resolve("AssignProcessToJobObject");
151         }
152         
153         process.setProcessChannelMode(QProcess::MergedChannels);
154         process.setReadChannel(QProcess::StandardOutput);
155         process.start(program, args);
156         
157         if(process.waitForStarted())
158         {
159                 if(AssignProcessToJobObjectPtr && m_handle_jobObject)
160                 {
161                         if(!AssignProcessToJobObjectPtr(m_handle_jobObject, process.pid()->hProcess))
162                         {
163                                 qWarning("Failed to assign process to job object!");
164                         }
165                 }
166                 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
167                 {
168                         SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
169                 }
170                 
171                 lock.unlock();
172                 
173                 if(m_firstLaunch)
174                 {
175                         emit statusUpdated(0);
176                         m_firstLaunch = false;
177                 }
178                 
179                 m_lastLaunchTime = currentTime() + START_DELAY_NANO;
180                 return true;
181         }
182
183         emit messageLogged("Process creation has failed :-(");
184         QString errorMsg= process.errorString().trimmed();
185         if(!errorMsg.isEmpty()) emit messageLogged(errorMsg);
186
187         process.kill();
188         process.waitForFinished(-1);
189
190         m_lastLaunchTime = currentTime() + START_DELAY_NANO;
191         return false;
192 }
193
194 /*
195  * Convert program arguments to single string
196  */
197 QString AbstractTool::commandline2string(const QString &program, const QStringList &arguments)
198 {
199         QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
200         
201         for(int i = 0; i < arguments.count(); i++)
202         {
203                 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
204         }
205
206         return commandline;
207 }
208
209 /*
210  * Convert long path to short path
211  */
212 QString AbstractTool::pathToShort(const QString &longPath)
213 {
214         QString shortPath;
215         DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
216         
217         if(buffSize > 0)
218         {
219                 wchar_t *buffer = new wchar_t[buffSize];
220                 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
221
222                 if(result > 0 && result < buffSize)
223                 {
224                         shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
225                 }
226
227                 delete[] buffer;
228         }
229
230         return (shortPath.isEmpty() ? longPath : shortPath);
231 }
232
233 const quint64 AbstractTool::currentTime(void)
234 {
235         FILETIME fileTime;
236         GetSystemTimeAsFileTime(&fileTime);
237
238         ULARGE_INTEGER temp;
239         temp.HighPart = fileTime.dwHighDateTime;
240         temp.LowPart = fileTime.dwLowDateTime;
241
242         return temp.QuadPart;
243 }