Moved some more OS-specific functions into the MUtilities library.

This commit is contained in:
LoRd_MuldeR 2014-12-04 00:02:42 +01:00
parent 6412989afd
commit 06db588742
14 changed files with 65 additions and 482 deletions

View File

@ -35,7 +35,7 @@
#define VER_LAMEXP_MINOR_LO 1 #define VER_LAMEXP_MINOR_LO 1
#define VER_LAMEXP_TYPE Beta #define VER_LAMEXP_TYPE Beta
#define VER_LAMEXP_PATCH 4 #define VER_LAMEXP_PATCH 4
#define VER_LAMEXP_BUILD 1610 #define VER_LAMEXP_BUILD 1612
#define VER_LAMEXP_CONFG 1558 #define VER_LAMEXP_CONFG 1558
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

View File

@ -366,7 +366,7 @@ void AboutDialog::openURL(const QString &url)
{ {
if(!QDesktopServices::openUrl(QUrl(url))) if(!QDesktopServices::openUrl(QUrl(url)))
{ {
lamexp_exec_shell(this, url); MUtils::OS::shell_open(this, url);
} }
} }
@ -386,8 +386,8 @@ void AboutDialog::gotoLicenseTab(void)
void AboutDialog::moveDisque(void) void AboutDialog::moveDisque(void)
{ {
int delta = 2; int delta = 2;
const __int64 perfFrequ = lamexp_perfcounter_frequ(); const qint64 perfFrequ = MUtils::OS::perfcounter_freq();
const __int64 perfCount = lamexp_perfcounter_value(); const qint64 perfCount = MUtils::OS::perfcounter_read();
if((perfFrequ >= 0) && (perfCount >= 0)) if((perfFrequ >= 0) && (perfCount >= 0))
{ {

View File

@ -38,6 +38,7 @@
//MUtils //MUtils
#include <MUtils/Global.h> #include <MUtils/Global.h>
#include <MUtils/OSSupport.h>
//Qt includes //Qt includes
#include <QFileInfo> #include <QFileInfo>
@ -302,14 +303,15 @@ void CueImportDialog::importButtonClicked(void)
writeTest.remove(); writeTest.remove();
} }
bool ok = false; quint64 currentFreeDiskspace = 0;
unsigned __int64 currentFreeDiskspace = lamexp_free_diskspace(m_outputDir, &ok); if(MUtils::OS::free_diskspace(m_outputDir, currentFreeDiskspace))
{
if(ok && (currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))) if(currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))
{ {
QMessageBox::warning(this, tr("Low Diskspace Warning"), QString("<nobr>%1</nobr><br><nobr>%2</nobr>").arg(tr("There are less than %1 GB of free diskspace available in the selected output directory.").arg(QString::number(minimumFreeDiskspaceMultiplier)), tr("It is highly recommend to free up more diskspace before proceeding with the import!"))); QMessageBox::warning(this, tr("Low Diskspace Warning"), QString("<nobr>%1</nobr><br><nobr>%2</nobr>").arg(tr("There are less than %1 GB of free diskspace available in the selected output directory.").arg(QString::number(minimumFreeDiskspaceMultiplier)), tr("It is highly recommend to free up more diskspace before proceeding with the import!")));
return; return;
} }
}
importCueSheet(); importCueSheet();
accept(); accept();

View File

