Updated SoX binary to v14.4.2-Git (2014-10-06), compiled with ICL 15.0 and MSVC 12.0.
[LameXP.git] / src / Global_Utils.cpp
blobebb833849f69a4a3c7d4e3f8fc26c42ef7aaf525
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Global.h"
25 //Qt includes
26 #include <QApplication>
27 #include <QDate>
28 #include <QDir>
29 #include <QFileInfo>
30 #include <QIcon>
31 #include <QMutex>
32 #include <QProcessEnvironment>
33 #include <QReadWriteLock>
34 #include <QTextCodec>
35 #include <QUuid>
36 #include <QWidget>
38 //Natural sort
39 #include "strnatcmp.h"
41 //CRT includes
42 #include <time.h>
43 #include <process.h>
45 ///////////////////////////////////////////////////////////////////////////////
46 // GLOBAL VARS
47 ///////////////////////////////////////////////////////////////////////////////
49 //%TEMP% folder
50 static struct
52 QString *path;
53 QReadWriteLock lock;
55 g_lamexp_temp_folder;
57 static struct
59 QIcon *appIcon;
60 QReadWriteLock lock;
62 g_lamexp_app_icon;
64 ///////////////////////////////////////////////////////////////////////////////
65 // GLOBAL FUNCTIONS
66 ///////////////////////////////////////////////////////////////////////////////
69 * Get a random string
71 QString lamexp_rand_str(const bool bLong)
73 const QUuid uuid = QUuid::createUuid().toString();
75 const unsigned int u1 = uuid.data1;
76 const unsigned int u2 = (((unsigned int)(uuid.data2)) << 16) | ((unsigned int)(uuid.data3));
77 const unsigned int u3 = (((unsigned int)(uuid.data4[0])) << 24) | (((unsigned int)(uuid.data4[1])) << 16) | (((unsigned int)(uuid.data4[2])) << 8) | ((unsigned int)(uuid.data4[3]));
78 const unsigned int u4 = (((unsigned int)(uuid.data4[4])) << 24) | (((unsigned int)(uuid.data4[5])) << 16) | (((unsigned int)(uuid.data4[6])) << 8) | ((unsigned int)(uuid.data4[7]));
80 return bLong ? QString().sprintf("%08x%08x%08x%08x", u1, u2, u3, u4) : QString().sprintf("%08x%08x", (u1 ^ u2), (u3 ^ u4));
84 * Try to initialize the folder (with *write* access)
86 static QString lamexp_try_init_folder(const QString &folderPath)
88 static const char *TEST_DATA = "Lorem ipsum dolor sit amet, consectetur, adipisci velit!";
90 bool success = false;
92 const QFileInfo folderInfo(folderPath);
93 const QDir folderDir(folderInfo.absoluteFilePath());
95 //Create folder, if it does *not* exist yet
96 for(int i = 0; (i < 16) && (!folderDir.exists()); i++)
98 folderDir.mkpath(".");
101 //Make sure folder exists now *and* is writable
102 if(folderDir.exists())
104 const QByteArray testData = QByteArray(TEST_DATA);
105 for(int i = 0; (i < 32) && (!success); i++)
107 QFile testFile(folderDir.absoluteFilePath(QString("~%1.tmp").arg(lamexp_rand_str())));
108 if(testFile.open(QIODevice::ReadWrite | QIODevice::Truncate))
110 if(testFile.write(testData) >= testData.size())
112 success = true;
114 testFile.remove();
119 return (success ? folderDir.canonicalPath() : QString());
123 * Initialize LameXP temp folder
125 #define INIT_TEMP_FOLDER_RAND(OUT_PTR, BASE_DIR) do \
127 for(int _i = 0; _i < 128; _i++) \
129 const QString _randDir = QString("%1/%2").arg((BASE_DIR), lamexp_rand_str()); \
130 if(!QDir(_randDir).exists()) \
132 *(OUT_PTR) = lamexp_try_init_folder(_randDir); \
133 if(!(OUT_PTR)->isEmpty()) break; \
137 while(0)
140 * Get LameXP temp folder
142 const QString &lamexp_temp_folder2(void)
144 QReadLocker readLock(&g_lamexp_temp_folder.lock);
146 //Already initialized?
147 if(g_lamexp_temp_folder.path && (!g_lamexp_temp_folder.path->isEmpty()))
149 if(QDir(*g_lamexp_temp_folder.path).exists())
151 return *g_lamexp_temp_folder.path;
155 //Obtain the write lock to initilaize
156 readLock.unlock();
157 QWriteLocker writeLock(&g_lamexp_temp_folder.lock);
159 //Still uninitilaized?
160 if(g_lamexp_temp_folder.path && (!g_lamexp_temp_folder.path->isEmpty()))
162 if(QDir(*g_lamexp_temp_folder.path).exists())
164 return *g_lamexp_temp_folder.path;
168 //Create the string, if not done yet
169 if(!g_lamexp_temp_folder.path)
171 g_lamexp_temp_folder.path = new QString();
174 g_lamexp_temp_folder.path->clear();
176 //Try the %TMP% or %TEMP% directory first
177 QString tempPath = lamexp_try_init_folder(QDir::temp().absolutePath());
178 if(!tempPath.isEmpty())
180 INIT_TEMP_FOLDER_RAND(g_lamexp_temp_folder.path, tempPath);
183 //Otherwise create TEMP folder in %LOCALAPPDATA% or %SYSTEMROOT%
184 if(g_lamexp_temp_folder.path->isEmpty())
186 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
187 static const lamexp_known_folder_t folderId[2] = { lamexp_folder_localappdata, lamexp_folder_systroot_dir };
188 for(size_t id = 0; (g_lamexp_temp_folder.path->isEmpty() && (id < 2)); id++)
190 const QString &knownFolder = lamexp_known_folder(folderId[id]);
191 if(!knownFolder.isEmpty())
193 tempPath = lamexp_try_init_folder(QString("%1/Temp").arg(knownFolder));
194 if(!tempPath.isEmpty())
196 INIT_TEMP_FOLDER_RAND(g_lamexp_temp_folder.path, tempPath);
202 //Failed to create TEMP folder?
203 if(g_lamexp_temp_folder.path->isEmpty())
205 qFatal("Temporary directory could not be initialized !!!");
208 return *g_lamexp_temp_folder.path;
212 * Setup QPorcess object
214 void lamexp_init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
216 //Environment variable names
217 static const char *const s_envvar_names_temp[] =
219 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
221 static const char *const s_envvar_names_remove[] =
223 "WGETRC", "SYSTEM_WGETRC", "HTTP_PROXY", "FTP_PROXY", "NO_PROXY", "GNUPGHOME", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LANG", NULL
226 //Initialize environment
227 QProcessEnvironment env = process.processEnvironment();
228 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
230 //Clean a number of enviroment variables that might affect our tools
231 for(size_t i = 0; s_envvar_names_remove[i]; i++)
233 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
234 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
237 const QString tempDir = QDir::toNativeSeparators(lamexp_temp_folder2());
239 //Replace TEMP directory in environment
240 if(bReplaceTempDir)
242 for(size_t i = 0; s_envvar_names_temp[i]; i++)
244 env.insert(s_envvar_names_temp[i], tempDir);
248 //Setup PATH variable
249 const QString path = env.value("PATH", QString()).trimmed();
250 env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
252 //Setup QPorcess object
253 process.setWorkingDirectory(wokringDir);
254 process.setProcessChannelMode(QProcess::MergedChannels);
255 process.setReadChannel(QProcess::StandardOutput);
256 process.setProcessEnvironment(env);
260 * Natural Order String Comparison - the 'lessThan' helper function
262 static bool lamexp_natural_string_sort_helper(const QString &str1, const QString &str2)
264 return (strnatcmp(QWCHAR(str1), QWCHAR(str2)) < 0);
268 * Natural Order String Comparison - the 'lessThan' helper function *with* case folding
270 static bool lamexp_natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
272 return (strnatcasecmp(QWCHAR(str1), QWCHAR(str2)) < 0);
276 * Natural Order String Comparison - the main sorting function
278 void lamexp_natural_string_sort(QStringList &list, const bool bIgnoreCase)
280 qSort(list.begin(), list.end(), bIgnoreCase ? lamexp_natural_string_sort_helper_fold_case : lamexp_natural_string_sort_helper);
284 * Remove forbidden characters from a filename
286 const QString lamexp_clean_filename(const QString &str)
288 QString newStr(str);
289 QRegExp rx("\"(.+)\"");
290 rx.setMinimal(true);
292 newStr.replace("\\", "-");
293 newStr.replace(" / ", ", ");
294 newStr.replace("/", ",");
295 newStr.replace(":", "-");
296 newStr.replace("*", "x");
297 newStr.replace("?", "");
298 newStr.replace("<", "[");
299 newStr.replace(">", "]");
300 newStr.replace("|", "!");
301 newStr.replace(rx, "`\\1´");
302 newStr.replace("\"", "'");
304 return newStr.simplified();
308 * Remove forbidden characters from a file path
310 const QString lamexp_clean_filepath(const QString &str)
312 QStringList parts = QString(str).replace("\\", "/").split("/");
314 for(int i = 0; i < parts.count(); i++)
316 parts[i] = lamexp_clean_filename(parts[i]);
319 return parts.join("/");
323 * Get a list of all available Qt Text Codecs
325 QStringList lamexp_available_codepages(bool noAliases)
327 QStringList codecList;
329 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
330 while(!availableCodecs.isEmpty())
332 QByteArray current = availableCodecs.takeFirst();
333 if(!(current.startsWith("system") || current.startsWith("System")))
335 codecList << QString::fromLatin1(current.constData(), current.size());
336 if(noAliases)
338 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
341 QList<QByteArray> aliases = currentCodec->aliases();
342 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
348 return codecList;
352 * Robert Jenkins' 96 bit Mix Function
353 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
355 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
357 unsigned int a = x;
358 unsigned int b = y;
359 unsigned int c = z;
361 a=a-b; a=a-c; a=a^(c >> 13);
362 b=b-c; b=b-a; b=b^(a << 8);
363 c=c-a; c=c-b; c=c^(b >> 13);
364 a=a-b; a=a-c; a=a^(c >> 12);
365 b=b-c; b=b-a; b=b^(a << 16);
366 c=c-a; c=c-b; c=c^(b >> 5);
367 a=a-b; a=a-c; a=a^(c >> 3);
368 b=b-c; b=b-a; b=b^(a << 10);
369 c=c-a; c=c-b; c=c^(b >> 15);
371 return c;
375 * Seeds the random number generator
376 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
378 void lamexp_seed_rand(void)
380 qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
384 * Returns a randum number
385 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
387 unsigned int lamexp_rand(void)
389 quint32 rnd = 0;
391 if(rand_s(&rnd) == 0)
393 return rnd;
396 for(size_t i = 0; i < sizeof(unsigned int); i++)
398 rnd = (rnd << 8) ^ qrand();
401 return rnd;
405 * Make a window blink (to draw user's attention)
407 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
409 static QMutex blinkMutex;
411 const double maxOpac = 1.0;
412 const double minOpac = 0.3;
413 const double delOpac = 0.1;
415 if(!blinkMutex.tryLock())
417 qWarning("Blinking is already in progress, skipping!");
418 return;
423 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
424 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
425 const double opacity = poWindow->windowOpacity();
427 for(unsigned int i = 0; i < count; i++)
429 for(double x = maxOpac; x >= minOpac; x -= delOpac)
431 poWindow->setWindowOpacity(x);
432 QApplication::processEvents();
433 lamexp_sleep(sleep);
436 for(double x = minOpac; x <= maxOpac; x += delOpac)
438 poWindow->setWindowOpacity(x);
439 QApplication::processEvents();
440 lamexp_sleep(sleep);
444 poWindow->setWindowOpacity(opacity);
445 QApplication::processEvents();
446 blinkMutex.unlock();
448 catch(...)
450 blinkMutex.unlock();
451 qWarning("Exception error while blinking!");
456 * Clean folder
458 bool lamexp_clean_folder(const QString &folderPath)
460 QDir tempFolder(folderPath);
461 if(tempFolder.exists())
463 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
465 for(int i = 0; i < entryList.count(); i++)
467 if(entryList.at(i).isDir())
469 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
471 else
473 for(int j = 0; j < 3; j++)
475 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
477 break;
482 return tempFolder.rmdir(".");
484 return true;
488 * Computus according to H. Lichtenberg
490 static bool lamexp_computus(const QDate &date)
492 int X = date.year();
493 int A = X % 19;
494 int K = X / 100;
495 int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
496 int D = (19*A + M) % 30;
497 int S = 2 - (3*K + 3) / 4;
498 int R = D / 29 + (D / 28 - D / 29) * (A / 11);
499 int OG = 21 + D - R;
500 int SZ = 7 - (X + X / 4 + S) % 7;
501 int OE = 7 - (OG - SZ) % 7;
502 int OS = (OG + OE);
504 if(OS > 31)
506 return (date.month() == 4) && (date.day() == (OS - 31));
508 else
510 return (date.month() == 3) && (date.day() == OS);
515 * Check for Thanksgiving
517 static bool lamexp_thanksgiving(const QDate &date)
519 int day = 0;
521 switch(QDate(date.year(), 11, 1).dayOfWeek())
523 case 1: day = 25; break;
524 case 2: day = 24; break;
525 case 3: day = 23; break;
526 case 4: day = 22; break;
527 case 5: day = 28; break;
528 case 6: day = 27; break;
529 case 7: day = 26; break;
532 return (date.month() == 11) && (date.day() == day);
536 * Initialize app icon
538 const QIcon &lamexp_app_icon(void)
540 QReadLocker readLock(&g_lamexp_app_icon.lock);
542 //Already initialized?
543 if(g_lamexp_app_icon.appIcon)
545 return *g_lamexp_app_icon.appIcon;
548 readLock.unlock();
549 QWriteLocker writeLock(&g_lamexp_app_icon.lock);
551 while(!g_lamexp_app_icon.appIcon)
553 QDate currentDate = QDate::currentDate();
554 QTime currentTime = QTime::currentTime();
556 if(lamexp_thanksgiving(currentDate))
558 g_lamexp_app_icon.appIcon = new QIcon(":/MainIcon6.png");
560 else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1) && (currentTime.hour() <= 19)))
562 g_lamexp_app_icon.appIcon = new QIcon(":/MainIcon5.png");
564 else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1) && (currentTime.hour() <= 11)))
566 g_lamexp_app_icon.appIcon = new QIcon(":/MainIcon4.png");
568 else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
570 g_lamexp_app_icon.appIcon = new QIcon(":/MainIcon3.png");
572 else if(lamexp_computus(currentDate))
574 g_lamexp_app_icon.appIcon = new QIcon(":/MainIcon2.png");
576 else
578 g_lamexp_app_icon.appIcon = new QIcon(":/MainIcon1.png");
582 return *g_lamexp_app_icon.appIcon;
586 * Broadcast event to all windows
588 bool lamexp_broadcast(int eventType, bool onlyToVisible)
590 if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
592 qDebug("Broadcasting %d", eventType);
594 bool allOk = true;
595 QEvent poEvent(static_cast<QEvent::Type>(eventType));
596 QWidgetList list = app->topLevelWidgets();
598 while(!list.isEmpty())
600 QWidget *widget = list.takeFirst();
601 if(!onlyToVisible || widget->isVisible())
603 if(!app->sendEvent(widget, &poEvent))
605 allOk = false;
610 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
611 return allOk;
613 else
615 qWarning("Broadcast failed, could not get QApplication instance!");
616 return false;
620 ///////////////////////////////////////////////////////////////////////////////
621 // INITIALIZATION
622 ///////////////////////////////////////////////////////////////////////////////
624 extern "C" void _lamexp_global_init_utils(void)
626 LAMEXP_ZERO_MEMORY(g_lamexp_temp_folder);
627 LAMEXP_ZERO_MEMORY(g_lamexp_app_icon);
630 ///////////////////////////////////////////////////////////////////////////////
631 // FINALIZATION
632 ///////////////////////////////////////////////////////////////////////////////
634 extern "C" void _lamexp_global_free_utils(void)
636 //Delete temporary files
637 const QString &tempFolder = lamexp_temp_folder2();
638 if(!tempFolder.isEmpty())
640 bool success = false;
641 for(int i = 0; i < 100; i++)
643 if(lamexp_clean_folder(tempFolder))
645 success = true;
646 break;
648 lamexp_sleep(100);
650 if(!success)
652 lamexp_system_message(L"Sorry, LameXP was unable to clean up all temporary files. Some residual files in your TEMP directory may require manual deletion!", lamexp_beep_warning);
653 lamexp_exec_shell(NULL, tempFolder, QString(), QString(), true);
657 //Free memory
658 LAMEXP_DELETE(g_lamexp_temp_folder.path);
659 LAMEXP_DELETE(g_lamexp_app_icon.appIcon);