Improve speed of category tab title updates
[amule.git] / src / amuleAppCommon.cpp
blob4fdcc3990d458a67188a488710b26d32f0ee806b
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2009 aMule Team ( admin@amule.org / http://www.amule.org )
5 //
6 // Any parts of this program derived from the xMule, lMule or eMule project,
7 // or contributed by third-party developers are copyrighted by their
8 // respective authors.
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 // This file is for functions common to all three apps (amule, amuled, amulegui),
27 // but preprocessor-dependent (using theApp, thePrefs), so it is compiled seperately for each app.
31 #include <wx/wx.h>
32 #include <wx/cmdline.h> // Needed for wxCmdLineParser
33 #include <wx/snglinst.h> // Needed for wxSingleInstanceChecker
34 #include <wx/textfile.h> // Needed for wxTextFile
35 #include <wx/config.h> // Do_not_auto_remove (win32)
36 #include <wx/fileconf.h>
38 #include "amule.h" // Interface declarations.
39 #include <common/Format.h> // Needed for CFormat
40 #include "CFile.h" // Needed for CFile
41 #include "ED2KLink.h" // Needed for command line passing of links
42 #include "FileLock.h" // Needed for CFileLock
43 #include "GuiEvents.h" // Needed for Notify_*
44 #include "KnownFile.h"
45 #include "Logger.h"
46 #include "MagnetURI.h" // Needed for CMagnetURI
47 #include "Preferences.h"
48 #include "ScopedPtr.h"
50 #ifndef CLIENT_GUI
51 #include "DownloadQueue.h"
52 #endif
54 CamuleAppCommon::CamuleAppCommon()
56 m_singleInstance = NULL;
57 ec_config = false;
58 m_geometryEnabled = false;
59 if (IsRemoteGui()) {
60 m_appName = wxT("aMuleGUI");
61 m_configFile = wxT("remote.conf");
62 m_logFile = wxT("remotelogfile");
63 } else {
64 m_configFile = wxT("amule.conf");
65 m_logFile = wxT("logfile");
67 if (IsDaemon()) {
68 m_appName = wxT("aMuleD");
69 } else {
70 m_appName = wxT("aMule");
75 CamuleAppCommon::~CamuleAppCommon()
77 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
78 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
79 #else
80 delete m_singleInstance;
81 #endif
84 void CamuleAppCommon::RefreshSingleInstanceChecker()
86 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
87 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
88 #else
89 delete m_singleInstance;
90 m_singleInstance = new wxSingleInstanceChecker(wxT("muleLock"), ConfigDir);
91 #endif
94 void CamuleAppCommon::AddLinksFromFile()
96 const wxString fullPath = ConfigDir + wxT("ED2KLinks");
97 if (!wxFile::Exists(fullPath)) {
98 return;
101 // Attempt to lock the ED2KLinks file.
102 CFileLock lock((const char*)unicode2char(fullPath));
104 wxTextFile file(fullPath);
105 if ( file.Open() ) {
106 for ( unsigned int i = 0; i < file.GetLineCount(); i++ ) {
107 wxString line = file.GetLine( i ).Strip( wxString::both );
109 if ( !line.IsEmpty() ) {
110 // Special case! used by a secondary running mule to raise this one.
111 if (line == wxT("RAISE_DIALOG")) {
112 Notify_ShowGUI();
113 continue;
115 unsigned long category = 0;
116 if (line.AfterLast(wxT(':')).ToULong(&category) == true) {
117 line = line.BeforeLast(wxT(':'));
118 } else { // If ToULong returns false the category still can have been changed!
119 // This is fixed in wx 2.9
120 category = 0;
122 theApp->downloadqueue->AddLink(line, category);
126 file.Close();
127 } else {
128 AddLogLineNS(_("Failed to open ED2KLinks file."));
131 // Delete the file.
132 wxRemoveFile(theApp->ConfigDir + wxT("ED2KLinks"));
136 // Returns a magnet ed2k URI
137 wxString CamuleAppCommon::CreateMagnetLink(const CAbstractFile *f)
139 CMagnetURI uri;
141 uri.AddField(wxT("dn"), f->GetFileName().Cleanup(false).GetPrintable());
142 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2k:")) + f->GetFileHash().Encode().Lower());
143 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2khash:")) + f->GetFileHash().Encode().Lower());
144 uri.AddField(wxT("xl"), CFormat(wxT("%d")) % f->GetFileSize());
146 return uri.GetLink();
149 // Returns a ed2k file URL
150 wxString CamuleAppCommon::CreateED2kLink(const CAbstractFile *f, bool add_source, bool use_hostname, bool addcryptoptions)
152 wxASSERT(!(!add_source && (use_hostname || addcryptoptions)));
153 // Construct URL like this: ed2k://|file|<filename>|<size>|<hash>|/
154 wxString strURL = CFormat(wxT("ed2k://|file|%s|%i|%s|/"))
155 % f->GetFileName().Cleanup(false)
156 % f->GetFileSize() % f->GetFileHash().Encode();
158 if (add_source && theApp->IsConnected() && !theApp->IsFirewalled()) {
159 // Create the first part of the URL
160 strURL << wxT("|sources,");
161 if (use_hostname) {
162 strURL << thePrefs::GetYourHostname();
163 } else {
164 uint32 clientID = theApp->GetID();
165 strURL << (uint8) clientID << wxT(".") <<
166 (uint8)(clientID >> 8) << wxT(".") <<
167 (uint8)(clientID >> 16) << wxT(".") <<
168 (uint8)(clientID >> 24);
171 strURL << wxT(":") <<
172 thePrefs::GetPort();
174 if (addcryptoptions) {
175 const uint8 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
176 const uint8 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
177 const uint8 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
178 const uint8 byCryptOptions = (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0) | (uSupportsCryptLayer ? 0x80 : 0x00);
180 strURL << wxT(":") << byCryptOptions;
182 if (byCryptOptions & 0x80) {
183 strURL << wxT(":") << thePrefs::GetUserHash().Encode();
186 strURL << wxT("|/");
187 } else if (add_source) {
188 AddLogLineC(_("WARNING: You can't add yourself as a source for an eD2k link while having a lowid."));
191 // Result is "ed2k://|file|<filename>|<size>|<hash>|/|sources,[(<ip>|<hostname>):<port>[:cryptoptions[:hash]]]|/"
192 return strURL;
195 // Returns a ed2k link with AICH info if available
196 wxString CamuleAppCommon::CreateED2kAICHLink(const CKnownFile* f)
198 // Create the first part of the URL
199 wxString strURL = CreateED2kLink(f);
200 // Append the AICH info
201 if (f->HasProperAICHHashSet()) {
202 strURL.RemoveLast(); // remove trailing '/'
203 strURL << wxT("h=") << f->GetAICHMasterHash() << wxT("|/");
206 // Result is "ed2k://|file|<filename>|<size>|<hash>|h=<AICH master hash>|/"
207 return strURL;
210 bool CamuleAppCommon::InitCommon(int argc, wxChar ** argv)
212 theApp->SetAppName(wxT("aMule"));
213 wxString FullMuleVersion = GetFullMuleVersion();
214 wxString OSDescription = wxGetOsDescription();
215 strFullMuleVersion = strdup((const char *)unicode2char(FullMuleVersion));
216 strOSDescription = strdup((const char *)unicode2char(OSDescription));
217 OSType = OSDescription.BeforeFirst( wxT(' ') );
218 if ( OSType.IsEmpty() ) {
219 OSType = wxT("Unknown");
222 // Parse cmdline arguments.
223 wxCmdLineParser cmdline(argc, argv);
225 // Handle these arguments.
226 cmdline.AddSwitch(wxT("v"), wxT("version"), wxT("Displays the current version number."));
227 cmdline.AddSwitch(wxT("h"), wxT("help"), wxT("Displays this information."));
228 cmdline.AddOption(wxT("c"), wxT("config-dir"), wxT("read config from <dir> instead of home"));
229 #ifdef AMULE_DAEMON
230 cmdline.AddSwitch(wxT("f"), wxT("full-daemon"), wxT("Fork to background."));
231 cmdline.AddOption(wxT("p"), wxT("pid-file"), wxT("After fork, create a pid-file in the given fullname file."));
232 cmdline.AddSwitch(wxT("e"), wxT("ec-config"), wxT("Configure EC (External Connections)."));
233 #else
235 #ifdef __WXMSW__
236 // MSW shows help otions in a dialog box, and the formatting doesn't fit there
237 #define HELPTAB wxT("\t")
238 #else
239 #define HELPTAB wxT("\t\t\t")
240 #endif
242 cmdline.AddOption(wxT("geometry"), wxEmptyString,
243 wxT("Sets the geometry of the app.\n")
244 HELPTAB wxT("<str> uses the same format as standard X11 apps:\n")
245 HELPTAB wxT("[=][<width>{xX}<height>][{+-}<xoffset>{+-}<yoffset>]"));
246 #endif // !AMULE_DAEMON
248 cmdline.AddSwitch(wxT("o"), wxT("log-stdout"), wxT("Print log messages to stdout."));
249 cmdline.AddSwitch(wxT("r"), wxT("reset-config"), wxT("Resets config to default values."));
251 #ifdef CLIENT_GUI
252 cmdline.AddSwitch(wxT("s"), wxT("skip"), wxT("Skip connection dialog."));
253 #else
254 // Change webserver path. This is also a config option, so this switch will go at some time.
255 cmdline.AddOption(wxT("w"), wxT("use-amuleweb"), wxT("Specify location of amuleweb binary."));
256 #endif
257 #ifndef __WXMSW__
258 cmdline.AddSwitch(wxT("d"), wxT("disable-fatal"), wxT("Do not handle fatal exception."));
259 // Keep stdin open to run valgrind --gen_suppressions
260 cmdline.AddSwitch(wxT("i"), wxT("enable-stdin"), wxT("Do not disable stdin."));
261 #endif
263 // Allow passing of links to the app
264 cmdline.AddOption(wxT("t"), wxT("category"), wxT("Set category for passed ED2K links."), wxCMD_LINE_VAL_NUMBER);
265 cmdline.AddParam(wxT("ED2K link"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
267 // wx asserts in debug mode if there is a check for an option that wasn't added.
268 // So we have to wrap around the same #ifdefs as above. >:(
270 // Show help on --help or invalid commands
271 if ( cmdline.Parse() ) {
272 return false;
273 } else if (cmdline.Found(wxT("help"))) {
274 cmdline.Usage();
275 return false;
278 if ( cmdline.Found(wxT("version"))) {
279 // This looks silly with logging macros that add a timestamp.
280 printf("%s\n", (const char*)unicode2char(wxString(CFormat(wxT("%s (OS: %s)")) % FullMuleVersion % OSType)));
281 return false;
284 if ( cmdline.Found(wxT("config-dir"), &ConfigDir) ) {
285 // Make an absolute path from the config dir
286 wxFileName fn(ConfigDir);
287 fn.MakeAbsolute();
288 ConfigDir = fn.GetFullPath();
289 if (ConfigDir.Last() != wxFileName::GetPathSeparator()) {
290 ConfigDir += wxFileName::GetPathSeparator();
292 } else {
293 ConfigDir = GetConfigDir();
296 #ifndef __WXMSW__
297 #if wxUSE_ON_FATAL_EXCEPTION
298 if ( !cmdline.Found(wxT("disable-fatal")) ) {
299 // catch fatal exceptions
300 wxHandleFatalExceptions(true);
302 #endif
303 #endif
305 theLogger.SetEnabledStdoutLog(cmdline.Found(wxT("log-stdout")));
306 #ifdef AMULE_DAEMON
307 enable_daemon_fork = cmdline.Found(wxT("full-daemon"));
308 if ( cmdline.Found(wxT("pid-file"), &m_PidFile) ) {
309 // Remove any existing PidFile
310 if ( wxFileExists (m_PidFile) ) wxRemoveFile (m_PidFile);
312 ec_config = cmdline.Found(wxT("ec-config"));
313 #else
314 enable_daemon_fork = false;
316 // Default geometry of the GUI. Can be changed with a cmdline argument...
317 if ( cmdline.Found(wxT("geometry"), &m_geometryString) ) {
318 m_geometryEnabled = true;
320 #endif
322 if (theLogger.IsEnabledStdoutLog()) {
323 if ( enable_daemon_fork ) {
324 AddLogLineNS(wxT("Daemon will fork to background - log to stdout disabled"));
325 theLogger.SetEnabledStdoutLog(false);
326 } else {
327 AddLogLineNS(wxT("Logging to stdout enabled"));
331 AddLogLineNS(wxT("Initialising ") + FullMuleVersion);
333 // Ensure that "~/.aMule/" is accessible.
334 CPath outDir;
335 if (!CheckMuleDirectory(wxT("configuration"), CPath(ConfigDir), wxEmptyString, outDir)) {
336 return false;
339 if (cmdline.Found(wxT("reset-config"))) {
340 // Make a backup first.
341 wxRemoveFile(ConfigDir + m_configFile + wxT(".backup"));
342 wxRenameFile(ConfigDir + m_configFile, ConfigDir + m_configFile + wxT(".backup"));
343 AddLogLineNS(CFormat(wxT("Your settings have been reset to default values.\nThe old config file has been saved as %s.backup\n")) % m_configFile);
346 size_t linksPassed = cmdline.GetParamCount(); // number of links from the command line
347 int linksActuallyPassed = 0; // number of links that pass the syntax check
348 if (linksPassed) {
349 long cat = 0;
350 if (!cmdline.Found(wxT("t"), &cat)) {
351 cat = 0;
354 wxTextFile ed2kFile(ConfigDir + wxT("ED2KLinks"));
355 if (!ed2kFile.Exists()) {
356 ed2kFile.Create();
358 if (ed2kFile.Open()) {
359 for (size_t i = 0; i < linksPassed; i++) {
360 wxString link;
361 if (CheckPassedLink(cmdline.GetParam(i), link, cat)) {
362 ed2kFile.AddLine(link);
363 linksActuallyPassed++;
366 ed2kFile.Write();
367 } else {
368 AddLogLineCS(wxT("Failed to open 'ED2KLinks', cannot add links."));
372 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
373 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
374 AddLogLineCS(wxT("WARNING: The check for other instances is currently disabled in amuled.\n"
375 "Please make sure that no other instance of aMule is running or your files might be corrupted.\n"));
376 #else
377 AddLogLineNS(wxT("Checking if there is an instance already running..."));
379 m_singleInstance = new wxSingleInstanceChecker();
380 wxString lockfile = IsRemoteGui() ? wxT("muleLockRGUI") : wxT("muleLock");
381 if (m_singleInstance->Create(lockfile, ConfigDir)
382 && m_singleInstance->IsAnotherRunning()) {
383 AddLogLineCS(CFormat(wxT("There is an instance of %s already running")) % m_appName);
384 AddLogLineNS(CFormat(wxT("(lock file: %s%s)")) % ConfigDir % lockfile);
385 if (linksPassed) {
386 AddLogLineNS(CFormat(wxT("passed %d %s to it, finished")) % linksActuallyPassed
387 % (linksPassed == 1 ? wxT("link") : wxT("links")));
388 return false;
391 // This is very tricky. The most secure way to communicate is via ED2K links file
392 wxTextFile ed2kFile(ConfigDir + wxT("ED2KLinks"));
393 if (!ed2kFile.Exists()) {
394 ed2kFile.Create();
397 if (ed2kFile.Open()) {
398 ed2kFile.AddLine(wxT("RAISE_DIALOG"));
399 ed2kFile.Write();
401 AddLogLineNS(wxT("Raising current running instance."));
402 } else {
403 AddLogLineCS(wxT("Failed to open 'ED2KFile', cannot signal running instance."));
406 return false;
407 } else {
408 AddLogLineNS(wxT("No other instances are running."));
410 #endif
412 #ifndef __WXMSW__
413 // Close standard-input
414 if ( !cmdline.Found(wxT("enable-stdin")) ) {
415 // The full daemon will close all std file-descriptors by itself,
416 // so closing it here would lead to the closing on the first open
417 // file, which is the logfile opened below
418 if (!enable_daemon_fork) {
419 close(0);
422 #endif
424 // Create the CFG file we shall use and set the config object as the global cfg file
425 wxConfig::Set(new wxFileConfig( wxEmptyString, wxEmptyString, ConfigDir + m_configFile));
427 // Make a backup of the log file
428 CPath logfileName = CPath(ConfigDir + m_logFile);
429 if (logfileName.FileExists()) {
430 CPath::BackupFile(logfileName, wxT(".bak"));
433 // Open the log file
434 if (!theLogger.OpenLogfile(logfileName.GetRaw())) {
435 // use std err as last resolt to indicate problem
436 fputs("ERROR: unable to open log file\n", stderr);
437 // failure to open log is serious problem
438 return false;
441 // Load Preferences
442 CPreferences::BuildItemList(ConfigDir);
443 CPreferences::LoadAllItems( wxConfigBase::Get() );
445 #ifdef CLIENT_GUI
446 m_skipConnectionDialog = cmdline.Found(wxT("skip"));
447 #else
448 wxString amulewebPath;
449 if (cmdline.Found(wxT("use-amuleweb"), &amulewebPath)) {
450 thePrefs::SetWSPath(amulewebPath);
451 AddLogLineNS(CFormat(wxT("Using amuleweb in '%s'.")) % amulewebPath);
453 #endif
455 return true;
459 * Returns a description of the version of aMule being used.
461 * @return A detailed description of the aMule version, including application
462 * name and wx information.
464 const wxString CamuleAppCommon::GetFullMuleVersion() const
466 return GetMuleAppName() + wxT(" ") + GetMuleVersion();
469 bool CamuleAppCommon::CheckPassedLink(const wxString &in, wxString &out, int cat)
471 wxString link(in);
473 // restore ASCII-encoded pipes
474 link.Replace(wxT("%7C"), wxT("|"));
475 link.Replace(wxT("%7c"), wxT("|"));
477 if (link.compare(0, 7, wxT("magnet:")) == 0) {
478 link = CMagnetED2KConverter(link);
479 if (link.empty()) {
480 AddLogLineCS(CFormat(wxT("Cannot convert magnet link to eD2k: %s")) % in);
481 return false;
485 try {
486 CScopedPtr<CED2KLink> uri(CED2KLink::CreateLinkFromUrl(link));
487 out = uri.get()->GetLink();
488 if (cat && uri.get()->GetKind() == CED2KLink::kFile) {
489 out += CFormat(wxT(":%d")) % cat;
491 return true;
492 } catch ( const wxString& err ) {
493 AddLogLineCS(CFormat(wxT("Invalid eD2k link \"%s\" - ERROR: %s")) % link % err);
495 return false;
500 * Checks permissions on a aMule directory, creating if needed.
502 * @param desc A description of the directory in question, used for error messages.
503 * @param directory The directory in question.
504 * @param alternative If the dir specified with 'directory' could not be created, try this instead.
505 * @param outDir Returns the used path.
506 * @return False on error.
508 bool CamuleAppCommon::CheckMuleDirectory(const wxString& desc, const CPath& directory, const wxString& alternative, CPath& outDir)
510 wxString msg;
512 if (directory.IsDir(CPath::readwritable)) {
513 outDir = directory;
514 return true;
515 } else if (directory.DirExists()) {
516 // Strings are not translated here because translation isn't up yet.
517 msg = CFormat(wxT("Permissions on the %s directory too strict!\n")
518 wxT("aMule cannot proceed. To fix this, you must set read/write/exec\n")
519 wxT("permissions for the folder '%s'"))
520 % desc % directory;
521 } else if (CPath::MakeDir(directory)) {
522 outDir = directory;
523 return true;
524 } else {
525 msg << CFormat(wxT("Could not create the %s directory at '%s'."))
526 % desc % directory;
529 // Attempt to use fallback directory.
530 const CPath fallback(alternative);
531 if (fallback.IsOk() && (directory != fallback)) {
532 msg << wxT("\nAttempting to use default directory at location \n'")
533 << alternative << wxT("'.");
534 if (theApp->ShowAlert(msg, wxT("Error accessing directory."), wxICON_ERROR | wxOK | wxCANCEL) == wxCANCEL) {
535 outDir = CPath(wxEmptyString);
536 return false;
539 return CheckMuleDirectory(desc, fallback, wxEmptyString, outDir);
542 theApp->ShowAlert(msg, wxT("Fatal error."), wxICON_ERROR | wxOK);
543 outDir = CPath(wxEmptyString);
544 return false;