@ -630,7 +630,7 @@ MainWindow::MainWindow(FileListModel *fileListModel, AudioFileModel_MetaInfo *me
ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo()); ui->actionCheckForBetaUpdates->setChecked(m_settings->autoUpdateCheckBeta() || lamexp_version_demo());
ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo()); ui->actionCheckForBetaUpdates->setEnabled(!lamexp_version_demo());
ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer()); ui->actionHibernateComputer->setChecked(m_settings->hibernateComputer());
ui->actionHibernateComputer->setEnabled(lamexp_is_hibernation_supported()); ui->actionHibernateComputer->setEnabled(MUtils::OS::is_hibernation_supported());
connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool))); connect(ui->actionDisableUpdateReminder, SIGNAL(triggered(bool)), this, SLOT(disableUpdateReminderActionTriggered(bool)));
connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool))); connect(ui->actionDisableSounds, SIGNAL(triggered(bool)), this, SLOT(disableSoundsActionTriggered(bool)));
connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool))); connect(ui->actionDisableNeroAacNotifications, SIGNAL(triggered(bool)), this, SLOT(disableNeroAacNotificationsActionTriggered(bool)));
@ -1332,7 +1332,7 @@ void MainWindow::windowShown(void)
QString uninstallerPath = uninstallerInfo.canonicalFilePath(); QString uninstallerPath = uninstallerInfo.canonicalFilePath();
for(int i = 0; i < 3; i++) for(int i = 0; i < 3; i++)
{ {
if(lamexp_exec_shell(this, QDir::toNativeSeparators(uninstallerPath), "/Force", QDir::toNativeSeparators(uninstallerDir))) break; if(MUtils::OS::shell_open(this, QDir::toNativeSeparators(uninstallerPath), "/Force", QDir::toNativeSeparators(uninstallerDir))) break;
} }
} }
QApplication::quit(); QApplication::quit();
@ -1594,10 +1594,10 @@ void MainWindow::encodeButtonClicked(void)
return; return;
} }
bool ok = false; quint64 currentFreeDiskspace = 0;
unsigned __int64 currentFreeDiskspace = lamexp_free_diskspace(tempFolder, &ok); if(MUtils::OS::free_diskspace(tempFolder, currentFreeDiskspace))
{
if(ok && (currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))) if(currentFreeDiskspace < (oneGigabyte * minimumFreeDiskspaceMultiplier))
{ {
QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive); QStringList tempFolderParts = tempFolder.split("/", QString::SkipEmptyParts, Qt::CaseInsensitive);
tempFolderParts.takeLast(); tempFolderParts.takeLast();
@ -1621,6 +1621,7 @@ void MainWindow::encodeButtonClicked(void)
break; break;
} }
} }
}
switch(m_settings->compressionEncoder()) switch(m_settings->compressionEncoder())
{ {
@ -2468,7 +2469,7 @@ void MainWindow::previewContextActionTriggered(void)
return; return;
} }
if(!lamexp_open_media_file(m_fileListModel->getFile(index).filePath())) if(!MUtils::OS::open_media_file(m_fileListModel->getFile(index).filePath()))
{ {
qDebug("Player not found, falling back to default application..."); qDebug("Player not found, falling back to default application...");
QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath())); QDesktopServices::openUrl(QString("file:///").append(m_fileListModel->getFile(index).filePath()));
@ -3011,7 +3012,7 @@ void MainWindow::showFolderContextActionTriggered(void)
QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex())); QString path = QDir::toNativeSeparators(m_fileSystemModel->filePath(ui->outputFolderView->currentIndex()));
if(!path.endsWith(QDir::separator())) path.append(QDir::separator()); if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
lamexp_exec_shell(this, path, true); MUtils::OS::shell_open(this, path, true);
} }
/* /*
@ -3282,7 +3283,7 @@ void MainWindow::outputFolderMouseEventOccurred(QWidget *sender, QEvent *event)
{ {
QString path = ui->outputFolderLabel->text(); QString path = ui->outputFolderLabel->text();
if(!path.endsWith(QDir::separator())) path.append(QDir::separator()); if(!path.endsWith(QDir::separator())) path.append(QDir::separator());
lamexp_exec_shell(this, path, true); MUtils::OS::shell_open(this, path, true);
} }
break; break;
case QEvent::Enter: case QEvent::Enter:

View File

@ -389,7 +389,7 @@ void ProcessingDialog::showEvent(QShowEvent *event)
m_progressIndicator->start(); m_progressIndicator->start();
m_systemTray->setVisible(true); m_systemTray->setVisible(true);
lamexp_change_process_priority(1); MUtils::OS::change_process_priority(1);
ui->label_cpu->setText(NA); ui->label_cpu->setText(NA);
ui->label_disk->setText(NA); ui->label_disk->setText(NA);
@ -559,16 +559,9 @@ void ProcessingDialog::initEncoding(void)
m_threadPool->setMaxThreadCount(maximumInstances); m_threadPool->setMaxThreadCount(maximumInstances);
} }
//for(int i = 0; i < m_threadPool->maxThreadCount(); i++)
//{
// startNextJob();
// qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
// QThread::yieldCurrentThread();
//}
m_initThreads = m_threadPool->maxThreadCount(); m_initThreads = m_threadPool->maxThreadCount();
QTimer::singleShot(100, this, SLOT(initNextJob())); QTimer::singleShot(100, this, SLOT(initNextJob()));
m_timerStart = lamexp_perfcounter_value(); m_timerStart = MUtils::OS::perfcounter_read();
} }
void ProcessingDialog::initNextJob(void) void ProcessingDialog::initNextJob(void)
@ -718,8 +711,8 @@ void ProcessingDialog::doneEncoding(void)
} }
else else
{ {
const __int64 counter = lamexp_perfcounter_value(); const qint64 counter = MUtils::OS::perfcounter_read();
const __int64 frequency = lamexp_perfcounter_frequ(); const qint64 frequency = MUtils::OS::perfcounter_freq();
if((counter >= 0I64) && (frequency >= 0)) if((counter >= 0I64) && (frequency >= 0))
{ {
if((m_timerStart >= 0I64) && (m_timerStart < counter)) if((m_timerStart >= 0I64) && (m_timerStart < counter))

View File

@ -35,6 +35,7 @@
#include <MUtils/UpdateChecker.h> #include <MUtils/UpdateChecker.h>
#include <MUtils/Version.h> #include <MUtils/Version.h>
#include <MUtils/Exception.h> #include <MUtils/Exception.h>
#include <MUtils/OSSupport.h>
//Qt includes //Qt includes
#include <QClipboard> #include <QClipboard>
@ -241,7 +242,7 @@ void UpdateDialog::checkForUpdates(void)
qWarning("Update in progress, cannot check for updates now!"); qWarning("Update in progress, cannot check for updates now!");
} }
if(!lamexp_user_is_admin()) if(!MUtils::OS::user_is_admin())
{ {
qWarning("User is not in the \"admin\" group, cannot update!"); qWarning("User is not in the \"admin\" group, cannot update!");
QString message; QString message;
@ -413,7 +414,7 @@ void UpdateDialog::applyUpdate(void)
bool updateStarted = process.waitForStarted(); bool updateStarted = process.waitForStarted();
if(updateStarted) if(updateStarted)
{ {
m_updaterProcess = lamexp_process_id(&process); m_updaterProcess = MUtils::OS::process_id(&process);
loop.exec(QEventLoop::ExcludeUserInputEvents); loop.exec(QEventLoop::ExcludeUserInputEvents);
} }

View File

@ -87,48 +87,31 @@ void lamexp_blink_window(QWidget *poWindow, unsigned int count = 10, unsigned in
bool lamexp_block_window_move(void *message); bool lamexp_block_window_move(void *message);
bool lamexp_bring_process_to_front(const unsigned long pid); bool lamexp_bring_process_to_front(const unsigned long pid);
bool lamexp_bring_to_front(const QWidget *win); bool lamexp_bring_to_front(const QWidget *win);
bool lamexp_change_process_priority(const int priority);
bool lamexp_change_process_priority(void *hProcess, const int priority);
bool lamexp_change_process_priority(const QProcess *proc, const int priority);
bool lamexp_check_escape_state(void); bool lamexp_check_escape_state(void);
bool lamexp_check_sysmenu_msg(void *message, const unsigned int identifier); bool lamexp_check_sysmenu_msg(void *message, const unsigned int identifier);
bool lamexp_check_tool(const QString &toolName); bool lamexp_check_tool(const QString &toolName);
const QString lamexp_clean_filename(const QString &str); const QString lamexp_clean_filename(const QString &str);
const QString lamexp_clean_filepath(const QString &str); const QString lamexp_clean_filepath(const QString &str);
unsigned __int64 lamexp_current_file_time(void);
void lamexp_dbg_dbg_output_string(const char* format, ...);
unsigned long lamexp_dbg_private_bytes(void); unsigned long lamexp_dbg_private_bytes(void);
bool lamexp_enable_close_button(const QWidget *win, const bool bEnable = true); bool lamexp_enable_close_button(const QWidget *win, const bool bEnable = true);
bool lamexp_exec_shell(const QWidget *win, const QString &url, const bool explore = false);
bool lamexp_exec_shell(const QWidget *win, const QString &url, const QString &parameters, const QString &directory, const bool explore = false);
void lamexp_finalization(void); void lamexp_finalization(void);
unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok = NULL);
void lamexp_free_window_icon(lamexp_icon_t *icon); void lamexp_free_window_icon(lamexp_icon_t *icon);
int lamexp_init_ipc(void); int lamexp_init_ipc(void);
bool lamexp_install_translator(const QString &language); bool lamexp_install_translator(const QString &language);
bool lamexp_install_translator_from_file(const QString &qmFile); bool lamexp_install_translator_from_file(const QString &qmFile);
void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize); void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize);
void lamexp_ipc_send(unsigned int command, const char* message); void lamexp_ipc_send(unsigned int command, const char* message);
bool lamexp_is_executable(const QString &path);
bool lamexp_is_hibernation_supported(void);
const QString lamexp_lookup_tool(const QString &toolName); const QString lamexp_lookup_tool(const QString &toolName);
const char *lamexp_mulders_url(void); const char *lamexp_mulders_url(void);
int lamexp_network_status(void);
bool lamexp_open_media_file(const QString &mediaFilePath);
QString lamexp_path_to_short(const QString &longPath);
__int64 lamexp_perfcounter_frequ(void);
__int64 lamexp_perfcounter_value(void);
bool lamexp_play_sound(const QString &name, const bool bAsync); bool lamexp_play_sound(const QString &name, const bool bAsync);
bool lamexp_play_sound_file(const QString &library, const unsigned short uiSoundIdx, const bool bAsync); bool lamexp_play_sound_file(const QString &library, const unsigned short uiSoundIdx, const bool bAsync);
bool lamexp_play_sound_alias(const QString &alias, const bool bAsync); bool lamexp_play_sound_alias(const QString &alias, const bool bAsync);
bool lamexp_portable_mode(void); bool lamexp_portable_mode(void);
unsigned long lamexp_process_id(const QProcess *proc);
QStringList lamexp_query_translations(void); QStringList lamexp_query_translations(void);
void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version = 0, const QString *tag = NULL); void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version = 0, const QString *tag = NULL);
lamexp_icon_t *lamexp_set_window_icon(QWidget *window, const QIcon &icon, const bool bIsBigIcon); lamexp_icon_t *lamexp_set_window_icon(QWidget *window, const QIcon &icon, const bool bIsBigIcon);
bool lamexp_sheet_of_glass(QWidget *window); bool lamexp_sheet_of_glass(QWidget *window);
bool lamexp_sheet_of_glass_update(QWidget *window); bool lamexp_sheet_of_glass_update(QWidget *window);
bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout = 30, const bool forceShutdown = true, const bool hibernate = false);
QColor lamexp_system_color(const int color_id); QColor lamexp_system_color(const int color_id);
const char *lamexp_support_url(void); const char *lamexp_support_url(void);
bool lamexp_themes_enabled(void); bool lamexp_themes_enabled(void);
@ -144,7 +127,6 @@ QString lamexp_translation_name(const QString &language);
bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country); bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country);
unsigned int lamexp_translation_sysid(const QString &langId); unsigned int lamexp_translation_sysid(const QString &langId);
bool lamexp_update_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text); bool lamexp_update_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text);
bool lamexp_user_is_admin(void);
const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText, const QString *tag = NULL); const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText, const QString *tag = NULL);
unsigned int lamexp_version_build(void); unsigned int lamexp_version_build(void);
unsigned int lamexp_version_confg(void); unsigned int lamexp_version_confg(void);

View File

@ -214,76 +214,6 @@ bool lamexp_themes_enabled(void)
return g_lamexp_themes_enabled.bThemesEnabled; return g_lamexp_themes_enabled.bThemesEnabled;
} }
/*
* Get number of free bytes on disk
*/
unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
{
ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
{
if(ok) *ok = true;
return freeBytesAvailable.QuadPart;
}
else
{
if(ok) *ok = false;
return 0;
}
}
/*
* Check if computer does support hibernation
*/
bool lamexp_is_hibernation_supported(void)
{
bool hibernationSupported = false;
SYSTEM_POWER_CAPABILITIES pwrCaps;
SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
if(GetPwrCapabilities(&pwrCaps))
{
hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
}
return hibernationSupported;
}
/*
* Shutdown the computer
*/
bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
{
HANDLE hToken = NULL;
if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
TOKEN_PRIVILEGES privileges;
memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
privileges.PrivilegeCount = 1;
privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
{
if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
{
if(hibernate)
{
if(SetSuspendState(TRUE, TRUE, TRUE))
{
return true;
}
}
const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
}
}
}
return false;
}
/* /*
* Block window "move" message * Block window "move" message
*/ */
@ -304,14 +234,6 @@ bool lamexp_block_window_move(void *message)
return false; return false;
} }
/*
* Suspend calling thread for N milliseconds
*/
inline void lamexp_sleep(const unsigned int delay)
{
Sleep(delay);
}
bool lamexp_beep(int beepType) bool lamexp_beep(int beepType)
{ {
switch(beepType) switch(beepType)
@ -409,48 +331,6 @@ bool lamexp_play_sound_file(const QString &library, const unsigned short uiSound
return result; return result;
} }
/*
* Open file using the shell
*/
bool lamexp_exec_shell(const QWidget *win, const QString &url, const bool explore)
{
return lamexp_exec_shell(win, url, QString(), QString(), explore);
}
/*
* Open file using the shell (with parameters)
*/
bool lamexp_exec_shell(const QWidget *win, const QString &url, const QString &parameters, const QString &directory, const bool explore)
{
return ((int) ShellExecuteW(((win) ? win->winId() : NULL), (explore ? L"explore" : L"open"), MUTILS_WCHR(url), ((!parameters.isEmpty()) ? MUTILS_WCHR(parameters) : NULL), ((!directory.isEmpty()) ? MUTILS_WCHR(directory) : NULL), SW_SHOW)) > 32;
}
/*
* Query value of the performance counter
*/
__int64 lamexp_perfcounter_value(void)
{
LARGE_INTEGER counter;
if(QueryPerformanceCounter(&counter) == TRUE)
{
return counter.QuadPart;
}
return -1;
}
/*
* Query frequency of the performance counter
*/
__int64 lamexp_perfcounter_frequ(void)
{
LARGE_INTEGER frequency;
if(QueryPerformanceFrequency(&frequency) == TRUE)
{
return frequency.QuadPart;
}
return -1;
}
/* /*
* Insert entry to the window's system menu * Insert entry to the window's system menu
*/ */
@ -512,79 +392,6 @@ bool lamexp_check_escape_state(void)
return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0; return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
} }
/*
* Set the process priority class for current process
*/
bool lamexp_change_process_priority(const int priority)
{
return lamexp_change_process_priority(GetCurrentProcess(), priority);
}
/*
* Set the process priority class for specified process
*/
bool lamexp_change_process_priority(const QProcess *proc, const int priority)
{
if(Q_PID qPid = proc->pid())
{
return lamexp_change_process_priority(qPid->hProcess, priority);
}
else
{
return false;
}
}
/*
* Set the process priority class for specified process
*/
bool lamexp_change_process_priority(void *hProcess, const int priority)
{
bool ok = false;
switch(qBound(-2, priority, 2))
{
case 2:
ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
break;
case 1:
if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
{
ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
}
break;
case 0:
ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
break;
case -1:
if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
{
ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
}
break;
case -2:
ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
break;
}
return ok;
}
/*
* Returns the current file time
*/
unsigned __int64 lamexp_current_file_time(void)
{
FILETIME fileTime;
GetSystemTimeAsFileTime(&fileTime);
ULARGE_INTEGER temp;
temp.HighPart = fileTime.dwHighDateTime;
temp.LowPart = fileTime.dwLowDateTime;
return temp.QuadPart;
}
/* /*
* Bring the specifed window to the front * Bring the specifed window to the front
*/ */
@ -631,102 +438,6 @@ bool lamexp_bring_process_to_front(const unsigned long pid)
return EnumWindows(lamexp_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE; return EnumWindows(lamexp_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
} }
/*
* Retrun the process ID of the given QProcess
*/
unsigned long lamexp_process_id(const QProcess *proc)
{
PROCESS_INFORMATION *procInf = proc->pid();
return (procInf) ? procInf->dwProcessId : NULL;
}
/*
* Convert long path to short path
*/
QString lamexp_path_to_short(const QString &longPath)
{
QString shortPath;
DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
if(buffSize > 0)
{
wchar_t *buffer = new wchar_t[buffSize];
DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
if(result > 0 && result < buffSize)
{
shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
}
delete[] buffer;
}
return (shortPath.isEmpty() ? longPath : shortPath);
}
/*
* Open media file in external player
*/
bool lamexp_open_media_file(const QString &mediaFilePath)
{
const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
const static wchar_t *registryKeys[3] =
{
L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
L"foobar2000"
};
const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
for(size_t i = 0; i < 3; i++)
{
for(size_t j = 0; j < 2; j++)
{
QString mplayerPath;
HKEY registryKeyHandle = NULL;
const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
{
for(size_t k = 0; k < 2; k++)
{
wchar_t Buffer[4096];
DWORD BuffSize = sizeof(wchar_t*) * 4096;
DWORD DataType = REG_NONE;
if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
{
if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
{
mplayerPath = MUTILS_QSTR(Buffer);
break;
}
}
}
RegCloseKey(registryKeyHandle);
}
if(!mplayerPath.isEmpty())
{
QDir mplayerDir(mplayerPath);
if(mplayerDir.exists())
{
for(size_t k = 0; k < 4; k++)
{
if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
{
qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
return true;
}
}
}
}
}
}
return false;
}
static void lamexp_init_dwmapi(void) static void lamexp_init_dwmapi(void)
{ {
QReadLocker writeLock(&g_lamexp_dwmapi.lock); QReadLocker writeLock(&g_lamexp_dwmapi.lock);
@ -930,112 +641,6 @@ QColor lamexp_system_color(const int color_id)
return color; return color;
} }
/*
* Check if the current user is an administartor (helper function)
*/
static bool lamexp_user_is_admin_helper(void)
{
HANDLE hToken = NULL;
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
{
return false;
}
DWORD dwSize = 0;
if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
{
if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
{
CloseHandle(hToken);
return false;
}
}
PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
if(!lpGroups)
{
CloseHandle(hToken);
return false;
}
if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
{
free(lpGroups);
CloseHandle(hToken);
return false;
}
PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
{
free(lpGroups);
CloseHandle(hToken);
return false;
}
bool bResult = false;
for(DWORD i = 0; i < lpGroups->GroupCount; i++)
{
if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
{
bResult = true;
break;
}
}
FreeSid(lpSid);
free(lpGroups);
CloseHandle(hToken);
return bResult;
}
/*
* Check if the current user is an administartor
*/
bool lamexp_user_is_admin(void)
{
bool isAdmin = false;
//Check for process elevation and UAC support first!
if(MUtils::OS::is_elevated(&isAdmin))
{
qWarning("Process is elevated -> user is admin!");
return true;
}
//If not elevated and UAC is not available -> user must be in admin group!
if(!isAdmin)
{
qDebug("UAC is disabled/unavailable -> checking for Administrators group");
isAdmin = lamexp_user_is_admin_helper();
}
return isAdmin;
}
/*
* Check if file is a valid Win32/Win64 executable
*/
bool lamexp_is_executable(const QString &path)
{
bool bIsExecutable = false;
DWORD binaryType;
if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
{
bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
}
return bIsExecutable;
}
/*
* Fatal application exit - helper
*/
static DWORD WINAPI lamexp_fatal_exit_helper(LPVOID lpParameter)
{
MessageBoxA(NULL, ((LPCSTR) lpParameter), "LameXP - Guru Meditation", MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_TOPMOST | MB_SETFOREGROUND);
return 0;
}
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// INITIALIZATION // INITIALIZATION
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

