Fixed problem in the CFile write_safe concept
[amule.git] / src / Preferences.cpp
blobde2de00c004c82c1bfa66599ccfb25e79646f449
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2011 Merkur ( devs@emule-project.net / http://www.emule-project.net )
6 //
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
9 // respective authors.
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include <wx/wx.h>
27 #include "Preferences.h"
29 #include <protocol/ed2k/Constants.h>
30 #include <common/Constants.h>
31 #include <common/DataFileVersion.h>
33 #include <wx/config.h>
34 #include <wx/dir.h>
35 #include <wx/stdpaths.h>
36 #include <wx/stopwatch.h>
37 #include <wx/tokenzr.h>
38 #include <wx/utils.h> // Needed for wxBusyCursor
40 #include "amule.h"
41 #ifdef HAVE_CONFIG_H
42 #include "config.h" // Needed for PACKAGE_STRING
43 #endif
45 #include "CFile.h"
46 #include <common/MD5Sum.h>
47 #include "Logger.h"
48 #include <common/Format.h> // Needed for CFormat
49 #include <common/TextFile.h> // Needed for CTextFile
50 #include <common/ClientVersion.h>
52 #include "UserEvents.h"
54 #ifndef AMULE_DAEMON
55 #include <wx/valgen.h>
56 #include "muuli_wdr.h"
57 #include "StatisticsDlg.h"
58 #include "MuleColour.h"
59 #endif
61 #ifndef CLIENT_GUI
62 #include "RandomFunctions.h"
63 #include "PlatformSpecific.h" // Needed for PlatformSpecific::GetMaxConnections()
64 #include "SharedFileList.h" // Needed for theApp->sharedfiles->Reload()
65 #endif
67 // Needed for IP filtering prefs
68 #include "ClientList.h"
69 #include "ServerList.h"
70 #include "GuiEvents.h"
72 #define DEFAULT_TCP_PORT 4662
73 #define DEFAULT_UDP_PORT 4672
75 // Static variables
76 unsigned long CPreferences::s_colors[cntStatColors];
77 unsigned long CPreferences::s_colors_ref[cntStatColors];
79 CPreferences::CFGMap CPreferences::s_CfgList;
80 CPreferences::CFGList CPreferences::s_MiscList;
83 /* Proxy */
84 CProxyData CPreferences::s_ProxyData;
86 /* The rest, organize it! */
87 wxString CPreferences::s_nick;
88 Cfg_Lang_Base * CPreferences::s_cfgLang;
89 uint16 CPreferences::s_maxupload;
90 uint16 CPreferences::s_maxdownload;
91 uint16 CPreferences::s_slotallocation;
92 wxString CPreferences::s_Addr;
93 uint16 CPreferences::s_port;
94 uint16 CPreferences::s_udpport;
95 bool CPreferences::s_UDPEnable;
96 uint16 CPreferences::s_maxconnections;
97 bool CPreferences::s_reconnect;
98 bool CPreferences::s_autoconnect;
99 bool CPreferences::s_autoconnectstaticonly;
100 bool CPreferences::s_UPnPEnabled;
101 bool CPreferences::s_UPnPECEnabled;
102 bool CPreferences::s_UPnPWebServerEnabled;
103 uint16 CPreferences::s_UPnPTCPPort;
104 bool CPreferences::s_autoserverlist;
105 bool CPreferences::s_deadserver;
106 CPath CPreferences::s_incomingdir;
107 CPath CPreferences::s_tempdir;
108 bool CPreferences::s_ICH;
109 uint8 CPreferences::s_depth3D;
110 bool CPreferences::s_scorsystem;
111 bool CPreferences::s_mintotray;
112 bool CPreferences::s_trayiconenabled;
113 bool CPreferences::s_addnewfilespaused;
114 bool CPreferences::s_addserversfromserver;
115 bool CPreferences::s_addserversfromclient;
116 uint16 CPreferences::s_maxsourceperfile;
117 uint16 CPreferences::s_trafficOMeterInterval;
118 uint16 CPreferences::s_statsInterval;
119 uint32 CPreferences::s_maxGraphDownloadRate;
120 uint32 CPreferences::s_maxGraphUploadRate;
121 bool CPreferences::s_confirmExit;
122 bool CPreferences::s_filterLanIP;
123 bool CPreferences::s_paranoidfilter;
124 bool CPreferences::s_IPFilterSys;
125 bool CPreferences::s_onlineSig;
126 uint16 CPreferences::s_OSUpdate;
127 wxString CPreferences::s_languageID;
128 uint8 CPreferences::s_iSeeShares;
129 uint8 CPreferences::s_iToolDelayTime;
130 uint8 CPreferences::s_splitterbarPosition;
131 uint16 CPreferences::s_deadserverretries;
132 uint32 CPreferences::s_dwServerKeepAliveTimeoutMins;
133 uint8 CPreferences::s_statsMax;
134 uint8 CPreferences::s_statsAverageMinutes;
135 bool CPreferences::s_bpreviewprio;
136 bool CPreferences::s_smartidcheck;
137 uint8 CPreferences::s_smartidstate;
138 bool CPreferences::s_safeServerConnect;
139 bool CPreferences::s_startMinimized;
140 uint16 CPreferences::s_MaxConperFive;
141 bool CPreferences::s_checkDiskspace;
142 uint32 CPreferences::s_uMinFreeDiskSpace;
143 wxString CPreferences::s_yourHostname;
144 bool CPreferences::s_bVerbose;
145 bool CPreferences::s_bmanualhighprio;
146 bool CPreferences::s_bstartnextfile;
147 bool CPreferences::s_bstartnextfilesame;
148 bool CPreferences::s_bstartnextfilealpha;
149 bool CPreferences::s_bshowoverhead;
150 bool CPreferences::s_bDAP;
151 bool CPreferences::s_bUAP;
152 #ifndef __SVN__
153 bool CPreferences::s_showVersionOnTitle;
154 #endif
155 uint8_t CPreferences::s_showRatesOnTitle;
156 wxString CPreferences::s_VideoPlayer;
157 bool CPreferences::s_showAllNotCats;
158 bool CPreferences::s_msgonlyfriends;
159 bool CPreferences::s_msgsecure;
160 uint8 CPreferences::s_filterlevel;
161 uint8 CPreferences::s_iFileBufferSize;
162 uint8 CPreferences::s_iQueueSize;
163 wxString CPreferences::s_datetimeformat;
164 wxString CPreferences::s_sWebPath;
165 wxString CPreferences::s_sWebPassword;
166 wxString CPreferences::s_sWebLowPassword;
167 uint16 CPreferences::s_nWebPort;
168 uint16 CPreferences::s_nWebUPnPTCPPort;
169 bool CPreferences::s_bWebEnabled;
170 bool CPreferences::s_bWebUseGzip;
171 uint32 CPreferences::s_nWebPageRefresh;
172 bool CPreferences::s_bWebLowEnabled;
173 wxString CPreferences::s_WebTemplate;
174 bool CPreferences::s_showCatTabInfos;
175 AllCategoryFilter CPreferences::s_allcatFilter;
176 uint8 CPreferences::s_NoNeededSources;
177 bool CPreferences::s_DropFullQueueSources;
178 bool CPreferences::s_DropHighQueueRankingSources;
179 uint32 CPreferences::s_HighQueueRanking;
180 uint32 CPreferences::s_AutoDropTimer;
181 bool CPreferences::s_AcceptExternalConnections;
182 wxString CPreferences::s_ECAddr;
183 uint32 CPreferences::s_ECPort;
184 wxString CPreferences::s_ECPassword;
185 bool CPreferences::s_TransmitOnlyUploadingClients;
186 bool CPreferences::s_IPFilterClients;
187 bool CPreferences::s_IPFilterServers;
188 bool CPreferences::s_UseSrcSeeds;
189 bool CPreferences::s_ProgBar;
190 bool CPreferences::s_Percent;
191 bool CPreferences::s_SecIdent;
192 bool CPreferences::s_ExtractMetaData;
193 bool CPreferences::s_allocFullFile;
194 wxString CPreferences::s_CustomBrowser;
195 bool CPreferences::s_BrowserTab;
196 CPath CPreferences::s_OSDirectory;
197 wxString CPreferences::s_Skin;
198 bool CPreferences::s_FastED2KLinksHandler;
199 bool CPreferences::s_ToolbarOrientation;
200 bool CPreferences::s_AICHTrustEveryHash;
201 wxString CPreferences::s_CommentFilterString;
202 bool CPreferences::s_IPFilterAutoLoad;
203 wxString CPreferences::s_IPFilterURL;
204 CMD4Hash CPreferences::s_userhash;
205 bool CPreferences::s_MustFilterMessages;
206 wxString CPreferences::s_MessageFilterString;
207 bool CPreferences::s_FilterAllMessages;
208 bool CPreferences::s_FilterComments;
209 bool CPreferences::s_FilterSomeMessages;
210 bool CPreferences::s_ShowMessagesInLog;
211 bool CPreferences::s_IsAdvancedSpamfilterEnabled;
212 bool CPreferences::s_IsChatCaptchaEnabled;
213 bool CPreferences::s_ShareHiddenFiles;
214 bool CPreferences::s_AutoSortDownload;
215 bool CPreferences::s_NewVersionCheck;
216 bool CPreferences::s_ConnectToKad;
217 bool CPreferences::s_ConnectToED2K;
218 unsigned CPreferences::s_maxClientVersions;
219 bool CPreferences::s_DropSlowSources;
220 bool CPreferences::s_IsClientCryptLayerSupported;
221 bool CPreferences::s_bCryptLayerRequested;
222 bool CPreferences::s_IsClientCryptLayerRequired;
223 uint32 CPreferences::s_dwKadUDPKey;
224 uint8 CPreferences::s_byCryptTCPPaddingLength;
226 wxString CPreferences::s_Ed2kURL;
227 wxString CPreferences::s_KadURL;
228 bool CPreferences::s_GeoIPEnabled;
229 wxString CPreferences::s_GeoIPUpdateUrl;
230 bool CPreferences::s_preventSleepWhileDownloading;
231 wxString CPreferences::s_StatsServerName;
232 wxString CPreferences::s_StatsServerURL;
235 * Template Cfg class for connecting with widgets.
237 * This template provides the base functionionality needed to syncronize a
238 * variable with a widget. However, please note that wxGenericValidator only
239 * supports a few types (int, wxString, bool and wxArrayInt), so this template
240 * can't always be used directly.
242 * Cfg_Str and Cfg_Bool are able to use this template directly, whereas Cfg_Int
243 * makes use of serveral workaround to enable it to be used with integers other
244 * than int.
246 template <typename TYPE>
247 class Cfg_Tmpl : public Cfg_Base
249 public:
251 * Constructor.
253 * @param keyname
254 * @param value
255 * @param defaultVal
257 Cfg_Tmpl( const wxString& keyname, TYPE& value, const TYPE& defaultVal )
258 : Cfg_Base( keyname ),
259 m_value( value ),
260 m_default( defaultVal ),
261 m_widget( NULL )
264 #ifndef AMULE_DAEMON
266 * Connects the Cfg to a widget.
268 * @param id The ID of the widget to be connected.
269 * @param parent The parent of the widget. Use this to speed up searches.
271 * This function works by setting the wxValidator of the class. This however
272 * poses some restrictions on which variable types can be used for this
273 * template, as noted above. It also poses some limits on the widget types,
274 * refer to the wx documentation for those.
276 virtual bool ConnectToWidget( int id, wxWindow* parent = NULL )
278 if ( id ) {
279 m_widget = wxWindow::FindWindowById( id, parent );
281 if ( m_widget ) {
282 wxGenericValidator validator( &m_value );
284 m_widget->SetValidator( validator );
286 return true;
288 } else {
289 m_widget = NULL;
292 return false;
296 /** Updates the assosiated variable, returning true on success. */
297 virtual bool TransferFromWindow()
299 if ( m_widget ) {
300 wxValidator* validator = m_widget->GetValidator();
302 if ( validator ) {
303 TYPE temp = m_value;
305 if ( validator->TransferFromWindow() ) {
306 SetChanged( temp != m_value );
308 return true;
313 return false;
316 /** Updates the assosiated widget, returning true on success. */
317 virtual bool TransferToWindow()
319 if ( m_widget ) {
320 wxValidator* validator = m_widget->GetValidator();
322 if ( validator )
323 return validator->TransferToWindow();
326 return false;
329 #endif
331 /** Sets the default value. */
332 void SetDefault(const TYPE& defaultVal)
334 m_default = defaultVal;
337 protected:
338 //! Reference to the associated variable
339 TYPE& m_value;
341 //! Default variable value
342 TYPE m_default;
344 //! Pointer to the widget assigned to the Cfg instance
345 wxWindow* m_widget;
349 /** Cfg class for wxStrings. */
350 class Cfg_Str : public Cfg_Tmpl<wxString>
352 public:
353 /** Constructor. */
354 Cfg_Str( const wxString& keyname, wxString& value, const wxString& defaultVal = EmptyString )
355 : Cfg_Tmpl<wxString>( keyname, value, defaultVal )
358 /** Loads the string, using the specified default value. */
359 virtual void LoadFromFile(wxConfigBase* cfg)
361 cfg->Read( GetKey(), &m_value, m_default );
365 /** Saves the string to the specified wxConfig object. */
366 virtual void SaveToFile(wxConfigBase* cfg)
368 cfg->Write( GetKey(), m_value );
374 * Cfg-class for encrypting strings, for example for passwords.
376 class Cfg_Str_Encrypted : public Cfg_Str
378 public:
379 Cfg_Str_Encrypted( const wxString& keyname, wxString& value, const wxString& defaultVal = EmptyString )
380 : Cfg_Str( keyname, value, defaultVal )
383 #ifndef AMULE_DAEMON
384 virtual bool TransferFromWindow()
386 // Shakraw: when storing value, store it encrypted here (only if changed in prefs)
387 if ( Cfg_Str::TransferFromWindow() ) {
389 // Only recalucate the hash for new, non-empty passwords
390 if ( HasChanged() && !m_value.IsEmpty() ) {
391 m_value = MD5Sum( m_value ).GetHash();
394 return true;
398 return false;
400 #endif
404 /** Cfg class for CPath. */
405 class Cfg_Path : public Cfg_Str
407 public:
408 /** Constructor. */
409 Cfg_Path(const wxString& keyname, CPath& value, const wxString& defaultVal = EmptyString )
410 : Cfg_Str(keyname, m_temp_path, defaultVal)
411 , m_real_path(value)
414 /** @see Cfg_Str::LoadFromFile. */
415 virtual void LoadFromFile(wxConfigBase* cfg)
417 Cfg_Str::LoadFromFile(cfg);
419 m_real_path = CPath::FromUniv(m_temp_path);
423 /** @see Cfg_Str::SaveToFile. */
424 virtual void SaveToFile(wxConfigBase* cfg)
426 m_temp_path = CPath::ToUniv(m_real_path);
428 Cfg_Str::SaveToFile(cfg);
432 /** @see Cfg_Tmpl::TransferToWindow. */
433 virtual bool TransferToWindow()
435 m_temp_path = m_real_path.GetRaw();
437 return Cfg_Str::TransferToWindow();
440 /** @see Cfg_Tmpl::TransferFromWindow. */
441 virtual bool TransferFromWindow()
443 if (Cfg_Str::TransferFromWindow()) {
444 m_real_path = CPath(m_temp_path);
445 return true;
448 return false;
451 private:
452 wxString m_temp_path;
453 CPath& m_real_path;
458 * Cfg class that takes care of integer types.
460 * This template is needed since wxValidator only supports normals ints, and
461 * wxConfig for the matter only supports longs, thus some worksarounds are
462 * needed.
464 * There are two work-arounds:
465 * 1) wxValidator only supports int*, so we need a immediate variable to act
466 * as a storage. Thus we use Cfg_Tmpl<int> as base class. Thus this class
467 * contains a integer which we use to pass the value back and forth
468 * between the widgets.
470 * 2) wxConfig uses longs to save and read values, thus we need an immediate
471 * stage when loading and saving the value.
473 template <typename TYPE>
474 class Cfg_Int : public Cfg_Tmpl<int>
476 public:
477 Cfg_Int( const wxString& keyname, TYPE& value, int defaultVal = 0 )
478 : Cfg_Tmpl<int>( keyname, m_temp_value, defaultVal ),
479 m_real_value( value ),
480 m_temp_value( value )
484 virtual void LoadFromFile(wxConfigBase* cfg)
486 long tmp = 0;
487 cfg->Read( GetKey(), &tmp, m_default );
489 // Set the temp value
490 m_temp_value = (int)tmp;
491 // Set the actual value
492 m_real_value = (TYPE)tmp;
495 virtual void SaveToFile(wxConfigBase* cfg)
497 cfg->Write( GetKey(), (long)m_real_value );
501 #ifndef AMULE_DAEMON
502 virtual bool TransferFromWindow()
504 if ( Cfg_Tmpl<int>::TransferFromWindow() ) {
505 m_real_value = (TYPE)m_temp_value;
507 return true;
510 return false;
513 virtual bool TransferToWindow()
515 m_temp_value = (int)m_real_value;
517 if ( Cfg_Tmpl<int>::TransferToWindow() ) {
519 // In order to let us update labels on slider-changes, we trigger a event
520 wxSlider *slider = dynamic_cast<wxSlider *>(m_widget);
521 if (slider) {
522 int id = m_widget->GetId();
523 int pos = slider->GetValue();
524 wxScrollEvent evt( wxEVT_SCROLL_THUMBRELEASE, id, pos );
525 m_widget->GetEventHandler()->ProcessEvent( evt );
528 return true;
531 return false;
533 #endif
535 protected:
537 TYPE& m_real_value;
538 int m_temp_value;
543 * Helper function for creating new Cfg_Ints.
545 * @param keyname The cfg-key under which the item should be saved.
546 * @param value The variable to syncronize. The type of this variable defines the type used to create the Cfg_Int.
547 * @param defaultVal The default value if the key isn't found when loading the value.
548 * @return A pointer to the new Cfg_Int object. The caller is responsible for deleting it.
550 * This template-function returns a Cfg_Int of the appropriate type for the
551 * variable used as argument and should be used to avoid having to specify
552 * the integer type when adding a new Cfg_Int, since that's just increases
553 * the maintainence burden.
555 template <class TYPE>
556 Cfg_Base* MkCfg_Int( const wxString& keyname, TYPE& value, int defaultVal )
558 return new Cfg_Int<TYPE>( keyname, value, defaultVal );
563 * Cfg-class for bools.
565 class Cfg_Bool : public Cfg_Tmpl<bool>
567 public:
568 Cfg_Bool( const wxString& keyname, bool& value, bool defaultVal )
569 : Cfg_Tmpl<bool>( keyname, value, defaultVal )
573 virtual void LoadFromFile(wxConfigBase* cfg)
575 cfg->Read( GetKey(), &m_value, m_default );
578 virtual void SaveToFile(wxConfigBase* cfg)
580 cfg->Write( GetKey(), m_value );
585 #ifndef AMULE_DAEMON
587 class Cfg_Colour : public Cfg_Base
589 public:
590 Cfg_Colour(const wxString& key, wxColour& colour)
591 : Cfg_Base(key),
592 m_colour(colour),
593 m_default(CMuleColour(colour).GetULong())
596 virtual void LoadFromFile(wxConfigBase* cfg)
598 long int rgb;
599 cfg->Read(GetKey(), &rgb, m_default);
600 m_colour.Set(rgb);
603 virtual void SaveToFile(wxConfigBase* cfg)
605 cfg->Write(GetKey(), static_cast<long int>(CMuleColour(m_colour).GetULong()));
608 private:
609 wxColour& m_colour;
610 long int m_default;
614 typedef struct {
615 int id;
616 bool available;
617 wxString displayname;
618 wxString name;
619 } LangInfo;
623 * The languages aMule has translation for.
625 * Add new languages here.
626 * Then activate the test code in Cfg_Lang::UpdateChoice below!
628 static LangInfo aMuleLanguages[] = {
629 { wxLANGUAGE_DEFAULT, true, wxEmptyString, wxTRANSLATE("System default") },
630 { wxLANGUAGE_ALBANIAN, false, wxEmptyString, wxTRANSLATE("Albanian") },
631 { wxLANGUAGE_ARABIC, false, wxEmptyString, wxTRANSLATE("Arabic") },
632 { wxLANGUAGE_ASTURIAN, false, wxEmptyString, wxTRANSLATE("Asturian") },
633 { wxLANGUAGE_BASQUE, false, wxEmptyString, wxTRANSLATE("Basque") },
634 { wxLANGUAGE_BULGARIAN, false, wxEmptyString, wxTRANSLATE("Bulgarian") },
635 { wxLANGUAGE_CATALAN, false, wxEmptyString, wxTRANSLATE("Catalan") },
636 { wxLANGUAGE_CHINESE_SIMPLIFIED, false, wxEmptyString, wxTRANSLATE("Chinese (Simplified)") },
637 { wxLANGUAGE_CHINESE_TRADITIONAL, false, wxEmptyString, wxTRANSLATE("Chinese (Traditional)") },
638 { wxLANGUAGE_CROATIAN, false, wxEmptyString, wxTRANSLATE("Croatian") },
639 { wxLANGUAGE_CZECH, false, wxEmptyString, wxTRANSLATE("Czech") },
640 { wxLANGUAGE_DANISH, false, wxEmptyString, wxTRANSLATE("Danish") },
641 { wxLANGUAGE_DUTCH, false, wxEmptyString, wxTRANSLATE("Dutch") },
642 { wxLANGUAGE_ENGLISH, false, wxEmptyString, wxTRANSLATE("English (U.K.)") },
643 { wxLANGUAGE_ESTONIAN, false, wxEmptyString, wxTRANSLATE("Estonian") },
644 { wxLANGUAGE_FINNISH, false, wxEmptyString, wxTRANSLATE("Finnish") },
645 { wxLANGUAGE_FRENCH, false, wxEmptyString, wxTRANSLATE("French") },
646 { wxLANGUAGE_GALICIAN, false, wxEmptyString, wxTRANSLATE("Galician") },
647 { wxLANGUAGE_GERMAN, false, wxEmptyString, wxTRANSLATE("German") },
648 { wxLANGUAGE_GREEK, false, wxEmptyString, wxTRANSLATE("Greek") },
649 { wxLANGUAGE_HEBREW, false, wxEmptyString, wxTRANSLATE("Hebrew") },
650 { wxLANGUAGE_HUNGARIAN, false, wxEmptyString, wxTRANSLATE("Hungarian") },
651 { wxLANGUAGE_ITALIAN, false, wxEmptyString, wxTRANSLATE("Italian") },
652 { wxLANGUAGE_ITALIAN_SWISS, false, wxEmptyString, wxTRANSLATE("Italian (Swiss)") },
653 { wxLANGUAGE_JAPANESE, false, wxEmptyString, wxTRANSLATE("Japanese") },
654 { wxLANGUAGE_KOREAN, false, wxEmptyString, wxTRANSLATE("Korean") },
655 { wxLANGUAGE_LITHUANIAN, false, wxEmptyString, wxTRANSLATE("Lithuanian") },
656 { wxLANGUAGE_NORWEGIAN_NYNORSK, false, wxEmptyString, wxTRANSLATE("Norwegian (Nynorsk)") },
657 { wxLANGUAGE_POLISH, false, wxEmptyString, wxTRANSLATE("Polish") },
658 { wxLANGUAGE_PORTUGUESE, false, wxEmptyString, wxTRANSLATE("Portuguese") },
659 { wxLANGUAGE_PORTUGUESE_BRAZILIAN, false, wxEmptyString, wxTRANSLATE("Portuguese (Brazilian)") },
660 { wxLANGUAGE_RUSSIAN, false, wxEmptyString, wxTRANSLATE("Russian") },
661 { wxLANGUAGE_SLOVENIAN, false, wxEmptyString, wxTRANSLATE("Slovenian") },
662 { wxLANGUAGE_SPANISH, false, wxEmptyString, wxTRANSLATE("Spanish") },
663 { wxLANGUAGE_SWEDISH, false, wxEmptyString, wxTRANSLATE("Swedish") },
664 { wxLANGUAGE_TURKISH, false, wxEmptyString, wxTRANSLATE("Turkish") },
665 { wxLANGUAGE_UKRAINIAN, false, wxEmptyString, wxTRANSLATE("Ukrainian") },
669 typedef Cfg_Int<int> Cfg_PureInt;
671 class Cfg_Lang : public Cfg_PureInt, public Cfg_Lang_Base
673 public:
674 Cfg_Lang()
675 : Cfg_PureInt( wxEmptyString, m_selection, 0 )
677 m_languagesReady = false;
678 m_changePos = 0;
681 virtual void LoadFromFile(wxConfigBase* WXUNUSED(cfg)) {}
682 virtual void SaveToFile(wxConfigBase* WXUNUSED(cfg)) {}
685 virtual bool TransferFromWindow()
687 if (!m_languagesReady) {
688 return true; // nothing changed, no problem
691 if ( Cfg_PureInt::TransferFromWindow() ) {
692 // find wx ID of selected language
693 int i = 0;
694 while (m_selection > 0) {
695 i++;
696 if (aMuleLanguages[i].available) {
697 m_selection--;
700 int id = aMuleLanguages[i].id;
702 // save language selection
703 thePrefs::SetLanguageID(wxLang2Str(id));
705 return true;
708 return false;
712 virtual bool TransferToWindow()
714 m_langSelector = dynamic_cast<wxChoice*>(m_widget); // doesn't work in ctor!
715 if (m_languagesReady) {
716 FillChoice();
717 } else {
718 int wxId = StrLang2wx(thePrefs::GetLanguageID());
719 m_langSelector->Clear();
720 m_selection = 0;
721 for (uint32 i = 0; i < itemsof(aMuleLanguages); i++) {
722 if ( aMuleLanguages[i].id == wxId ) {
723 m_langSelector->Append(wxString(wxGetTranslation(aMuleLanguages[i].name)) + wxT(" [") + aMuleLanguages[i].name + wxT("]"));
724 break;
727 m_langSelector->Append(_("Change Language"));
728 m_changePos = m_langSelector->GetCount() - 1;
731 return Cfg_PureInt::TransferToWindow();
734 virtual void UpdateChoice(int pos)
736 if (!m_languagesReady && pos == m_changePos) {
737 // Find available languages and translate them.
738 // This is only done when the user selects "Change Language"
739 // Language is changed rarely, and the go-through-all locales takes a considerable
740 // time when the settings dialog is opened for the first time.
741 wxBusyCursor busyCursor;
742 aMuleLanguages[0].displayname = wxGetTranslation(aMuleLanguages[0].name);
743 for (unsigned int i = 1; i < itemsof(aMuleLanguages); ++i) {
744 if (wxLocale::IsAvailable(aMuleLanguages[i].id)) {
745 // This supresses error-messages about invalid locales.
746 wxLogNull logTarget;
747 wxLocale locale_to_check;
749 InitLocale(locale_to_check, aMuleLanguages[i].id);
750 if (locale_to_check.IsOk() && locale_to_check.IsLoaded(wxT(PACKAGE))) {
751 aMuleLanguages[i].displayname = wxString(wxGetTranslation(aMuleLanguages[i].name)) + wxT(" [") + aMuleLanguages[i].name + wxT("]");
752 aMuleLanguages[i].available = true;
753 #if 0
754 // Check for language problems
755 // Activate this code temporarily after messing with the languages!
756 int wxid = StrLang2wx(wxLang2Str(aMuleLanguages[i].id));
757 if (wxid != aMuleLanguages[i].id) {
758 AddDebugLogLineN(logGeneral, CFormat(wxT("Language problem for %s : aMule id %d != wx id %d"))
759 % aMuleLanguages[i].name % aMuleLanguages[i].id % wxid);
761 #endif
765 // Restore original locale
766 wxLocale tmpLocale;
767 InitLocale(tmpLocale, theApp->m_locale.GetLanguage());
768 FillChoice();
769 m_langSelector->SetSelection(m_selection);
770 m_languagesReady = true;
774 protected:
775 int m_selection;
777 private:
778 void FillChoice()
780 int wxId = StrLang2wx(thePrefs::GetLanguageID());
781 m_langSelector->Clear();
782 // Add all available languages and find the index of the selected language.
783 for ( unsigned int i = 0, j = 0; i < itemsof(aMuleLanguages); i++) {
784 if (aMuleLanguages[i].available) {
785 m_langSelector->Append(aMuleLanguages[i].displayname);
786 if ( aMuleLanguages[i].id == wxId ) {
787 m_selection = j;
789 j++;
794 bool m_languagesReady; // true: all translations calculated
795 int m_changePos;
796 wxChoice * m_langSelector;
799 #endif /* ! AMULE_DAEMON */
801 void Cfg_Lang_Base::UpdateChoice(int) {} // dummy
803 class Cfg_Skin : public Cfg_Str
805 public:
806 Cfg_Skin( const wxString& keyname, wxString& value, const wxString& defaultVal = EmptyString )
807 : Cfg_Str( keyname, value, defaultVal ),
808 m_is_skin(false)
811 #ifndef AMULE_DAEMON
812 virtual bool TransferFromWindow()
814 if ( Cfg_Str::TransferFromWindow() ) {
815 if (m_is_skin) {
816 wxChoice *skinSelector = dynamic_cast<wxChoice*>(m_widget);
817 // "- default -" is always the first
818 if (skinSelector->GetSelection() == 0) {
819 m_value.Clear();
822 return true;
825 return false;
829 virtual bool TransferToWindow()
832 wxChoice *skinSelector = dynamic_cast<wxChoice*>(m_widget);
833 skinSelector->Clear();
835 wxString folder;
836 int flags = wxDIR_DIRS;
837 wxString filespec;
838 wxString defaultSelection = _("- default -");
839 //#warning there has to be a better way...
840 if ( GetKey() == wxT("/SkinGUIOptions/Skin") ) {
841 folder = wxT("skins");
842 m_is_skin = true;
843 flags = wxDIR_FILES;
844 filespec = wxT("*.zip");
845 skinSelector->Append(defaultSelection);
846 } else {
847 folder = wxT("webserver");
849 wxString dirName(JoinPaths(GetConfigDir(theApp->m_configFile), folder));
850 wxString Filename;
851 wxDir d;
853 if (wxDir::Exists(dirName) &&
854 d.Open(dirName) &&
855 d.GetFirst(& Filename, filespec, flags)
860 if (m_is_skin) {
861 Filename = wxT("User:") + Filename;
863 skinSelector->Append(Filename);
865 while (d.GetNext(&Filename));
868 wxString dataDir;
869 if (m_is_skin) {
870 dataDir = wxStandardPaths::Get().GetDataDir();
871 } else {
872 dataDir = wxStandardPaths::Get().GetResourcesDir();
874 #if !defined(__WXMSW__) && !defined(__WXMAC__)
875 dataDir = dataDir.BeforeLast(wxT('/')) + wxT("/amule");
876 #endif
877 wxString systemDir(JoinPaths(dataDir,folder));
879 if (wxDir::Exists(systemDir) &&
880 d.Open(systemDir) &&
881 d.GetFirst(& Filename, filespec, flags)
886 if (m_is_skin) {
887 Filename = wxT("System:") + Filename;
889 // avoid duplicates for webserver templates
890 if (skinSelector->FindString(Filename) == wxNOT_FOUND) {
891 skinSelector->Append(Filename);
894 while (d.GetNext(&Filename));
897 if ( skinSelector->GetCount() == 0 ) {
898 skinSelector->Append(_("no options available"));
901 int id = skinSelector->FindString(m_value);
902 if ( id == wxNOT_FOUND ) {
903 id = 0;
904 if (m_is_skin) {
905 m_value = defaultSelection;
908 skinSelector->SetSelection(id);
910 return Cfg_Str::TransferToWindow();
912 #endif /* ! AMULE_DAEMON */
914 protected:
915 bool m_is_skin;
919 /// new implementation
920 CPreferences::CPreferences()
922 srand( wxGetLocalTimeMillis().GetLo() ); // we need random numbers sometimes
924 // load preferences.dat or set standard values
925 wxString fullpath(theApp->ConfigDir + wxT("preferences.dat"));
926 CFile preffile;
927 if (wxFileExists(fullpath)) {
928 if (preffile.Open(fullpath, CFile::read)) {
929 try {
930 preffile.ReadUInt8(); // Version. Value is not used.
931 s_userhash = preffile.ReadHash();
932 } catch (const CSafeIOException& e) {
933 AddDebugLogLineC(logGeneral,
934 wxT("Error while reading userhash: ") + e.what());
939 if (s_userhash.IsEmpty()) {
940 for (int i = 0; i < 8; i++) {
941 RawPokeUInt16(s_userhash.GetHash() + (i * 2), rand());
944 Save();
947 // Mark hash as an eMule-type hash
948 // See also CUpDownClient::GetHashType
949 s_userhash[5] = 14;
950 s_userhash[14] = 111;
952 #ifndef CLIENT_GUI
953 LoadPreferences();
954 ReloadSharedFolders();
956 // serverlist adresses
957 CTextFile slistfile;
958 if (slistfile.Open(theApp->ConfigDir + wxT("addresses.dat"), CTextFile::read)) {
959 adresses_list = slistfile.ReadLines();
961 #endif
965 // Gets called at init time
967 void CPreferences::BuildItemList( const wxString& appdir )
969 #ifndef AMULE_DAEMON
970 #define NewCfgItem(ID, COMMAND) s_CfgList[ID] = COMMAND
971 #else
972 int current_id = 0;
973 #define NewCfgItem(ID, COMMAND) s_CfgList[++current_id] = COMMAND
974 #endif /* AMULE_DAEMON */
977 * User settings
979 NewCfgItem(IDC_NICK, (new Cfg_Str( wxT("/eMule/Nick"), s_nick, wxT("http://www.aMule.org") )));
980 #ifndef AMULE_DAEMON
981 Cfg_Lang * cfgLang = new Cfg_Lang();
982 s_cfgLang = cfgLang;
983 NewCfgItem(IDC_LANGUAGE, cfgLang);
984 #endif
987 * Browser options
989 #ifdef __WXMAC__
990 wxString customBrowser = wxT("/usr/bin/open");
991 #else
992 wxString customBrowser; // left empty
993 #endif
995 NewCfgItem(IDC_BROWSERTABS, (new Cfg_Bool( wxT("/Browser/OpenPageInTab"), s_BrowserTab, true )));
996 NewCfgItem(IDC_BROWSERSELF, (new Cfg_Str( wxT("/Browser/CustomBrowserString"), s_CustomBrowser, customBrowser )));
1000 * Misc
1002 NewCfgItem(IDC_QUEUESIZE, (MkCfg_Int( wxT("/eMule/QueueSizePref"), s_iQueueSize, 50 )));
1005 #ifdef __DEBUG__
1007 * Debugging
1009 NewCfgItem(ID_VERBOSEDEBUG, (new Cfg_Bool( wxT("/eMule/VerboseDebug"), s_bVerbose, false )));
1010 #endif
1013 * Connection settings
1015 NewCfgItem(IDC_MAXUP, (MkCfg_Int( wxT("/eMule/MaxUpload"), s_maxupload, 0 )));
1016 NewCfgItem(IDC_MAXDOWN, (MkCfg_Int( wxT("/eMule/MaxDownload"), s_maxdownload, 0 )));
1017 NewCfgItem(IDC_SLOTALLOC, (MkCfg_Int( wxT("/eMule/SlotAllocation"), s_slotallocation, 2 )));
1018 NewCfgItem(IDC_PORT, (MkCfg_Int( wxT("/eMule/Port"), s_port, DEFAULT_TCP_PORT )));
1019 NewCfgItem(IDC_UDPPORT, (MkCfg_Int( wxT("/eMule/UDPPort"), s_udpport, DEFAULT_UDP_PORT )));
1020 NewCfgItem(IDC_UDPENABLE, (new Cfg_Bool( wxT("/eMule/UDPEnable"), s_UDPEnable, true )));
1021 NewCfgItem(IDC_ADDRESS, (new Cfg_Str( wxT("/eMule/Address"), s_Addr, wxEmptyString)));
1022 NewCfgItem(IDC_AUTOCONNECT, (new Cfg_Bool( wxT("/eMule/Autoconnect"), s_autoconnect, true )));
1023 NewCfgItem(IDC_MAXSOURCEPERFILE, (MkCfg_Int( wxT("/eMule/MaxSourcesPerFile"), s_maxsourceperfile, 300 )));
1024 NewCfgItem(IDC_MAXCON, (MkCfg_Int( wxT("/eMule/MaxConnections"), s_maxconnections, GetRecommendedMaxConnections() )));
1025 NewCfgItem(IDC_MAXCON5SEC, (MkCfg_Int( wxT("/eMule/MaxConnectionsPerFiveSeconds"), s_MaxConperFive, 20 )));
1028 * Proxy
1030 NewCfgItem(ID_PROXY_ENABLE_PROXY, (new Cfg_Bool( wxT("/Proxy/ProxyEnableProxy"), s_ProxyData.m_proxyEnable, false )));
1031 NewCfgItem(ID_PROXY_TYPE, (MkCfg_Int( wxT("/Proxy/ProxyType"), s_ProxyData.m_proxyType, 0 )));
1032 NewCfgItem(ID_PROXY_NAME, (new Cfg_Str( wxT("/Proxy/ProxyName"), s_ProxyData.m_proxyHostName, wxEmptyString )));
1033 NewCfgItem(ID_PROXY_PORT, (MkCfg_Int( wxT("/Proxy/ProxyPort"), s_ProxyData.m_proxyPort, 1080 )));
1034 NewCfgItem(ID_PROXY_ENABLE_PASSWORD, (new Cfg_Bool( wxT("/Proxy/ProxyEnablePassword"), s_ProxyData.m_enablePassword, false )));
1035 NewCfgItem(ID_PROXY_USER, (new Cfg_Str( wxT("/Proxy/ProxyUser"), s_ProxyData.m_userName, wxEmptyString )));
1036 NewCfgItem(ID_PROXY_PASSWORD, (new Cfg_Str( wxT("/Proxy/ProxyPassword"), s_ProxyData.m_password, wxEmptyString )));
1037 // These were copied from eMule config file, maybe someone with windows can complete this?
1038 // NewCfgItem(ID_PROXY_AUTO_SERVER_CONNECT_WITHOUT_PROXY, (new Cfg_Bool( wxT("/Proxy/Proxy????"), s_Proxy????, false )));
1041 * Servers
1043 NewCfgItem(IDC_REMOVEDEAD, (new Cfg_Bool( wxT("/eMule/RemoveDeadServer"), s_deadserver, 1 )));
1044 NewCfgItem(IDC_SERVERRETRIES, (MkCfg_Int( wxT("/eMule/DeadServerRetry"), s_deadserverretries, 3 )));
1045 NewCfgItem(IDC_SERVERKEEPALIVE, (MkCfg_Int( wxT("/eMule/ServerKeepAliveTimeout"), s_dwServerKeepAliveTimeoutMins, 0 )));
1046 NewCfgItem(IDC_RECONN, (new Cfg_Bool( wxT("/eMule/Reconnect"), s_reconnect, true )));
1047 NewCfgItem(IDC_SCORE, (new Cfg_Bool( wxT("/eMule/Scoresystem"), s_scorsystem, true )));
1048 NewCfgItem(IDC_AUTOSERVER, (new Cfg_Bool( wxT("/eMule/Serverlist"), s_autoserverlist, false )));
1049 NewCfgItem(IDC_UPDATESERVERCONNECT, (new Cfg_Bool( wxT("/eMule/AddServerListFromServer"), s_addserversfromserver, false)));
1050 NewCfgItem(IDC_UPDATESERVERCLIENT, (new Cfg_Bool( wxT("/eMule/AddServerListFromClient"), s_addserversfromclient, false )));
1051 NewCfgItem(IDC_SAFESERVERCONNECT, (new Cfg_Bool( wxT("/eMule/SafeServerConnect"), s_safeServerConnect, false )));
1052 NewCfgItem(IDC_AUTOCONNECTSTATICONLY, (new Cfg_Bool( wxT("/eMule/AutoConnectStaticOnly"), s_autoconnectstaticonly, false )));
1053 NewCfgItem(IDC_UPNP_ENABLED, (new Cfg_Bool( wxT("/eMule/UPnPEnabled"), s_UPnPEnabled, false )));
1054 NewCfgItem(IDC_UPNPTCPPORT, (MkCfg_Int( wxT("/eMule/UPnPTCPPort"), s_UPnPTCPPort, 50000 )));
1055 NewCfgItem(IDC_SMARTIDCHECK, (new Cfg_Bool( wxT("/eMule/SmartIdCheck"), s_smartidcheck, true )));
1056 // Enabled networks
1057 NewCfgItem( IDC_NETWORKKAD, (new Cfg_Bool( wxT("/eMule/ConnectToKad"), s_ConnectToKad, true )) );
1058 NewCfgItem( IDC_NETWORKED2K, ( new Cfg_Bool( wxT("/eMule/ConnectToED2K"), s_ConnectToED2K, true ) ));
1062 * Files
1064 NewCfgItem(IDC_TEMPFILES, (new Cfg_Path( wxT("/eMule/TempDir"), s_tempdir, appdir + wxT("Temp") )));
1066 #if defined(__WXMAC__) || defined(__WXMSW__)
1067 wxString incpath = wxStandardPaths::Get().GetDocumentsDir();
1068 if (incpath.IsEmpty()) {
1069 // There is a built-in possibility for this call to fail, though I can't imagine a reason for that.
1070 incpath = appdir + wxT("Incoming");
1071 } else {
1072 incpath = JoinPaths(incpath, wxT("aMule Downloads"));
1074 #else
1075 wxString incpath = appdir + wxT("Incoming");
1076 #endif
1077 NewCfgItem(IDC_INCFILES, (new Cfg_Path( wxT("/eMule/IncomingDir"), s_incomingdir, incpath )));
1079 NewCfgItem(IDC_ICH, (new Cfg_Bool( wxT("/eMule/ICH"), s_ICH, true )));
1080 NewCfgItem(IDC_AICHTRUST, (new Cfg_Bool( wxT("/eMule/AICHTrust"), s_AICHTrustEveryHash, false )));
1081 NewCfgItem(IDC_CHECKDISKSPACE, (new Cfg_Bool( wxT("/eMule/CheckDiskspace"), s_checkDiskspace, true )));
1082 NewCfgItem(IDC_MINDISKSPACE, (MkCfg_Int( wxT("/eMule/MinFreeDiskSpace"), s_uMinFreeDiskSpace, 1 )));
1083 NewCfgItem(IDC_ADDNEWFILESPAUSED, (new Cfg_Bool( wxT("/eMule/AddNewFilesPaused"), s_addnewfilespaused, false )));
1084 NewCfgItem(IDC_PREVIEWPRIO, (new Cfg_Bool( wxT("/eMule/PreviewPrio"), s_bpreviewprio, false )));
1085 NewCfgItem(IDC_MANUALSERVERHIGHPRIO, (new Cfg_Bool( wxT("/eMule/ManualHighPrio"), s_bmanualhighprio, false )));
1086 NewCfgItem(IDC_STARTNEXTFILE, (new Cfg_Bool( wxT("/eMule/StartNextFile"), s_bstartnextfile, false )));
1087 NewCfgItem(IDC_STARTNEXTFILE_SAME, (new Cfg_Bool( wxT("/eMule/StartNextFileSameCat"), s_bstartnextfilesame, false )));
1088 NewCfgItem(IDC_STARTNEXTFILE_ALPHA, (new Cfg_Bool( wxT("/eMule/StartNextFileAlpha"), s_bstartnextfilealpha, false )));
1089 NewCfgItem(IDC_SRCSEEDS, (new Cfg_Bool( wxT("/ExternalConnect/UseSrcSeeds"), s_UseSrcSeeds, false )));
1090 NewCfgItem(IDC_FILEBUFFERSIZE, (MkCfg_Int( wxT("/eMule/FileBufferSizePref"), s_iFileBufferSize, 16 )));
1091 NewCfgItem(IDC_DAP, (new Cfg_Bool( wxT("/eMule/DAPPref"), s_bDAP, true )));
1092 NewCfgItem(IDC_UAP, (new Cfg_Bool( wxT("/eMule/UAPPref"), s_bUAP, true )));
1093 NewCfgItem(IDC_ALLOCFULLFILE, (new Cfg_Bool( wxT("/eMule/AllocateFullFile"), s_allocFullFile, false )));
1096 * Web Server
1098 NewCfgItem(IDC_OSDIR, (new Cfg_Path( wxT("/eMule/OSDirectory"), s_OSDirectory, appdir )));
1099 NewCfgItem(IDC_ONLINESIG, (new Cfg_Bool( wxT("/eMule/OnlineSignature"), s_onlineSig, false )));
1100 NewCfgItem(IDC_OSUPDATE, (MkCfg_Int( wxT("/eMule/OnlineSignatureUpdate"), s_OSUpdate, 5 )));
1101 NewCfgItem(IDC_ENABLE_WEB, (new Cfg_Bool( wxT("/WebServer/Enabled"), s_bWebEnabled, false )));
1102 NewCfgItem(IDC_WEB_PASSWD, (new Cfg_Str_Encrypted( wxT("/WebServer/Password"), s_sWebPassword )));
1103 NewCfgItem(IDC_WEB_PASSWD_LOW, (new Cfg_Str_Encrypted( wxT("/WebServer/PasswordLow"), s_sWebLowPassword )));
1104 NewCfgItem(IDC_WEB_PORT, (MkCfg_Int( wxT("/WebServer/Port"), s_nWebPort, 4711 )));
1105 NewCfgItem(IDC_WEBUPNPTCPPORT, (MkCfg_Int( wxT("/WebServer/WebUPnPTCPPort"), s_nWebUPnPTCPPort, 50001 )));
1106 NewCfgItem(IDC_UPNP_WEBSERVER_ENABLED,
1107 (new Cfg_Bool( wxT("/WebServer/UPnPWebServerEnabled"), s_UPnPWebServerEnabled, false )));
1108 NewCfgItem(IDC_WEB_GZIP, (new Cfg_Bool( wxT("/WebServer/UseGzip"), s_bWebUseGzip, true )));
1109 NewCfgItem(IDC_ENABLE_WEB_LOW, (new Cfg_Bool( wxT("/WebServer/UseLowRightsUser"), s_bWebLowEnabled, false )));
1110 NewCfgItem(IDC_WEB_REFRESH_TIMEOUT, (MkCfg_Int( wxT("/WebServer/PageRefreshTime"), s_nWebPageRefresh, 120 )));
1111 NewCfgItem(IDC_WEBTEMPLATE, (new Cfg_Skin( wxT("/WebServer/Template"), s_WebTemplate, wxEmptyString )));
1114 * External Connections
1116 NewCfgItem(IDC_EXT_CONN_ACCEPT, (new Cfg_Bool( wxT("/ExternalConnect/AcceptExternalConnections"), s_AcceptExternalConnections, false )));
1117 NewCfgItem(IDC_EXT_CONN_IP, (new Cfg_Str( wxT("/ExternalConnect/ECAddress"), s_ECAddr, wxEmptyString )));
1118 NewCfgItem(IDC_EXT_CONN_TCP_PORT, (MkCfg_Int( wxT("/ExternalConnect/ECPort"), s_ECPort, 4712 )));
1119 NewCfgItem(IDC_EXT_CONN_PASSWD, (new Cfg_Str_Encrypted( wxT("/ExternalConnect/ECPassword"), s_ECPassword, wxEmptyString )));
1120 NewCfgItem(IDC_UPNP_EC_ENABLED, (new Cfg_Bool( wxT("/ExternalConnect/UPnPECEnabled"), s_UPnPECEnabled, false )));
1123 * GUI behavior
1125 NewCfgItem(IDC_ENABLETRAYICON, (new Cfg_Bool( wxT("/eMule/EnableTrayIcon"), s_trayiconenabled, false )));
1126 NewCfgItem(IDC_MINTRAY, (new Cfg_Bool( wxT("/eMule/MinToTray"), s_mintotray, false )));
1127 NewCfgItem(IDC_EXIT, (new Cfg_Bool( wxT("/eMule/ConfirmExit"), s_confirmExit, true )));
1128 NewCfgItem(IDC_STARTMIN, (new Cfg_Bool( wxT("/eMule/StartupMinimized"), s_startMinimized, false )));
1131 * GUI appearence
1133 NewCfgItem(IDC_3DDEPTH, (MkCfg_Int( wxT("/eMule/3DDepth"), s_depth3D, 10 )));
1134 NewCfgItem(IDC_TOOLTIPDELAY, (MkCfg_Int( wxT("/eMule/ToolTipDelay"), s_iToolDelayTime, 1 )));
1135 NewCfgItem(IDC_SHOWOVERHEAD, (new Cfg_Bool( wxT("/eMule/ShowOverhead"), s_bshowoverhead, false )));
1136 NewCfgItem(IDC_EXTCATINFO, (new Cfg_Bool( wxT("/eMule/ShowInfoOnCatTabs"), s_showCatTabInfos, true )));
1137 NewCfgItem(IDC_FED2KLH, (new Cfg_Bool( wxT("/Razor_Preferences/FastED2KLinksHandler"), s_FastED2KLinksHandler, true )));
1138 NewCfgItem(IDC_PROGBAR, (new Cfg_Bool( wxT("/ExternalConnect/ShowProgressBar"), s_ProgBar, true )));
1139 NewCfgItem(IDC_PERCENT, (new Cfg_Bool( wxT("/ExternalConnect/ShowPercent"), s_Percent, true )));
1140 NewCfgItem(IDC_SKIN, (new Cfg_Skin( wxT("/SkinGUIOptions/Skin"), s_Skin, wxEmptyString )));
1141 NewCfgItem(IDC_VERTTOOLBAR, (new Cfg_Bool( wxT("/eMule/VerticalToolbar"), s_ToolbarOrientation, false )));
1142 NewCfgItem(IDC_SHOW_COUNTRY_FLAGS, (new Cfg_Bool( wxT("/eMule/GeoIPEnabled"), s_GeoIPEnabled, true )));
1143 #ifndef __SVN__
1144 NewCfgItem(IDC_SHOWVERSIONONTITLE, (new Cfg_Bool( wxT("/eMule/ShowVersionOnTitle"), s_showVersionOnTitle, false )));
1145 #endif
1148 * External Apps
1150 NewCfgItem(IDC_VIDEOPLAYER, (new Cfg_Str( wxT("/eMule/VideoPlayer"), s_VideoPlayer, wxEmptyString )));
1153 * Statistics
1155 NewCfgItem(IDC_SLIDER, (MkCfg_Int( wxT("/eMule/StatGraphsInterval"), s_trafficOMeterInterval, 3 )));
1156 NewCfgItem(IDC_SLIDER2, (MkCfg_Int( wxT("/eMule/statsInterval"), s_statsInterval, 30 )));
1157 NewCfgItem(IDC_DOWNLOAD_CAP, (MkCfg_Int( wxT("/eMule/DownloadCapacity"), s_maxGraphDownloadRate, 300 )));
1158 NewCfgItem(IDC_UPLOAD_CAP, (MkCfg_Int( wxT("/eMule/UploadCapacity"), s_maxGraphUploadRate, 100 )));
1159 NewCfgItem(IDC_SLIDER3, (MkCfg_Int( wxT("/eMule/StatsAverageMinutes"), s_statsAverageMinutes, 5 )));
1160 NewCfgItem(IDC_SLIDER4, (MkCfg_Int( wxT("/eMule/VariousStatisticsMaxValue"), s_statsMax, 100 )));
1161 NewCfgItem(IDC_CLIENTVERSIONS, (MkCfg_Int( wxT("/Statistics/MaxClientVersions"), s_maxClientVersions, 0 )));
1164 * Security
1166 NewCfgItem(IDC_SEESHARES, (MkCfg_Int( wxT("/eMule/SeeShare"), s_iSeeShares, 2 )));
1167 NewCfgItem(IDC_SECIDENT, (new Cfg_Bool( wxT("/ExternalConnect/UseSecIdent"), s_SecIdent, true )));
1168 NewCfgItem(IDC_IPFCLIENTS, (new Cfg_Bool( wxT("/ExternalConnect/IpFilterClients"), s_IPFilterClients, true )));
1169 NewCfgItem(IDC_IPFSERVERS, (new Cfg_Bool( wxT("/ExternalConnect/IpFilterServers"), s_IPFilterServers, true )));
1170 NewCfgItem(IDC_FILTERLAN, (new Cfg_Bool( wxT("/eMule/FilterLanIPs"), s_filterLanIP, true )));
1171 NewCfgItem(IDC_PARANOID, (new Cfg_Bool( wxT("/eMule/ParanoidFiltering"), s_paranoidfilter, true )));
1172 NewCfgItem(IDC_AUTOIPFILTER, (new Cfg_Bool( wxT("/eMule/IPFilterAutoLoad"), s_IPFilterAutoLoad, true )));
1173 NewCfgItem(IDC_IPFILTERURL, (new Cfg_Str( wxT("/eMule/IPFilterURL"), s_IPFilterURL, wxEmptyString )));
1174 NewCfgItem(ID_IPFILTERLEVEL, (MkCfg_Int( wxT("/eMule/FilterLevel"), s_filterlevel, 127 )));
1175 NewCfgItem(IDC_IPFILTERSYS, (new Cfg_Bool( wxT("/eMule/IPFilterSystem"), s_IPFilterSys, false )));
1178 * Message Filter
1180 NewCfgItem(IDC_MSGFILTER, (new Cfg_Bool( wxT("/eMule/FilterMessages"), s_MustFilterMessages, true )));
1181 NewCfgItem(IDC_MSGFILTER_ALL, (new Cfg_Bool( wxT("/eMule/FilterAllMessages"), s_FilterAllMessages, false )));
1182 NewCfgItem(IDC_MSGFILTER_NONFRIENDS, (new Cfg_Bool( wxT("/eMule/MessagesFromFriendsOnly"), s_msgonlyfriends, false )));
1183 NewCfgItem(IDC_MSGFILTER_NONSECURE, (new Cfg_Bool( wxT("/eMule/MessageFromValidSourcesOnly"), s_msgsecure, true )));
1184 NewCfgItem(IDC_MSGFILTER_WORD, (new Cfg_Bool( wxT("/eMule/FilterWordMessages"), s_FilterSomeMessages, false )));
1185 NewCfgItem(IDC_MSGWORD, (new Cfg_Str( wxT("/eMule/MessageFilter"), s_MessageFilterString, wxEmptyString )));
1186 NewCfgItem(IDC_MSGLOG, (new Cfg_Bool( wxT("/eMule/ShowMessagesInLog"), s_ShowMessagesInLog, true )));
1187 //Todo NewCfgItem(IDC_MSGADVSPAM, (new Cfg_Bool( wxT("/eMule/AdvancedSpamFilter"), s_IsAdvancedSpamfilterEnabled, true )));
1188 //Todo NewCfgItem(IDC_MSGCAPTCHA, (new Cfg_Bool( wxT("/eMule/MessageUseCaptchas"), s_IsChatCaptchaEnabled, true )));
1189 s_MiscList.push_back( new Cfg_Bool( wxT("/eMule/AdvancedSpamFilter"), s_IsAdvancedSpamfilterEnabled, true ) );
1190 s_MiscList.push_back( new Cfg_Bool( wxT("/eMule/MessageUseCaptchas"), s_IsChatCaptchaEnabled, true ) );
1192 NewCfgItem(IDC_FILTERCOMMENTS, (new Cfg_Bool( wxT("/eMule/FilterComments"), s_FilterComments, false )));
1193 NewCfgItem(IDC_COMMENTWORD, (new Cfg_Str( wxT("/eMule/CommentFilter"), s_CommentFilterString, wxEmptyString )));
1196 * Hidden files sharing
1198 NewCfgItem(IDC_SHAREHIDDENFILES, (new Cfg_Bool( wxT("/eMule/ShareHiddenFiles"), s_ShareHiddenFiles, false )));
1201 * Auto-Sorting of downloads
1203 NewCfgItem(IDC_AUTOSORT, (new Cfg_Bool( wxT("/eMule/AutoSortDownloads"), s_AutoSortDownload, false )));
1206 * Version check
1208 NewCfgItem(IDC_NEWVERSION, (new Cfg_Bool( wxT("/eMule/NewVersionCheck"), s_NewVersionCheck, true )));
1211 * Obfuscation
1213 NewCfgItem( IDC_SUPPORT_PO, ( new Cfg_Bool( wxT("/Obfuscation/IsClientCryptLayerSupported"), s_IsClientCryptLayerSupported, true )));
1214 NewCfgItem( IDC_ENABLE_PO_OUTGOING, ( new Cfg_Bool( wxT("/Obfuscation/IsCryptLayerRequested"), s_bCryptLayerRequested, true )));
1215 NewCfgItem( IDC_ENFORCE_PO_INCOMING, ( new Cfg_Bool( wxT("/Obfuscation/IsClientCryptLayerRequired"), s_IsClientCryptLayerRequired, false )));
1216 #ifndef CLIENT_GUI
1217 // There is no need for GUI items for this two.
1218 s_MiscList.push_back( MkCfg_Int( wxT("/Obfuscation/CryptoPaddingLenght"), s_byCryptTCPPaddingLength, 254 ) );
1219 s_MiscList.push_back( MkCfg_Int( wxT("/Obfuscation/CryptoKadUDPKey"), s_dwKadUDPKey, GetRandomUint32() ) );
1220 #endif
1223 * Power management
1225 NewCfgItem( IDC_PREVENT_SLEEP, ( new Cfg_Bool( wxT("/PowerManagement/PreventSleepWhileDownloading"), s_preventSleepWhileDownloading, false )));
1228 * The following doesn't have an associated widget or section
1230 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/Language"), s_languageID ) );
1231 s_MiscList.push_back( MkCfg_Int( wxT("/eMule/SplitterbarPosition"), s_splitterbarPosition, 75 ) );
1232 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/YourHostname"), s_yourHostname, wxEmptyString ) );
1233 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/DateTimeFormat"), s_datetimeformat, wxT("%A, %x, %X") ) );
1235 s_MiscList.push_back( MkCfg_Int( wxT("/eMule/AllcatType"), s_allcatFilter, 0 ) );
1236 s_MiscList.push_back( new Cfg_Bool( wxT("/eMule/ShowAllNotCats"), s_showAllNotCats, false ) );
1238 s_MiscList.push_back( MkCfg_Int( wxT("/eMule/SmartIdState"), s_smartidstate, 0 ) );
1240 s_MiscList.push_back( new Cfg_Bool( wxT("/eMule/DropSlowSources"), s_DropSlowSources, false ) );
1242 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/KadNodesUrl"), s_KadURL, wxT("http://download.tuxfamily.org/technosalad/utils/nodes.dat") ) );
1243 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/Ed2kServersUrl"), s_Ed2kURL, wxT("http://gruk.org/server.met.gz") ) );
1244 s_MiscList.push_back( MkCfg_Int( wxT("/eMule/ShowRatesOnTitle"), s_showRatesOnTitle, 0 ));
1246 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/GeoLiteCountryUpdateUrl"), s_GeoIPUpdateUrl, wxT("http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz") ) );
1247 wxConfigBase::Get()->DeleteEntry(wxT("/eMule/GeoIPUpdateUrl")); // get rid of the old one for a while
1249 s_MiscList.push_back( new Cfg_Str( wxT("/WebServer/Path"), s_sWebPath, wxT("amuleweb") ) );
1251 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/StatsServerName"), s_StatsServerName, wxT("Shorty's ED2K stats") ) );
1252 s_MiscList.push_back( new Cfg_Str( wxT("/eMule/StatsServerURL"), s_StatsServerURL, wxT("http://ed2k.shortypower.dyndns.org/?hash=") ) );
1254 s_MiscList.push_back( new Cfg_Bool( wxT("/ExternalConnect/TransmitOnlyUploadingClients"), s_TransmitOnlyUploadingClients, false ) );
1256 #ifndef AMULE_DAEMON
1257 // Colors have been moved from global prefs to CStatisticsDlg
1258 for ( int i = 0; i < cntStatColors; i++ ) {
1259 wxString str = CFormat(wxT("/eMule/StatColor%i")) % i;
1260 s_MiscList.push_back( new Cfg_Colour( str, CStatisticsDlg::acrStat[i] ) );
1262 #endif
1264 // User events
1265 for (unsigned int i = 0; i < CUserEvents::GetCount(); ++i) {
1266 // We can't use NewCfgItem here, because we need to find these items
1267 // later, which would be impossible in amuled with NewCfgItem.
1268 // The IDs we assign here are high enough to not cause any collision
1269 // even on the daemon.
1270 s_CfgList[USEREVENTS_FIRST_ID + i * USEREVENTS_IDS_PER_EVENT + 1] = new Cfg_Bool(wxT("/UserEvents/") + CUserEvents::GetKey(i) + wxT("/CoreEnabled"), CUserEvents::GetCoreEnableVar(i), false);
1271 s_CfgList[USEREVENTS_FIRST_ID + i * USEREVENTS_IDS_PER_EVENT + 2] = new Cfg_Str(wxT("/UserEvents/") + CUserEvents::GetKey(i) + wxT("/CoreCommand"), CUserEvents::GetCoreCommandVar(i), wxEmptyString);
1272 s_CfgList[USEREVENTS_FIRST_ID + i * USEREVENTS_IDS_PER_EVENT + 3] = new Cfg_Bool(wxT("/UserEvents/") + CUserEvents::GetKey(i) + wxT("/GUIEnabled"), CUserEvents::GetGUIEnableVar(i), false);
1273 s_CfgList[USEREVENTS_FIRST_ID + i * USEREVENTS_IDS_PER_EVENT + 4] = new Cfg_Str(wxT("/UserEvents/") + CUserEvents::GetKey(i) + wxT("/GUICommand"), CUserEvents::GetGUICommandVar(i), wxEmptyString);
1278 void CPreferences::EraseItemList()
1280 while ( s_CfgList.begin() != s_CfgList.end() ) {
1281 delete s_CfgList.begin()->second;
1282 s_CfgList.erase( s_CfgList.begin() );
1285 CFGList::iterator it = s_MiscList.begin();
1286 for ( ; it != s_MiscList.end(); ) {
1287 delete *it;
1288 it = s_MiscList.erase( it );
1293 void CPreferences::LoadAllItems(wxConfigBase* cfg)
1295 #ifndef CLIENT_GUI
1296 // Preserve values from old config. The global config object may not be set yet
1297 // when BuildItemList() is called, so we need to provide defaults later - here.
1298 if (cfg->HasEntry(wxT("/eMule/ExecOnCompletion"))) {
1299 bool ExecOnCompletion;
1300 cfg->Read(wxT("/eMule/ExecOnCompletion"), &ExecOnCompletion, false);
1301 // Assign to core command, that's the most likely it was.
1302 static_cast<Cfg_Bool*>(s_CfgList[USEREVENTS_FIRST_ID + CUserEvents::DownloadCompleted * USEREVENTS_IDS_PER_EVENT + 1])->SetDefault(ExecOnCompletion);
1303 cfg->DeleteEntry(wxT("/eMule/ExecOnCompletion"));
1305 if (cfg->HasEntry(wxT("/eMule/ExecOnCompletionCommand"))) {
1306 wxString ExecOnCompletionCommand;
1307 cfg->Read(wxT("/eMule/ExecOnCompletionCommand"), &ExecOnCompletionCommand, wxEmptyString);
1308 static_cast<Cfg_Str*>(s_CfgList[USEREVENTS_FIRST_ID + CUserEvents::DownloadCompleted * USEREVENTS_IDS_PER_EVENT + 2])->SetDefault(ExecOnCompletionCommand);
1309 cfg->DeleteEntry(wxT("/eMule/ExecOnCompletionCommand"));
1311 #endif
1312 CFGMap::iterator it_a = s_CfgList.begin();
1313 for ( ; it_a != s_CfgList.end(); ++it_a ) {
1314 it_a->second->LoadFromFile( cfg );
1317 CFGList::iterator it_b = s_MiscList.begin();
1318 for ( ; it_b != s_MiscList.end(); ++it_b ) {
1319 (*it_b)->LoadFromFile( cfg );
1322 // Preserve old value of UDPDisable
1323 if (cfg->HasEntry(wxT("/eMule/UDPDisable"))) {
1324 bool UDPDisable;
1325 cfg->Read(wxT("/eMule/UDPDisable"), &UDPDisable, false);
1326 SetUDPDisable(UDPDisable);
1327 cfg->DeleteEntry(wxT("/eMule/UDPDisable"));
1330 // Preserve old value of UseSkinFiles
1331 if (cfg->HasEntry(wxT("/SkinGUIOptions/UseSkinFiles"))) {
1332 bool UseSkinFiles;
1333 cfg->Read(wxT("/SkinGUIOptions/UseSkinFiles"), &UseSkinFiles, false);
1334 if (!UseSkinFiles) {
1335 s_Skin.Clear();
1337 cfg->DeleteEntry(wxT("/SkinGUIOptions/UseSkinFiles"));
1340 #ifdef __DEBUG__
1341 // Load debug-categories
1342 int count = theLogger.GetDebugCategoryCount();
1344 for ( int i = 0; i < count; i++ ) {
1345 const CDebugCategory& cat = theLogger.GetDebugCategory( i );
1347 bool enabled = false;
1348 cfg->Read( wxT("/Debug/Cat_") + cat.GetName(), &enabled );
1350 theLogger.SetEnabled( cat.GetType(), enabled );
1352 #endif
1354 // Now do some post-processing / sanity checking on the values we just loaded
1355 #ifndef CLIENT_GUI
1356 CheckUlDlRatio();
1357 SetPort(s_port);
1358 if (s_byCryptTCPPaddingLength > 254) {
1359 s_byCryptTCPPaddingLength = GetRandomUint8() % 254;
1361 SetSlotAllocation(s_slotallocation);
1362 #endif
1366 void CPreferences::SaveAllItems(wxConfigBase* cfg)
1368 // Save the Cfg values
1369 CFGMap::iterator it_a = s_CfgList.begin();
1370 for ( ; it_a != s_CfgList.end(); ++it_a )
1371 it_a->second->SaveToFile( cfg );
1373 CFGList::iterator it_b = s_MiscList.begin();
1374 for ( ; it_b != s_MiscList.end(); ++it_b )
1375 (*it_b)->SaveToFile( cfg );
1378 // Save debug-categories
1379 #ifdef __DEBUG__
1380 int count = theLogger.GetDebugCategoryCount();
1382 for ( int i = 0; i < count; i++ ) {
1383 const CDebugCategory& cat = theLogger.GetDebugCategory( i );
1385 cfg->Write( wxT("/Debug/Cat_") + cat.GetName(), cat.IsEnabled() );
1387 #endif
1390 void CPreferences::SetMaxUpload(uint16 in)
1392 if ( s_maxupload != in ) {
1393 s_maxupload = in;
1395 // Ensure that the ratio is upheld
1396 CheckUlDlRatio();
1401 void CPreferences::SetMaxDownload(uint16 in)
1403 if ( s_maxdownload != in ) {
1404 s_maxdownload = in;
1406 // Ensure that the ratio is upheld
1407 CheckUlDlRatio();
1412 void CPreferences::UnsetAutoServerStart()
1414 s_autoserverlist = false;
1418 // Here we slightly limit the users' ability to be a bad citizen: for very low upload rates
1419 // we force a low download rate, so as to discourage this type of leeching.
1420 // We're Open Source, and whoever wants it can do his own mod to get around this, but the
1421 // packaged product will try to enforce good behavior.
1423 // Kry note: of course, any leecher mod will be banned asap.
1424 void CPreferences::CheckUlDlRatio()
1426 // Backwards compatibility
1427 if ( s_maxupload == 0xFFFF )
1428 s_maxupload = UNLIMITED;
1430 // Backwards compatibility
1431 if ( s_maxdownload == 0xFFFF )
1432 s_maxdownload = UNLIMITED;
1434 if ( s_maxupload == UNLIMITED )
1435 return;
1437 // Enforce the limits
1438 if ( s_maxupload < 4 ) {
1439 if ( ( s_maxupload * 3 < s_maxdownload ) || ( s_maxdownload == 0 ) )
1440 s_maxdownload = s_maxupload * 3 ;
1441 } else if ( s_maxupload < 10 ) {
1442 if ( ( s_maxupload * 4 < s_maxdownload ) || ( s_maxdownload == 0 ) )
1443 s_maxdownload = s_maxupload * 4;
1448 void CPreferences::Save()
1450 wxString fullpath(theApp->ConfigDir + wxT("preferences.dat"));
1452 CFile preffile;
1453 if (!wxFileExists(fullpath)) {
1454 preffile.Create(fullpath);
1457 if (preffile.Open(fullpath, CFile::read_write)) {
1458 try {
1459 preffile.WriteUInt8(PREFFILE_VERSION);
1460 preffile.WriteHash(s_userhash);
1461 } catch (const CIOFailureException& e) {
1462 AddDebugLogLineC(logGeneral, wxT("IO failure while saving user-hash: ") + e.what());
1466 SavePreferences();
1468 #ifndef CLIENT_GUI
1469 CTextFile sdirfile;
1470 if (sdirfile.Open(theApp->ConfigDir + wxT("shareddir.dat"), CTextFile::write)) {
1471 for (size_t i = 0; i < shareddir_list.size(); ++i) {
1472 sdirfile.WriteLine(CPath::ToUniv(shareddir_list[i]), wxConvUTF8);
1476 #endif
1480 CPreferences::~CPreferences()
1482 DeleteContents(m_CatList);
1486 int32 CPreferences::GetRecommendedMaxConnections()
1488 #ifndef CLIENT_GUI
1489 int iRealMax = PlatformSpecific::GetMaxConnections();
1490 if(iRealMax == -1 || iRealMax > 520) {
1491 return 500;
1493 if(iRealMax < 20) {
1494 return iRealMax;
1496 if(iRealMax <= 256) {
1497 return iRealMax - 10;
1499 return iRealMax - 20;
1500 #else
1501 return 500;
1502 #endif
1506 void CPreferences::SavePreferences()
1508 wxConfigBase* cfg = wxConfigBase::Get();
1510 cfg->Write( wxT("/eMule/AppVersion"), wxT(VERSION) );
1512 // Save the options
1513 SaveAllItems( cfg );
1515 // Ensure that the changes are saved to disk.
1516 cfg->Flush();
1520 void CPreferences::SaveCats()
1522 if ( GetCatCount() ) {
1523 wxConfigBase* cfg = wxConfigBase::Get();
1525 // Save the main cat.
1526 cfg->Write( wxT("/eMule/AllcatType"), (int)s_allcatFilter);
1528 // The first category is the default one and should not be counted
1530 cfg->Write( wxT("/General/Count"), (long)(m_CatList.size() - 1) );
1532 uint32 maxcat = m_CatList.size();
1533 for (uint32 i = 1; i < maxcat; i++) {
1534 cfg->SetPath(CFormat(wxT("/Cat#%i")) % i);
1536 cfg->Write( wxT("Title"), m_CatList[i]->title );
1537 cfg->Write( wxT("Incoming"), CPath::ToUniv(m_CatList[i]->path) );
1538 cfg->Write( wxT("Comment"), m_CatList[i]->comment );
1539 cfg->Write( wxT("Color"), wxString(CFormat(wxT("%u")) % m_CatList[i]->color));
1540 cfg->Write( wxT("Priority"), (int)m_CatList[i]->prio );
1542 // remove deleted cats from config
1543 while (cfg->DeleteGroup(CFormat(wxT("/Cat#%i")) % maxcat++)) {}
1545 cfg->Flush();
1550 void CPreferences::LoadPreferences()
1552 LoadCats();
1556 void CPreferences::LoadCats()
1558 // default cat ... Meow! =(^.^)=
1559 Category_Struct* defaultcat = new Category_Struct;
1560 defaultcat->prio = 0;
1561 defaultcat->color = 0;
1563 AddCat( defaultcat );
1565 wxConfigBase* cfg = wxConfigBase::Get();
1567 long max = cfg->Read( wxT("/General/Count"), 0l );
1569 for ( int i = 1; i <= max ; i++ ) {
1570 cfg->SetPath(CFormat(wxT("/Cat#%i")) % i);
1572 Category_Struct* newcat = new Category_Struct;
1574 newcat->title = cfg->Read( wxT("Title"), wxEmptyString );
1575 newcat->path = CPath::FromUniv(cfg->Read(wxT("Incoming"), wxEmptyString));
1577 // Some sanity checking
1578 if ( newcat->title.IsEmpty() || !newcat->path.IsOk() ) {
1579 AddLogLineN(_("Invalid category found, skipping"));
1581 delete newcat;
1582 continue;
1585 newcat->comment = cfg->Read( wxT("Comment"), wxEmptyString );
1586 newcat->prio = cfg->Read( wxT("Priority"), 0l );
1587 newcat->color = StrToULong(cfg->Read(wxT("Color"), wxT("0")));
1589 AddCat(newcat);
1591 if (!newcat->path.DirExists()) {
1592 CPath::MakeDir(newcat->path);
1598 uint16 CPreferences::GetDefaultMaxConperFive()
1600 return MAXCONPER5SEC;
1604 uint32 CPreferences::AddCat(Category_Struct* cat)
1606 m_CatList.push_back( cat );
1608 return m_CatList.size() - 1;
1612 void CPreferences::RemoveCat(size_t index)
1614 if ( index < m_CatList.size() ) {
1615 CatList::iterator it = m_CatList.begin() + index;
1617 delete *it;
1619 m_CatList.erase( it );
1621 // remove cat directory from shares
1622 theApp->sharedfiles->Reload();
1627 uint32 CPreferences::GetCatCount()
1629 return m_CatList.size();
1633 Category_Struct* CPreferences::GetCategory(size_t index)
1635 wxASSERT( index < m_CatList.size() );
1637 return m_CatList[index];
1641 const CPath& CPreferences::GetCatPath(uint8 index)
1643 wxASSERT( index < m_CatList.size() );
1645 return m_CatList[index]->path;
1649 uint32 CPreferences::GetCatColor(size_t index)
1651 wxASSERT( index < m_CatList.size() );
1653 return m_CatList[index]->color;
1656 bool CPreferences::CreateCategory(
1657 Category_Struct *& category,
1658 const wxString& name,
1659 const CPath& path,
1660 const wxString& comment,
1661 uint32 color,
1662 uint8 prio)
1664 category = new Category_Struct();
1665 category->path = thePrefs::GetIncomingDir(); // set a default in case path is invalid
1666 uint32 cat = AddCat(category);
1667 return UpdateCategory(cat, name, path, comment, color, prio);
1670 bool CPreferences::UpdateCategory(
1671 uint8 cat,
1672 const wxString& name,
1673 const CPath& path,
1674 const wxString& comment,
1675 uint32 color,
1676 uint8 prio)
1678 Category_Struct *category = m_CatList[cat];
1680 // return true if path is ok, false if not
1681 bool ret = true;
1682 if (!path.IsOk() || (!path.DirExists() && !CPath::MakeDir(path))) {
1683 ret = false;
1684 // keep path as it was
1685 } else if (category->path != path) {
1686 // path changed: reload shared files, adding files in the new path and removing those from the old path
1687 category->path = path;
1688 theApp->sharedfiles->Reload();
1690 category->title = name;
1691 category->comment = comment;
1692 category->color = color;
1693 category->prio = prio;
1695 SaveCats();
1696 return ret;
1700 wxString CPreferences::GetBrowser()
1702 wxString cmd(s_CustomBrowser);
1703 #ifndef __WXMSW__
1704 if( s_BrowserTab ) {
1705 // This is certainly not the best way to do it, but I'm lazy
1706 if ((wxT("mozilla") == cmd.Right(7)) || (wxT("firefox") == cmd.Right(7))
1707 || (wxT("MozillaFirebird") == cmd.Right(15))) {
1708 cmd += wxT(" -remote 'openURL(%s, new-tab)'");
1710 if ((wxT("galeon") == cmd.Right(6)) || (wxT("epiphany") == cmd.Right(8))) {
1711 cmd += wxT(" -n '%s'");
1713 if (wxT("opera") == cmd.Right(5)) {
1714 cmd += wxT(" --newpage '%s'");
1716 if (wxT("netscape") == cmd.Right(8)) {
1717 cmd += wxT(" -remote 'openURLs(%s,new-tab)'");
1720 #endif /* !__WXMSW__ */
1721 return cmd;
1724 void CPreferences::SetFilteringClients(bool val)
1726 if (val != s_IPFilterClients) {
1727 s_IPFilterClients = val;
1728 if (val) {
1729 theApp->clientlist->FilterQueues();
1734 void CPreferences::SetFilteringServers(bool val)
1736 if (val != s_IPFilterServers) {
1737 s_IPFilterServers = val;
1738 if (val) {
1739 theApp->serverlist->FilterServers();
1744 void CPreferences::SetIPFilterLevel(uint8 level)
1746 if (level != s_filterlevel) {
1747 // Set the new access-level
1748 s_filterlevel = level;
1749 #ifndef CLIENT_GUI
1750 // and reload the filter
1751 NotifyAlways_IPFilter_Reload();
1752 #endif
1756 void CPreferences::SetPort(uint16 val)
1758 // Warning: Check for +3, because server UDP is TCP+3
1760 if (val +3 > 65535) {
1761 AddLogLineC(_("TCP port can't be higher than 65532 due to server UDP socket being TCP+3"));
1762 AddLogLineN(CFormat(_("Default port will be used (%d)")) % DEFAULT_TCP_PORT);
1763 s_port = DEFAULT_TCP_PORT;
1764 } else {
1765 s_port = val;
1770 void CPreferences::ReloadSharedFolders()
1772 #ifndef CLIENT_GUI
1773 shareddir_list.clear();
1775 CTextFile file;
1776 if (file.Open(theApp->ConfigDir + wxT("shareddir.dat"), CTextFile::read)) {
1777 wxArrayString lines = file.ReadLines(txtReadDefault, wxConvUTF8);
1779 for (size_t i = 0; i < lines.size(); ++i) {
1780 CPath path = CPath::FromUniv(lines[i]);
1782 if (path.DirExists()) {
1783 shareddir_list.push_back(path);
1784 } else {
1785 AddLogLineN(CFormat(_("Dropping non-existing shared directory: %s")) % path.GetRaw());
1789 #endif
1793 bool CPreferences::IsMessageFiltered(const wxString& message)
1795 if (s_FilterAllMessages) {
1796 return true;
1797 } else {
1798 if (s_FilterSomeMessages) {
1799 if (s_MessageFilterString.IsSameAs(wxT("*"))){
1800 // Filter anything
1801 return true;
1802 } else {
1803 wxStringTokenizer tokenizer( s_MessageFilterString, wxT(",") );
1804 while (tokenizer.HasMoreTokens()) {
1805 if ( message.Lower().Trim(false).Trim(true).Contains(
1806 tokenizer.GetNextToken().Lower().Trim(false).Trim(true))) {
1807 return true;
1810 return false;
1812 } else {
1813 return false;
1819 bool CPreferences::IsCommentFiltered(const wxString& comment)
1821 if (s_FilterComments) {
1822 wxStringTokenizer tokenizer( s_CommentFilterString, wxT(",") );
1823 while (tokenizer.HasMoreTokens()) {
1824 if ( comment.Lower().Trim(false).Trim(true).Contains(
1825 tokenizer.GetNextToken().Lower().Trim(false).Trim(true))) {
1826 return true;
1830 return false;
1833 wxString CPreferences::GetLastHTTPDownloadURL(uint8 t)
1835 wxConfigBase* cfg = wxConfigBase::Get();
1836 wxString key = CFormat(wxT("/HTTPDownload/URL_%d")) % t;
1837 return cfg->Read(key, wxEmptyString);
1840 void CPreferences::SetLastHTTPDownloadURL(uint8 t, const wxString& val)
1842 wxConfigBase* cfg = wxConfigBase::Get();
1843 wxString key = CFormat(wxT("/HTTPDownload/URL_%d")) % t;
1844 cfg->Write(key, val);
1847 // File_checked_for_headers