View File

@ -219,7 +219,7 @@ static int lamexp_main(int &argc, char **argv)
//Shotdown computer //Shotdown computer
if(iShutdown > shutdownFlag_None) if(iShutdown > shutdownFlag_None)
{ {
if(!lamexp_shutdown_computer(QApplication::applicationFilePath(), 12, true, (iShutdown == shutdownFlag_Hibernate))) if(!MUtils::OS::shutdown_computer(QApplication::applicationFilePath(), 12, true, (iShutdown == shutdownFlag_Hibernate)))
{ {
QMessageBox messageBox(QMessageBox::Critical, "LameXP", "Sorry, LameXP was unable to shutdown your computer!", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint); QMessageBox messageBox(QMessageBox::Critical, "LameXP", "Sorry, LameXP was unable to shutdown your computer!", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
} }

View File

@ -425,7 +425,7 @@ void SettingsModel::validate(void)
if(this->hibernateComputer()) if(this->hibernateComputer())
{ {
if(!lamexp_is_hibernation_supported()) if(!MUtils::OS::is_hibernation_supported())
{ {
this->hibernateComputer(false); this->hibernateComputer(false);
} }

View File

@ -78,14 +78,13 @@ void DiskObserverThread::run(void)
void DiskObserverThread::observe(void) void DiskObserverThread::observe(void)
{ {
unsigned __int64 minimumSpace = MIN_DISKSPACE; quint64 minimumSpace = MIN_DISKSPACE;
unsigned __int64 freeSpace, previousSpace = 0ui64; quint64 previousSpace = quint64(-1);
bool ok = false;
forever forever
{ {
freeSpace = lamexp_free_diskspace(m_path, &ok); quint64 freeSpace = 0ui64;
if(ok) if(MUtils::OS::free_diskspace(m_path, freeSpace))
{ {
if(freeSpace < minimumSpace) if(freeSpace < minimumSpace)
{ {

View File

@ -319,7 +319,7 @@ double InitializationThread::doInit(const size_t threadCount)
LockedFile::selfTest(); LockedFile::selfTest();
ExtractorTask::clearFlags(); ExtractorTask::clearFlags();
const long long timeExtractStart = lamexp_perfcounter_value(); const long long timeExtractStart = MUtils::OS::perfcounter_read();
//Extract all files //Extract all files
while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty())) while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
@ -364,7 +364,7 @@ double InitializationThread::doInit(const size_t threadCount)
pool->waitForDone(); pool->waitForDone();
MUTILS_DELETE(pool); MUTILS_DELETE(pool);
const long long timeExtractEnd = lamexp_perfcounter_value(); const long long timeExtractEnd = MUtils::OS::perfcounter_read();
//Make sure all files were extracted correctly //Make sure all files were extracted correctly
if(ExtractorTask::getExcept()) if(ExtractorTask::getExcept())
@ -388,7 +388,7 @@ double InitializationThread::doInit(const size_t threadCount)
} }
//Check delay //Check delay
const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(lamexp_perfcounter_frequ()); const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(MUtils::OS::perfcounter_freq());
if(delayExtract > g_allowedExtractDelay) if(delayExtract > g_allowedExtractDelay)
{ {
m_slowIndicator = true; m_slowIndicator = true;
@ -555,7 +555,7 @@ void InitializationThread::initNeroAac(void)
for(int i = 0; i < 3; i++) for(int i = 0; i < 3; i++)
{ {
if(!lamexp_is_executable(neroFileInfo[i].canonicalFilePath())) if(!MUtils::OS::is_executable_file(neroFileInfo[i].canonicalFilePath()))
{ {
qDebug("%s executbale is invalid -> AAC encoding support will be disabled!\n", MUTILS_UTF8(neroFileInfo[i].fileName())); qDebug("%s executbale is invalid -> AAC encoding support will be disabled!\n", MUTILS_UTF8(neroFileInfo[i].fileName()));
return; return;
@ -667,7 +667,7 @@ void InitializationThread::initFhgAac(void)
return; return;
} }
if(!lamexp_is_executable(fhgFileInfo[0].canonicalFilePath())) if(!MUtils::OS::is_executable_file(fhgFileInfo[0].canonicalFilePath()))
{ {
qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n"); qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n");
return; return;
@ -774,7 +774,7 @@ void InitializationThread::initQAac(void)
return; return;
} }
if(!lamexp_is_executable(qaacFileInfo[0].canonicalFilePath())) if(!MUtils::OS::is_executable_file(qaacFileInfo[0].canonicalFilePath()))
{ {
qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n"); qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n");
return; return;

View File

@ -96,7 +96,7 @@ bool AbstractTool::startProcess(QProcess &process, const QString &program, const
{ {
QMutexLocker lock(&s_mutex_startProcess); QMutexLocker lock(&s_mutex_startProcess);
if(lamexp_current_file_time() <= s_lastLaunchTime) if(MUtils::OS::current_file_time() <= s_lastLaunchTime)
{ {
MUtils::OS::sleep_ms(START_DELAY); MUtils::OS::sleep_ms(START_DELAY);
} }
@ -116,7 +116,7 @@ bool AbstractTool::startProcess(QProcess &process, const QString &program, const
} }
} }
lamexp_change_process_priority(&process, -1); MUtils::OS::change_process_priority(&process, -1);
lock.unlock(); lock.unlock();
if(m_firstLaunch) if(m_firstLaunch)
@ -125,7 +125,7 @@ bool AbstractTool::startProcess(QProcess &process, const QString &program, const
m_firstLaunch = false; m_firstLaunch = false;
} }
s_lastLaunchTime = lamexp_current_file_time() + START_DELAY_NANO; s_lastLaunchTime = MUtils::OS::current_file_time() + START_DELAY_NANO;
return true; return true;
} }
@ -136,7 +136,7 @@ bool AbstractTool::startProcess(QProcess &process, const QString &program, const
process.kill(); process.kill();
process.waitForFinished(-1); process.waitForFinished(-1);
s_lastLaunchTime = lamexp_current_file_time() + START_DELAY_NANO; s_lastLaunchTime = MUtils::OS::current_file_time() + START_DELAY_NANO;
return false; return false;
} }