Fix UI restore when window is resized while in loading screen
[ryzomcore.git] / ryzom / client / src / connection.cpp
blobce887e48ebc1e59337df98513502bb708a1f15f8
1 // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
2 // Copyright (C) 2010-2019 Winch Gate Property Limited
3 //
4 // This source file has been modified by the following contributors:
5 // Copyright (C) 2012 Matt RAYKOWSKI (sfb) <matt.raykowski@gmail.com>
6 // Copyright (C) 2013 Laszlo KIS-ADAM (dfighter) <dfighter1985@gmail.com>
7 // Copyright (C) 2014-2020 Jan BOON (Kaetemi) <jan.boon@kaetemi.be>
8 //
9 // This program is free software: you can redistribute it and/or modify
10 // it under the terms of the GNU Affero General Public License as
11 // published by the Free Software Foundation, either version 3 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 // GNU Affero General Public License for more details.
19 // You should have received a copy of the GNU Affero General Public License
20 // along with this program. If not, see <http://www.gnu.org/licenses/>.
25 //////////////
26 // Includes //
27 //////////////
28 #include "stdpch.h"
30 // Misc.
31 #include "nel/misc/i18n.h"
32 #include "nel/misc/path.h"
33 #include "nel/misc/time_nl.h"
34 #include "nel/misc/algo.h"
35 #include "nel/misc/system_utils.h"
36 // 3D Interface.
37 #include "nel/3d/u_driver.h"
38 #include "nel/3d/u_text_context.h"
39 #include "nel/3d/stereo_display.h"
40 // Game Share
41 //#include "game_share/gd_time.h" // \todo GUIGUI : TO DELETE/CHANGE
42 #include "game_share/gender.h"
43 #include "game_share/character_summary.h"
44 #include "game_share/roles.h"
45 #include "game_share/character_title.h"
46 #include "game_share/shard_names.h"
47 #include "game_share/utils.h"
48 #include "game_share/bg_downloader_msg.h"
50 // Std.
51 #include <vector>
52 // Client
53 #include "connection.h"
54 #include "nel/gui/action_handler.h"
55 #include "sound_manager.h"
56 #include "input.h"
57 #include "login.h"
58 #include "login_progress_post_thread.h"
60 #include "client_cfg.h"
61 #include "actions_client.h"
62 #include "user_entity.h"
63 #include "time_client.h"
64 #include "net_manager.h"
65 #include "string_manager_client.h"
66 #include "far_tp.h"
67 #include "movie_shooter.h"
69 // Interface part
70 #include "interface_v3/interface_manager.h"
71 #include "interface_v3/character_3d.h"
72 #include "nel/gui/ctrl_button.h"
73 #include "interface_v3/input_handler_manager.h"
74 #include "nel/gui/group_editbox.h"
75 #include "nel/gui/interface_expr.h"
76 #include "init_main_loop.h"
77 #include "continent_manager.h"
78 #include "interface_v3/group_quick_help.h"
79 #include "nel/gui/dbgroup_combo_box.h"
81 #include "r2/dmc/client_edition_module.h"
82 #include "r2/editor.h"
83 #include "game_share/scenario.h"
84 #include "session_browser_impl.h"
86 #include "bg_downloader_access.h"
87 #include "main_loop.h"
89 #include "misc.h"
92 ////////////////
93 // Namespaces //
94 ////////////////
95 using namespace NLMISC;
96 using namespace NL3D;
97 using namespace NLNET;
98 using namespace std;
99 using namespace RSMGR;
100 using namespace R2;
104 /////////////
105 // Externs //
106 /////////////
107 extern uint32 Version; // Client Version.
108 extern UDriver *Driver;
109 extern UTextContext *TextContext;
110 extern bool game_exit;
112 extern CSoundManager *SoundMngr;
114 extern bool serverReceivedReady;
115 extern CContinentManager ContinentMngr;
117 extern bool MovieShooterSaving;
118 extern void endMovieShooting();
119 extern void replayMovieShooting();
120 extern void saveMovieShooting();
121 extern void displaySpecialTextProgress(const char *text);
122 extern bool InitMouseWithCursor(bool hardware);
124 extern bool SetMousePosFirstTime;
126 /////////////
127 // Globals // initialization occurs in the function : connection
128 /////////////
129 bool userChar;
130 bool noUserChar;
131 bool ConnectInterf;
132 bool CreateInterf;
133 bool CharacterInterf;
134 TTime UniversalTime;
135 std::vector<CCharacterSummary> CharacterSummaries;
136 std::string UsedFSAddr;
137 std::string UserPrivileges;
138 uint8 ServerPeopleActive = 255;
139 uint8 ServerCareerActive = 255;
141 bool WaitServerAnswer;
142 bool CharNameValidArrived;
143 bool CharNameValid;
144 string CharNameValidDBLink;
145 uint8 PlayerSelectedSlot = 0;
146 string PlayerSelectedFileName;
147 TSessionId PlayerSelectedMainland= (TSessionId)0; // This is the mainland selected at the SELECT perso!!
148 std::string PlayerSelectedHomeShardName;
149 std::string PlayerSelectedHomeShardNameWithParenthesis;
150 extern std::string CurrentCookie;
152 std::string NewKeysCharNameWanted; // name of the character for which a new keyset must be created
153 std::string NewKeysCharNameValidated;
154 std::string GameKeySet = "keys.xml";
155 std::string RingEditorKeySet = "keys_r2ed.xml";
157 string ScenarioFileName;
158 sint LoginCharsel = -1;
160 std::string ImportCharacter;
162 static const char *KeySetVarName = "BuiltInKeySets";
164 #define GROUP_LIST_CHARACTER "ui:outgame:charsel_import:import_list"
165 #define GROUP_LIST_MAINLAND "ui:outgame:appear_mainland:mainland_list"
166 #define GROUP_LIST_KEYSET "ui:outgame:appear_keyset:keyset_list"
167 vector<CMainlandSummary> Mainlands;
168 TSessionId MainlandSelected = (TSessionId)0; // This is the mainland selected at the CREATE perso!!
170 // This is the home session (mainland) of the selected character
171 TSessionId CharacterHomeSessionId = (TSessionId)0;
174 bool PatchBegun = false;
176 // \todo GUIGUI : USE TRANSPORT CLASS.
177 // SVersionAnswer versionAnswer;
180 // Finite State Machine : all the states before entering the game
181 // ------------------------------------------------------------------------------------------------
182 TInterfaceState globalMenu();
185 bool hasPrivilegeDEV() { return (UserPrivileges.find(":DEV:") != std::string::npos); }
186 bool hasPrivilegeSGM() { return (UserPrivileges.find(":SGM:") != std::string::npos); }
187 bool hasPrivilegeGM() { return (UserPrivileges.find(":GM:") != std::string::npos); }
188 bool hasPrivilegeVG() { return (UserPrivileges.find(":VG:") != std::string::npos); }
189 bool hasPrivilegeSG() { return (UserPrivileges.find(":SG:") != std::string::npos); }
190 bool hasPrivilegeG() { return (UserPrivileges.find(":G:") != std::string::npos); }
191 bool hasPrivilegeEM() { return (UserPrivileges.find(":EM:") != std::string::npos); }
192 bool hasPrivilegeEG() { return (UserPrivileges.find(":EG:") != std::string::npos); }
195 // Restore the video mode (fullscreen for example) after the connection (done in a window)
196 void connectionRestoreVideoMode ()
198 // Setup full screen if we have to
199 UDriver::CMode mode;
200 Driver->getCurrentScreenMode(mode);
202 if (mode.Windowed)
204 uint32 width, height;
205 Driver->getWindowSize(width, height);
206 mode.Width = width;
207 mode.Height = height;
210 // don't allow sizes smaller than 1024x768
211 if (ClientCfg.Width < 1024) ClientCfg.Width = 1024;
212 if (ClientCfg.Height < 768) ClientCfg.Height = 768;
214 if (StereoDisplay)
215 StereoDisplayAttached = StereoDisplay->attachToDisplay();
217 if (!StereoDisplayAttached && (
218 (ClientCfg.Windowed != mode.Windowed) ||
219 (ClientCfg.Width != mode.Width) ||
220 (ClientCfg.Height != mode.Height)))
222 mode.Windowed = ClientCfg.Windowed;
223 mode.Depth = uint8(ClientCfg.Depth);
224 mode.Width = ClientCfg.Width;
225 mode.Height = ClientCfg.Height;
226 mode.Frequency = ClientCfg.Frequency;
227 setVideoMode(mode);
230 // And setup hardware mouse if we have to
231 InitMouseWithCursor (ClientCfg.HardwareCursor && !StereoDisplayAttached);
232 SetMouseFreeLook ();
233 SetMouseCursor ();
234 SetMouseSpeed (ClientCfg.CursorSpeed);
235 SetMouseAcceleration (ClientCfg.CursorAcceleration);
237 // Restore user UI scaling
238 CViewRenderer::getInstance()->setInterfaceScale(ClientCfg.InterfaceScale);
242 #define UI_VARIABLES_SCREEN_WEBSTART 8
245 // ***************************************************************************
246 // Called to reload the start test page in test browser mode
247 class CAHOnReloadTestPage: public IActionHandler
249 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
251 CInterfaceManager *pIM = CInterfaceManager::getInstance();
252 // need to reset password and current screen
253 CGroupHTML *pGH = dynamic_cast<CGroupHTML*>(CWidgetManager::getInstance()->getElementFromId(GROUP_BROWSER));
255 pGH->browse(ClientCfg.TestBrowserUrl.c_str());
259 REGISTER_ACTION_HANDLER (CAHOnReloadTestPage, "on_reload_test_page");
262 // ------------------------------------------------------------------------------------------------
263 void setOutGameFullScreen()
265 if (!ClientCfg.Local && ClientCfg.SelectCharacter == -1)
267 if (StereoDisplayAttached)
268 StereoDisplay->detachFromDisplay();
269 StereoDisplayAttached = false;
271 InitMouseWithCursor(ClientCfg.HardwareCursor && !StereoDisplayAttached);
274 // Enable auto scaling in login window
275 CViewRenderer::getInstance()->setInterfaceScale(1.0f, 1024, 768);
278 // ------------------------------------------------------------------------------------------------
279 class CSoundGlobalMenu
281 public:
282 CSoundGlobalMenu()
284 _MusicWantedAsync= false;
285 _NbFrameBeforeChange= NbFrameBeforeChangeMax;
287 void reset();
288 void setMusic(const string &music, bool async);
289 void updateSound();
290 private:
291 string _MusicPlayed;
292 string _MusicWanted;
293 bool _MusicWantedAsync;
294 sint _NbFrameBeforeChange;
295 enum {NbFrameBeforeChangeMax= 10};
298 void CSoundGlobalMenu::reset()
300 _MusicPlayed.clear();
301 _MusicWanted.clear();
304 void CSoundGlobalMenu::updateSound()
306 // **** update the music played
307 // The first music played is the music played at loading, before select char
308 if (_MusicPlayed.empty())
309 _MusicPlayed = toLowerAscii(LoadingMusic.empty() ? ClientCfg.StartMusic : LoadingMusic);
310 if (_MusicWanted.empty())
311 _MusicWanted = toLowerAscii(LoadingMusic.empty() ? ClientCfg.StartMusic : LoadingMusic);
313 // because music is changed when the player select other race for instance,
314 // wait the 3D to load (stall some secs)
316 // if the wanted music is the same as the one currently playing, just continue playing
317 if(_MusicPlayed!=_MusicWanted)
319 // wait nbFrameBeforeChangeMax before actually changing the music
320 _NbFrameBeforeChange--;
321 if(_NbFrameBeforeChange<=0)
323 _MusicPlayed= _MusicWanted;
324 // play the music
325 if (SoundMngr != NULL)
326 SoundMngr->playMusic(_MusicPlayed, 500, _MusicWantedAsync, true, true);
331 // **** update mngr
332 if (SoundMngr != NULL)
333 SoundMngr->update();
336 void CSoundGlobalMenu::setMusic(const string &music, bool async)
338 _MusicWanted= toLowerAscii(music);
339 _MusicWantedAsync= async;
340 // reset the counter
341 _NbFrameBeforeChange= NbFrameBeforeChangeMax;
343 static CSoundGlobalMenu SoundGlobalMenu;
346 // New version of the menu after the server connection
348 // If you add something in this function, check CFarTP,
349 // some kind of reinitialization might be useful over there.
350 // ------------------------------------------------------------------------------------------------
351 bool connection (const string &cookie, const string &fsaddr)
354 NLMISC::TTime connStart = ryzomGetLocalTime();
355 NLMISC::TTime connLast = connStart;
356 NLMISC::TTime connCurrent = connLast;
358 game_exit = false;
360 // set resolution from cfg after login
361 connectionRestoreVideoMode ();
363 // Preload continents
365 const string nmsg("Loading continents...");
366 ProgressBar.newMessage (ClientCfg.buildLoadingString(nmsg) );
367 ContinentMngr.preloadSheets();
369 connLast = connCurrent;
370 connCurrent = ryzomGetLocalTime();
371 nlinfo ("PROFILE: %d seconds (%d total) for Loading continents", (uint32)(connCurrent-connLast)/1000, (uint32)(connCurrent-connStart)/1000);
374 if (!fsaddr.empty () && !cookie.empty ())
376 // it means that we have a nel_launcher values, so we are online
377 ClientCfg.Local = 0;
378 nlinfo ("Using the nel launcher parameters '%s' '%s'", cookie.c_str (), fsaddr.c_str ());
381 CInterfaceManager *pIM = CInterfaceManager::getInstance();
383 // If the Client is in in Local Mode -> init the Time and return.
384 if (ClientCfg.Local)
386 #ifdef ENABLE_INCOMING_MSG_RECORDER
387 NetMngr.init("", "");
388 // Set the impulse callback.
389 NetMngr.setImpulseCallback (impulseCallBack);
390 // Set the database.
391 NetMngr.setDataBase (IngameDbMngr.getNodePtr());
392 // init the string manager cache.
393 STRING_MANAGER::CStringManagerClient::instance()->initCache("", ClientCfg.LanguageCode); // VOIR BORIS
394 #endif
395 return true;
398 ProgressBar.setFontFactor(1.0f);
400 // Init out game
401 setOutGameFullScreen();
403 string nmsg("Initializing outgame...");
404 ProgressBar.newMessage (ClientCfg.buildLoadingString(nmsg) );
405 pIM->initOutGame();
407 connLast = connCurrent;
408 connCurrent = ryzomGetLocalTime();
409 nlinfo ("PROFILE: %d seconds (%d total) for Initializing outgame", (uint32)(connCurrent-connLast)/1000, (uint32)(connCurrent-connStart)/1000);
411 // Init user interface
412 nmsg = "Initializing user interface...";
413 ProgressBar.newMessage (ClientCfg.buildLoadingString(nmsg) );
415 // Hide cursor for interface
416 //Driver->showCursor (false);
418 // Init global variables
419 userChar = false;
420 noUserChar = false;
421 ConnectInterf = true;
422 CreateInterf = true;
423 CharacterInterf = true;
424 WaitServerAnswer= false;
426 FarTP.setOutgame();
428 // Start the finite state machine
429 static bool firstConnection = true;
430 TInterfaceState InterfaceState = AUTO_LOGIN;
431 // TInterfaceState InterfaceState = firstConnection ? AUTO_LOGIN : GLOBAL_MENU;
432 /*if (!firstConnection)
434 noUserChar = userChar = false;
435 WaitServerAnswer = true;
438 NLGUI::CDBManager::getInstance()->getDbProp ("UI:CURRENT_SCREEN")->setValue32(ClientCfg.Local ? 6 : -1); // TMP TMP
439 IngameDbMngr.flushObserverCalls();
440 NLGUI::CDBManager::getInstance()->flushObserverCalls();
442 // Active inputs
443 Actions.enable(true);
444 EditActions.enable(true);
446 if (ClientCfg.SelectCharacter == -1)
448 // not initialized at login and remain hardware until here ...
450 // Re-initialise the mouse (will be now in hardware mode, if required)
451 //InitMouseWithCursor (ClientCfg.HardwareCursor && !StereoDisplayAttached); // the return value of enableLowLevelMouse() has already been tested at startup
453 // no ui init if character selection is automatic
454 //SetMouseFreeLook ();
455 //SetMouseCursor ();
456 SetMouseSpeed (ClientCfg.CursorSpeed);
457 SetMouseAcceleration (ClientCfg.CursorAcceleration);
459 NLGUI::CDBManager::getInstance()->getDbProp("UI:SELECTED_SLOT")->setValue32(ClientCfg.SelectedSlot);
460 PlayerSelectedSlot = ClientCfg.SelectedSlot;
463 connLast = connCurrent;
464 connCurrent = ryzomGetLocalTime();
465 nlinfo ("PROFILE: %d seconds (%d total) for Initializing user interface", (uint32)(connCurrent-connLast)/1000, (uint32)(connCurrent-connStart)/1000);
467 nlinfo ("PROFILE: %d seconds for connection", (uint32)(ryzomGetLocalTime ()-connStart)/1000);
469 // Init web box
471 // TMP TMP
472 if (ClientCfg.Local)
474 InterfaceState = GLOBAL_MENU;
477 // No loading music here, this is right before character selection, using the existing music
479 // Create the loading texture. We can't do that before because we need to add search path first.
480 beginLoading (LoadBackground);
481 UseEscapeDuringLoading = USE_ESCAPE_DURING_LOADING;
483 while ((InterfaceState != GOGOGO_IN_THE_GAME) && (InterfaceState != QUIT_THE_GAME))
485 switch (InterfaceState)
487 case AUTO_LOGIN:
488 InterfaceState = autoLogin (cookie, fsaddr, firstConnection);
489 break;
491 case GLOBAL_MENU:
492 if (!ClientCfg.Local)
494 if (ClientCfg.SelectCharacter == -1)
496 NLGUI::CDBManager::getInstance()->getDbProp ("UI:CURRENT_SCREEN")->setValue32(0); // 0 == select
499 InterfaceState = globalMenu();
500 break;
501 case GOGOGO_IN_THE_GAME:
502 break;
503 case QUIT_THE_GAME:
504 break;
508 firstConnection = false;
510 // Restore user UI scaling
511 CViewRenderer::getInstance()->setInterfaceScale(ClientCfg.InterfaceScale);
513 // Disable inputs
514 Actions.enable(false);
515 EditActions.enable(false);
517 // resetTextContext ("ingame.ttf", true);
518 resetTextContext ("ryzom.ttf", true);
520 if (InterfaceState == GOGOGO_IN_THE_GAME)
522 // set background downloader to 'paused' to ease loading of client
523 #ifdef RYZOM_BG_DOWNLOADER
524 pauseBGDownloader();
525 #endif
526 return true;
529 if (InterfaceState == QUIT_THE_GAME)
530 return false;
531 nlassert ((InterfaceState == GOGOGO_IN_THE_GAME) || (InterfaceState == QUIT_THE_GAME));
532 return true;
538 // Allow user to reselect character after the server reconnection
539 // ------------------------------------------------------------------------------------------------
540 bool reconnection()
543 game_exit = false;
545 setOutGameFullScreen();
547 // Preload continents
549 const string nmsg ("Loading continents...");
550 ProgressBar.newMessage (ClientCfg.buildLoadingString(nmsg) );
551 ContinentMngr.preloadSheets();
554 if (!fsaddr.empty () && !cookie.empty ())
556 // it means that we have a nel_launcher values, so we are online
557 ClientCfg.Local = 0;
558 nlinfo ("Using the nel launcher parameters '%s' '%s'", cookie.c_str (), fsaddr.c_str ());
561 // If the Client is in in Local Mode -> init the Time and return.
562 if (ClientCfg.Local)
564 #ifdef ENABLE_INCOMING_MSG_RECORDER
565 NetMngr.init("", "");
566 // Set the impulse callback.
567 NetMngr.setImpulseCallback (impulseCallBack);
568 // Set the database.
569 NetMngr.setDataBase (IngameDbMngr.getNodePtr());
570 // init the string manager cache.
571 STRING_MANAGER::CStringManagerClient::instance()->initCache("", ClientCfg.LanguageCode); // VOIR BORIS
572 #endif
573 connectionRestoreVideoMode ();
574 return true;
578 CInterfaceManager *pIM = CInterfaceManager::getInstance();
580 ProgressBar.setFontFactor(1.0f);
582 // Init out game
583 SoundGlobalMenu.reset();
584 pIM->initOutGame();
586 // Hide cursor for interface
587 Driver->showCursor (false);
589 // Init global variables
590 userChar = false;
591 noUserChar = false;
592 ConnectInterf = true;
593 CreateInterf = true;
594 CharacterInterf = true;
595 WaitServerAnswer= false;
597 FarTP.setOutgame();
599 if (SoundMngr)
600 SoundMngr->setupFadeSound(1.0f, 1.0f);
602 // these two globals sequence GlobalMenu to display the character select dialog
603 WaitServerAnswer = true;
604 userChar = true;
606 // Start the finite state machine
607 TInterfaceState InterfaceState = GLOBAL_MENU;
609 NLGUI::CDBManager::getInstance()->getDbProp ("UI:CURRENT_SCREEN")->setValue32(-1);
610 IngameDbMngr.flushObserverCalls();
611 NLGUI::CDBManager::getInstance()->flushObserverCalls();
613 // Active inputs
614 Actions.enable(true);
615 EditActions.enable(true);
617 if (ClientCfg.SelectCharacter == -1)
619 // Re-initialise the mouse (will be now in hardware mode, if required)
620 SetMousePosFirstTime = true;
621 InitMouseWithCursor (ClientCfg.HardwareCursor && !StereoDisplayAttached); // the return value of enableLowLevelMouse() has already been tested at startup
623 // no ui init if character selection is automatic
624 SetMouseFreeLook ();
625 SetMouseCursor ();
626 SetMouseSpeed (ClientCfg.CursorSpeed);
627 SetMouseAcceleration (ClientCfg.CursorAcceleration);
628 NLGUI::CDBManager::getInstance()->getDbProp("UI:SELECTED_SLOT")->setValue32(ClientCfg.SelectedSlot);
629 PlayerSelectedSlot = ClientCfg.SelectedSlot;
632 // we want the teleport graphics to display (not like in Server Hop mode)
633 // this also kicks the state machine to sendReady() so we stop spinning in farTPmainLoop
634 FarTP.setIngame();
636 // Not loading music here, this is before character selection, keep existing music
638 // Create the loading texture. We can't do that before because we need to add search path first.
639 beginLoading (LoadBackground);
640 UseEscapeDuringLoading = USE_ESCAPE_DURING_LOADING;
642 // character selection menu
643 while( InterfaceState == GLOBAL_MENU ) // != GOGOGO_IN_THE_GAME) && (InterfaceState != QUIT_THE_GAME))
645 if (ClientCfg.SelectCharacter == -1)
647 NLGUI::CDBManager::getInstance()->getDbProp ("UI:CURRENT_SCREEN")->setValue32(0); // 0 == select
649 InterfaceState = globalMenu();
652 // Restore user UI scaling
653 CViewRenderer::getInstance()->setInterfaceScale(ClientCfg.InterfaceScale);
655 // Disable inputs
656 Actions.enable(false);
657 EditActions.enable(false);
659 // resetTextContext ("ingame.ttf", true);
660 resetTextContext ("ryzom.ttf", true);
662 if (InterfaceState == GOGOGO_IN_THE_GAME)
664 #ifdef RYZOM_BG_DOWNLOADER
665 pauseBGDownloader();
666 #endif
667 return true;
669 if (InterfaceState == QUIT_THE_GAME)
670 return false;
671 nlassert ((InterfaceState == GOGOGO_IN_THE_GAME) || (InterfaceState == QUIT_THE_GAME));
672 return true;
675 // Automatic connection to the server, the user can't do anything
676 // ------------------------------------------------------------------------------------------------
677 TInterfaceState autoLogin (const string &cookie, const string &fsaddr, bool firstConnection)
679 noUserChar = userChar = false;
680 string defaultPort = string(":47851");
681 if(!fsaddr.empty())
683 // If we have a front end address from command line, use this one
684 UsedFSAddr = fsaddr;
685 if (UsedFSAddr.find(":") == string::npos)
687 UsedFSAddr += defaultPort;
690 else
692 // Otherwise, use the front end address from configfile
693 UsedFSAddr = ClientCfg.FSHost;
694 FSAddr = UsedFSAddr; // to be able to do /reconnect
695 LoginSM.pushEvent( CLoginStateMachine::ev_skip_all_login );
696 if (UsedFSAddr.find(":") == string::npos)
698 UsedFSAddr += defaultPort;
699 FSAddr += defaultPort; // to be able to do /reconnect
703 if (firstConnection)
704 NetMngr.init (cookie, UsedFSAddr);
706 // Connection
707 if (!ClientCfg.Local/*ace!ClientCfg.Light*/)
709 string result;
711 if (firstConnection)
713 NetMngr.connect (result);
715 if (!result.empty())
717 nlerror ("connection : %s.", result.c_str());
718 return QUIT_THE_GAME;
721 // Ok the client is connected
723 // Set the impulse callback.
724 NetMngr.setImpulseCallback (impulseCallBack);
725 // Set the database.
726 NetMngr.setDataBase (IngameDbMngr.getNodePtr());
728 // init the string manager cache.
729 STRING_MANAGER::CStringManagerClient::instance()->initCache(UsedFSAddr, ClientCfg.LanguageCode);
732 else
734 CCharacterSummary cs;
735 cs.Name = "babar";
736 //cs.Surname = "l'elephant";
737 cs.People = EGSPD::CPeople::Zorai;
738 cs.VisualPropA.PropertySubData.Sex = 0; // Male
739 //Deprecated
740 // cs.Role = ROLES::range_warrior;
741 // cs.Job = JOBS::CasterBuffer;
742 // cs.JobLevel = 16;
743 CharacterSummaries.push_back(cs);
745 cs.Name = "yeah";
746 //cs.Surname = "zeelot";
747 cs.People = EGSPD::CPeople::Matis;
748 cs.VisualPropA.PropertySubData.Sex = 1; // Female
749 //Deprecated
750 // cs.Role = ROLES::buffer_magician;
751 // cs.Job = JOBS::CasterHealer;
752 // cs.JobLevel = 8;
753 CharacterSummaries.push_back(cs);
755 userChar = true;
758 WaitServerAnswer = true;
760 return GLOBAL_MENU;
763 // ------------------------------------------------------------------------------------------------
764 void globalMenuMovieShooter()
767 if(MovieShooterSaving)
769 // Add the buffer frame to the movie.
770 if(!MovieShooter.addFrame(TimeInSec, Driver))
772 // Fail to add the frame => abort.
773 endMovieShooting();
775 else
777 // Ok, just add a display.
778 displaySpecialTextProgress("MovieShooting");
784 // ------------------------------------------------------------------------------------------------
785 // Build a valid PlayerName for file Save selection.
786 std::string buildPlayerNameForSaveFile(const std::string &playerNameIn)
788 // remove any shard name appended
789 string playerName = playerNameIn;
790 string::size_type pos = playerNameIn.find('(');
791 if(pos!=string::npos && pos>0)
793 playerName.resize(pos);
796 // replace any special ucchar with '_'
797 string ret;
798 ret.resize(playerName.size());
799 for(uint i=0;i<playerName.size();i++)
801 ucchar c= playerName[i];
802 if( (c>='A' && c<='Z') ||
803 (c>='a' && c<='z') ||
804 (c>='0' && c<='9') ||
805 (c=='_') )
807 ret[i]= tolower(c); // TODO: toLowerAscii
809 else
810 ret[i]= '_';
812 return ret;
816 #ifdef RYZOM_BG_DOWNLOADER
817 static bool LuaBGDSuccessFlag = true; // tmp, for debug
819 void updateBGDownloaderUI()
821 CInterfaceManager *im = CInterfaceManager::getInstance();
822 CBGDownloaderAccess &bgDownloader = CBGDownloaderAccess::getInstance();
823 bool bgWindowVisible = true;
824 if (im->isInGame())
826 static NLMISC::CRefPtr<CInterfaceElement> bgDownloaderWindow;
827 if (!bgDownloaderWindow)
829 bgDownloaderWindow = CWidgetManager::getInstance()->getElementFromId("ui:interface:bg_downloader");
831 bgWindowVisible = bgDownloaderWindow && bgDownloaderWindow->getActive();
833 bool prevSuccess = LuaBGDSuccessFlag;
834 if (isBGDownloadEnabled() && PatchBegun)
836 if (AvailablePatchs == 0)
838 if (LuaBGDSuccessFlag)
840 LuaBGDSuccessFlag = CLuaManager::getInstance().executeLuaScript("bgdownloader:setPatchSuccess()");
843 else
845 switch(bgDownloader.getLastTaskResult())
847 case BGDownloader::TaskResult_Unknown:
849 float progress = 0.f;
850 /*if (bgDownloader.getTotalSize() != 0)
852 progress = (float) bgDownloader.getPatchingSize() / bgDownloader.getTotalSize();
854 if (bgDownloader.getTotalFilesToGet() != 0)
856 progress = (bgDownloader.getCurrentFilesToGet() + bgDownloader.getCurrentFileProgress()) / bgDownloader.getTotalFilesToGet();
858 if (LuaBGDSuccessFlag && bgWindowVisible)
860 LuaBGDSuccessFlag = CLuaManager::getInstance().executeLuaScript(toString("bgdownloader:setPatchProgress(%f)", progress));
862 // display current priority of the downloader
863 if (LuaBGDSuccessFlag && bgWindowVisible)
865 LuaBGDSuccessFlag = CLuaManager::getInstance().executeLuaScript("bgdownloader:displayPriority()");
868 break;
869 case BGDownloader::TaskResult_Success:
870 if (LuaBGDSuccessFlag && bgWindowVisible)
872 LuaBGDSuccessFlag = CLuaManager::getInstance().executeLuaScript("bgdownloader:setPatchSuccess()");
874 // task finished
875 AvailablePatchs = 0;
876 if (bgDownloader.getPatchCompletionFlag(true /* clear flag */))
878 // when in-game, display a message to signal the end of the patch
879 if (im->isInGame())
881 im->displaySystemInfo(CI18N::get("uiBGD_InGamePatchCompletion"), "BC");
884 break;
885 default:
886 // error case
887 if (LuaBGDSuccessFlag && bgWindowVisible)
889 LuaBGDSuccessFlag = CLuaManager::getInstance().executeLuaScript("bgdownloader:setPatchError()");
891 break;
895 else
897 if (LuaBGDSuccessFlag && bgWindowVisible)
899 if (isBGDownloadEnabled())
901 // no necessary patch for now
902 LuaBGDSuccessFlag = CLuaManager::getInstance().executeLuaScript("bgdownloader:setNoNecessaryPatch()");
904 else
906 // no download ui
907 LuaBGDSuccessFlag = CLuaManager::getInstance().executeLuaScript("bgdownloader:setNoDownloader()");
911 if (prevSuccess != LuaBGDSuccessFlag)
913 nlwarning("Some scipt error occurred");
916 #endif
918 // compute patcher priority, depending on the presence of one or more mainland characters : in this case, give the patch a boost
919 void updatePatcherPriorityBasedOnCharacters()
921 #ifdef RYZOM_BG_DOWNLOADER
922 if (isBGDownloadEnabled())
924 if (CBGDownloaderAccess::getInstance().getDownloadThreadPriority() != BGDownloader::ThreadPriority_Paused)
926 // choose priority based on available characters :
927 bool hasMainlandChar = false;
928 for(std::vector<CCharacterSummary>::iterator it = CharacterSummaries.begin(); it != CharacterSummaries.end(); ++it)
930 if (it->Name.empty()) continue;
931 if (!it->InNewbieland)
933 hasMainlandChar = true;
934 break;
937 CBGDownloaderAccess::getInstance().requestDownloadThreadPriority(hasMainlandChar ? BGDownloader::ThreadPriority_Normal : BGDownloader::ThreadPriority_Low, false);
940 #endif
943 // Launch the interface to choose a character
944 // ------------------------------------------------------------------------------------------------
945 TInterfaceState globalMenu()
947 CLoginProgressPostThread::getInstance().step(CLoginStep(LoginStep_CharacterSelection, "login_step_character_selection"));
949 #ifdef RYZOM_BG_DOWNLOADER
950 CBGDownloaderAccess &bgDownloader = CBGDownloaderAccess::getInstance();
952 if (isBGDownloadEnabled())
954 // If there's a need for mainland download, then proceed
955 if (AvailablePatchs & (1 << BGDownloader::DownloadID_MainLand))
957 // if a task is already started, then this was a situation where player went back from game to the character selection,
958 // so just unpause
959 BGDownloader::TTaskResult dummyResult;
960 ucstring dummyMessage; // OLD
961 if (!bgDownloader.isTaskEnded(dummyResult, dummyMessage))
963 unpauseBGDownloader();
967 #endif
969 CInterfaceManager *pIM = CInterfaceManager::getInstance();
971 sint32 nScreenConnecting, nScreenIntro, nScreenServerCrashed;
972 fromString(CWidgetManager::getInstance()->getParser()->getDefine("screen_connecting"), nScreenConnecting);
973 fromString(CWidgetManager::getInstance()->getParser()->getDefine("screen_intro"), nScreenIntro);
974 fromString(CWidgetManager::getInstance()->getParser()->getDefine("screen_crashing"), nScreenServerCrashed);
976 // SKIP INTRO : Write to the database if we have to skip the intro and write we want to skip further intro to client cfg
977 if (ClientCfg.SkipIntro)
979 CCDBNodeLeaf *pNL = NLGUI::CDBManager::getInstance()->getDbProp("UI:TEMP:SKIP_INTRO", false);
980 if (pNL != NULL)
981 pNL->setValue64(1);
984 TGameCycle serverTick = NetMngr.getCurrentServerTick();
985 bool PlayerWantToGoInGame = false;
986 bool firewallTimeout = false;
988 ProgressBar.finish(); // no progress while selecting character
990 while (PlayerWantToGoInGame == false)
993 #if defined(NL_OS_WINDOWS) && defined(NL_DEBUG) && 0
994 // tmp for debug
995 if (::GetAsyncKeyState(VK_SPACE))
997 pIM->uninitOutGame();
998 pIM->initOutGame();
999 CWidgetManager::getInstance()->activateMasterGroup ("ui:outgame", true);
1000 NLGUI::CDBManager::getInstance()->getDbProp ("UI:CURRENT_SCREEN")->setValue32(2); // TMP TMP
1001 IngameDbMngr.flushObserverCalls();
1002 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1003 CWidgetManager::getInstance()->getElementFromId("ui:outgame:charsel")->setActive(false);
1004 CWidgetManager::getInstance()->getElementFromId("ui:outgame:charsel")->setActive(true);
1005 // Active inputs
1006 Actions.enable(true);
1007 EditActions.enable(true);
1008 LuaBGDSuccessFlag = true;
1009 CWidgetManager::getInstance()->getParser()->reloadAllLuaFileScripts();
1011 #endif
1013 #ifdef RYZOM_BG_DOWNLOADER
1014 updateBGDownloaderUI();
1015 #endif
1017 // Update network.
1020 if ( ! firewallTimeout )
1021 NetMngr.update();
1023 catch (const EBlockedByFirewall&)
1025 if ( NetMngr.getConnectionState() == CNetManager::Disconnect )
1027 firewallTimeout = true;
1029 else
1031 // Display the firewall alert string
1032 CViewText *pVT = dynamic_cast<CViewText*>(CWidgetManager::getInstance()->getElementFromId("ui:outgame:connecting:title"));
1033 if (pVT != NULL)
1034 pVT->setTextLocalized("uiFirewallAlert", true);
1036 // The mouse and fullscreen mode should be unlocked for the user to set the firewall permission
1037 nlSleep( 30 ); // 'nice' the client, and prevent to make too many send attempts
1041 IngameDbMngr.flushObserverCalls();
1042 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1044 // check if we can send another dated block
1045 if (NetMngr.getCurrentServerTick() != serverTick)
1048 serverTick = NetMngr.getCurrentServerTick();
1049 NetMngr.send(serverTick);
1051 else
1053 // Send dummy info
1054 NetMngr.send();
1056 // Update the DT T0 and T1 global variables
1057 updateClientTime();
1058 CInputHandlerManager::getInstance()->pumpEvents();
1059 Driver->clearBuffers(CRGBA::Black);
1060 Driver->setMatrixMode2D11();
1062 // Update sound
1063 SoundGlobalMenu.updateSound();
1065 // Interface handling & displaying (processes clicks...)
1066 pIM->updateFrameEvents();
1067 pIM->updateFrameViews(NULL);
1068 IngameDbMngr.flushObserverCalls();
1069 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1071 // Movie shooter
1072 globalMenuMovieShooter();
1074 // Force the client to sleep a bit.
1075 if(ClientCfg.Sleep >= 0)
1077 nlSleep(ClientCfg.Sleep);
1080 #if defined(NL_OS_WINDOWS) && defined(NL_DEBUG) && 0
1081 if (::GetAsyncKeyState(VK_CONTROL))
1083 pIM->displayUIViewBBoxs("");
1084 pIM->displayUICtrlBBoxs("");
1085 pIM->displayUIGroupBBoxs("");
1086 displayDebugUIUnderMouse();
1088 #endif
1090 // Display
1091 Driver->swapBuffers();
1093 // SERVER INTERACTIONS WITH INTERFACE
1094 if (WaitServerAnswer)
1096 if (noUserChar || userChar)
1098 #ifdef RYZOM_BG_DOWNLOADER
1099 if (isBGDownloadEnabled())
1101 // If there's a need for mainland download, then proceed
1102 if (AvailablePatchs & (1 << BGDownloader::DownloadID_MainLand))
1104 // if a task is already started, then this was a situation where player went back from game to the character selection,
1105 // so just unpause
1106 BGDownloader::TTaskResult dummyResult;
1107 ucstring dummyMessage; // OLD
1108 if (bgDownloader.isTaskEnded(dummyResult, dummyMessage))
1110 // launch mainland patch as a background task
1111 BGDownloader::CTaskDesc task(BGDownloader::DLState_GetAndApplyPatch,
1112 (1 << BGDownloader::DownloadID_MainLand));
1113 bgDownloader.startTask(task, getBGDownloaderCommandLine(), false /* showDownloader */);
1115 // choose priority based on available characters :
1116 updatePatcherPriorityBasedOnCharacters();
1118 PatchBegun = true;
1122 #endif
1124 //nlinfo("impulseCallBack : received userChars list");
1125 noUserChar = userChar = false;
1126 if( FarTP.isReselectingChar() || !FarTP.isServerHopInProgress() ) // if doing a Server Hop, expect serverReceivedReady without action from the user
1128 sint charSelect = -1;
1129 if (ClientCfg.SelectCharacter != -1)
1130 charSelect = ClientCfg.SelectCharacter;
1132 if (LoginCharsel != -1)
1133 charSelect = LoginCharsel;
1135 WaitServerAnswer = false;
1136 if (charSelect == -1)
1138 CCDBNodeLeaf *pNL = NLGUI::CDBManager::getInstance()->getDbProp("UI:SERVER_RECEIVED_CHARS", false);
1139 if (pNL != NULL)
1141 pNL->setValue64 (1); // Send impulse to interface observers
1142 IngameDbMngr.flushObserverCalls();
1143 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1144 pNL->setValue64 (0);
1145 IngameDbMngr.flushObserverCalls();
1146 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1149 else
1151 // check that the pre selected character is available
1152 if (CharacterSummaries[charSelect].People == EGSPD::CPeople::Unknown || charSelect > 4)
1154 // BAD ! preselected char does not exist, use the first available or fail
1155 uint i;
1156 for (i=0; i<CharacterSummaries.size(); ++i)
1158 if (CharacterSummaries[i].People != EGSPD::CPeople::Unknown)
1159 break;
1161 if (i == CharacterSummaries.size())
1163 Driver->systemMessageBox("You have no character for the current user.\nClient will exit.", "Char loading error", UDriver::okType, UDriver::exclamationIcon);
1164 exit(-1);
1166 else
1168 UDriver::TMessageBoxId ret = Driver->systemMessageBox("The pre-selected character doesn't exist.\nDo you want to use the first available character instead ?", "Char loading error", UDriver::yesNoType, UDriver::warningIcon);
1169 if (ret == UDriver::noId)
1170 exit(-1);
1171 else
1172 charSelect = i;
1175 // Auto-selection for fast launching (dev only)
1176 CAHManager::getInstance()->runActionHandler("launch_game", NULL, toString("slot=%d|edit_mode=0", charSelect));
1178 if (LoginCharsel == -1)
1179 ClientCfg.SelectCharacter = charSelect;
1184 // Clear sending buffer that may contain prevous QUIT_GAME when getting back to the char selection screen
1185 NetMngr.flushSendBuffer();
1188 if (CharNameValidArrived)
1190 //nlinfo("impulseCallBack : received CharNameValidArrived");
1191 CharNameValidArrived = false;
1192 WaitServerAnswer = false;
1193 if (ClientCfg.SelectCharacter == -1)
1195 CCDBNodeLeaf *pNL;
1196 pNL = NLGUI::CDBManager::getInstance()->getDbProp(CharNameValidDBLink,false);
1197 if (pNL != NULL)
1199 if (CharNameValid)
1200 pNL->setValue64(1);
1201 else
1202 pNL->setValue64(0);
1205 pNL = NLGUI::CDBManager::getInstance()->getDbProp("UI:SERVER_RECEIVED_VALID", false);
1206 if (pNL != NULL)
1208 pNL->setValue64 (1); // Send impulse to interface observers
1209 IngameDbMngr.flushObserverCalls();
1210 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1211 pNL->setValue64 (0);
1212 IngameDbMngr.flushObserverCalls();
1213 NLGUI::CDBManager::getInstance()->flushObserverCalls();
1218 if (serverReceivedReady)
1220 //nlinfo("impulseCallBack : received serverReceivedReady");
1221 serverReceivedReady = false;
1222 WaitServerAnswer = false;
1223 PlayerWantToGoInGame = true;
1226 else
1228 noUserChar = false;
1229 userChar = false;
1230 CharNameValidArrived = false;
1231 serverReceivedReady = false;
1234 // Check if server disconnect the client
1235 if (!ClientCfg.Local)
1237 if (NetMngr.getConnectionState() == CNetManager::Disconnect)
1239 // Display the connection failure screen
1240 CCDBNodeLeaf *pNL = NLGUI::CDBManager::getInstance()->getDbProp("UI:CURRENT_SCREEN", false);
1241 if (pNL != NULL)
1242 pNL->setValue64 (nScreenServerCrashed);
1244 if ( firewallTimeout )
1246 // Display the firewall error string instead of the normal failure string
1247 CViewText *pVT = dynamic_cast<CViewText*>(CWidgetManager::getInstance()->getElementFromId("ui:outgame:crashing:title"));
1248 if (pVT != NULL)
1250 pVT->setMultiLine( true );
1251 pVT->setTextLocalized(CI18N::get("uiFirewallFail")+".\n"+
1252 CI18N::get("uiFirewallAlert")+".", false);
1260 // We want to quit the game without playing
1261 if (game_exit)
1262 return QUIT_THE_GAME;
1265 if (ClientCfg.SelectCharacter != -1)
1266 PlayerSelectedSlot = ClientCfg.SelectCharacter;
1268 // Notify the state machine that we're exiting from global menu
1269 LoginSM.pushEvent(CLoginStateMachine::ev_global_menu_exited);
1271 // Init the current Player Name (for interface.cfg and sentence.name save). Make a good File Name.
1272 string playerName = CharacterSummaries[PlayerSelectedSlot].Name.toUtf8();
1273 PlayerSelectedFileName = buildPlayerNameForSaveFile(playerName);
1275 // Init the current Player Home shard Id and name
1276 CharacterHomeSessionId = CharacterSummaries[PlayerSelectedSlot].Mainland;
1277 PlayerSelectedMainland= CharacterSummaries[PlayerSelectedSlot].Mainland;
1278 PlayerSelectedHomeShardName.clear();
1279 PlayerSelectedHomeShardNameWithParenthesis.clear();
1280 for(uint i=0;i<CShardNames::getInstance().getSessionNames().size();i++)
1282 const CShardNames::TSessionName &sessionName= CShardNames::getInstance().getSessionNames()[i];
1283 if(PlayerSelectedMainland == sessionName.SessionId)
1285 PlayerSelectedHomeShardName= sessionName.DisplayName;
1286 PlayerSelectedHomeShardNameWithParenthesis= '(' + PlayerSelectedHomeShardName + ')';
1291 // Restore video mode
1292 if (ClientCfg.SelectCharacter == -1)
1293 connectionRestoreVideoMode ();
1295 // Skip intro next time
1296 ClientCfg.writeBool("SkipIntro", true);
1298 // return SELECT_CHARACTER;
1299 return GOGOGO_IN_THE_GAME;
1303 // Init the character selection slot texts from the character summaries
1304 // ------------------------------------------------------------------------------------------------
1305 class CAHNetInitCharSel : public IActionHandler
1307 public:
1308 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
1310 string sPath = getParam(Params, "slottexts");
1311 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1312 uint i;
1313 for (i = 0; i < CharacterSummaries.size(); ++i)
1315 CCharacterSummary &rCS = CharacterSummaries[i];
1316 CInterfaceElement *pIE = CWidgetManager::getInstance()->getElementFromId(sPath+":text"+NLMISC::toString(i));
1317 CViewText *pVT = dynamic_cast<CViewText*>(pIE);
1318 if (pVT == NULL) return;
1320 if (rCS.Name.empty())
1321 pVT->setTextLocalized("uiEmptySlot", true);
1322 else
1323 pVT->setTextLocalized(rCS.Name.toUtf8(), false);
1325 // 5 slots
1326 for (; i < 5; ++i)
1328 CViewText *pVT = dynamic_cast<CViewText*>(CWidgetManager::getInstance()->getElementFromId(sPath+":text"+NLMISC::toString(i)));
1329 if (pVT == NULL) return;
1330 pVT->setTextLocalized("uiEmptySlot", true);
1334 REGISTER_ACTION_HANDLER (CAHNetInitCharSel, "net_init_char_sel");
1336 // ------------------------------------------------------------------------------------------------
1337 void setTarget(CCtrlBase *ctrl, const string &targetName, std::string &value)
1339 std::vector<CInterfaceLink::CTargetInfo> targets;
1340 // find first enclosing group
1341 CCtrlBase *currCtrl = ctrl;
1342 CInterfaceGroup *ig = NULL;
1343 while (currCtrl)
1345 ig = dynamic_cast<CInterfaceGroup *>(currCtrl);
1346 if (ig != NULL) break;
1347 currCtrl = currCtrl->getParent();
1349 if (ig)
1351 CInterfaceExprValue exprValue;
1352 exprValue.setString(value);
1354 CInterfaceLink::splitLinkTargets(targetName, ig, targets);
1355 for(uint k = 0; k < targets.size(); ++k)
1357 if (targets[k].Elem) targets[k].affect(exprValue);
1362 // ------------------------------------------------------------------------------------------------
1363 void setTarget(CCtrlBase *ctrl, const string &targetName, uint32 value)
1365 std::vector<CInterfaceLink::CTargetInfo> targets;
1366 // find first enclosing group
1367 CCtrlBase *currCtrl = ctrl;
1368 CInterfaceGroup *ig = NULL;
1369 while (currCtrl)
1371 ig = dynamic_cast<CInterfaceGroup *>(currCtrl);
1372 if (ig != NULL) break;
1373 currCtrl = currCtrl->getParent();
1375 if (ig)
1377 CInterfaceExprValue exprValue;
1378 exprValue.setInteger(value);
1380 CInterfaceLink::splitLinkTargets(targetName, ig, targets);
1381 for(uint k = 0; k < targets.size(); ++k)
1383 if (targets[k].Elem) targets[k].affect(exprValue);
1388 // ------------------------------------------------------------------------------------------------
1389 class CAHGetSlot: public IActionHandler
1391 public:
1392 virtual void execute (CCtrlBase *pCaller, const string &Params)
1394 string sProp = getParam(Params, "prop");
1395 string sTarget = getParam(Params, "target");
1396 string sSlot = getParam(Params, "slot");
1398 CInterfaceExprValue result;
1399 if (!CInterfaceExpr::eval(sSlot, result))
1400 return;
1401 uint8 selectedSlot = (uint8)result.getInteger();
1402 if (selectedSlot >= CharacterSummaries.size())
1403 return;
1405 PlayerSelectedSlot = selectedSlot;
1407 if (CharacterSummaries[PlayerSelectedSlot].Name.empty())
1408 return;
1410 string sValue;
1411 uint32 nValue = 0;
1413 if (sProp == "name")
1415 sValue = CharacterSummaries[PlayerSelectedSlot].Name.toUtf8();
1416 setTarget (pCaller, sTarget, sValue);
1418 /* else if (sProp == "surname")
1419 Deprecated {
1420 sValue = CharacterSummaries[PlayerSelectedSlot].Surname;
1421 setTarget (pCaller, sTarget, sValue);
1423 */ else if (sProp == "title")
1425 bool womanTitle;
1426 if( CharacterSummaries[PlayerSelectedSlot].VisualPropA.PropertySubData.Sex == 1 )
1428 UserEntity->setGender( GSGENDER::female );
1429 womanTitle = true;
1431 else
1433 UserEntity->setGender( GSGENDER::male );
1434 womanTitle = false;
1436 string titleStr = CHARACTER_TITLE::toString(CharacterSummaries[PlayerSelectedSlot].Title);
1437 sValue = STRING_MANAGER::CStringManagerClient::getTitleLocalizedName(titleStr, womanTitle);
1439 // Sometimes translation contains another title
1440 string::size_type pos = sValue.find('$');
1441 if (pos != string::npos)
1443 sValue = STRING_MANAGER::CStringManagerClient::getTitleLocalizedName(CEntityCL::getTitleFromName(sValue), womanTitle);
1446 setTarget (pCaller, sTarget, sValue);
1448 /* else if (sProp == "orient")
1449 Deprecated {
1450 sValue = ROLES::roleToUCString(CharacterSummaries[PlayerSelectedSlot].Role);
1451 setTarget (pCaller, sTarget, sValue);
1453 else if (sProp == "job")
1455 //Deprecated
1456 // sValue = JOBS::jobToUCString(CharacterSummaries[PlayerSelectedSlot].Job);
1457 sValue = JOBS::jobToUCString(JOBS::BladeBearer);
1458 setTarget (pCaller, sTarget, sValue);
1460 */ else if (sProp == "level")
1462 //Deprecated
1463 // sValue = toString(CharacterSummaries[PlayerSelectedSlot].JobLevel);
1464 sValue = toString(1);
1465 setTarget (pCaller, sTarget, sValue);
1467 else if (sProp == "pos")
1469 nValue = CharacterSummaries[PlayerSelectedSlot].Location;
1470 setTarget (pCaller, sTarget, nValue);
1474 REGISTER_ACTION_HANDLER (CAHGetSlot, "get_slot");
1477 // Setup the database from a database entry which represents a slot
1478 // ------------------------------------------------------------------------------------------------
1479 class CAHSetDBFromSlot : public IActionHandler
1481 public:
1482 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
1484 string sDBLink = getParam(Params, "dblink");
1485 string sSlot = getParam(Params, "slot");
1487 CInterfaceExprValue result;
1488 if (!CInterfaceExpr::eval(sSlot, result))
1489 return;
1491 PlayerSelectedSlot = (uint8)result.getInteger();
1493 if (PlayerSelectedSlot >= CharacterSummaries.size())
1494 return;
1496 // Setup the database from the character summary
1497 CCharacterSummary &rCS = CharacterSummaries[PlayerSelectedSlot];
1498 if (rCS.Name.empty())
1499 return;
1501 SCharacter3DSetup::setupDBFromCharacterSummary(sDBLink, rCS);
1504 REGISTER_ACTION_HANDLER (CAHSetDBFromSlot, "set_db_from_slot");
1507 // Reset all the pushed radio button of a group
1508 // ------------------------------------------------------------------------------------------------
1509 class CAHResetPushed: public IActionHandler
1511 public:
1512 virtual void execute (CCtrlBase *pCaller, const string &Params)
1514 string sDBLink = getParam(Params, "dblink");
1515 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1516 CInterfaceElement *pIE = CWidgetManager::getInstance()->getElementFromId(pCaller->getId(), sDBLink);
1517 CInterfaceGroup *pIG = dynamic_cast<CInterfaceGroup*>(pIE);
1518 if (pIG == NULL) return;
1520 const vector<CCtrlBase*> vCB = pIG->getControls();
1521 for (uint i = 0; i < vCB.size(); ++i)
1523 CCtrlBaseButton *pBut = dynamic_cast<CCtrlBaseButton*>(vCB[i]);
1524 if (pBut && pBut->getType() == CCtrlBaseButton::RadioButton)
1526 pBut->setPushed (false);
1531 REGISTER_ACTION_HANDLER (CAHResetPushed, "reset_pushed");
1537 // Launch the game given a slot (slot is reference to the character summaries
1538 // ------------------------------------------------------------------------------------------------
1539 class CAHLaunchGame : public IActionHandler
1541 public:
1542 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
1544 // Get the edit/play mode
1545 string sEditMode = getParam(Params, "edit_mode");
1546 bool wantsEditMode = false;
1547 CInterfaceExprValue result;
1548 bool wantsNewScenario = false;
1550 if (CInterfaceExpr::eval(sEditMode, result))
1552 wantsEditMode = (result.getInteger() == 1) || (result.getInteger() == 2);
1553 wantsNewScenario = (result.getInteger() == 2);
1556 CInterfaceManager *im = CInterfaceManager::getInstance();
1557 if (wantsEditMode)
1559 // full patch needed for edition, warn the client
1560 if (AvailablePatchs != 0)
1562 if (im->isInGame())
1564 inGamePatchUncompleteWarning();
1566 else
1568 im->messageBoxWithHelp(CI18N::get("uiBGD_FullPatchNeeded"), "ui:outgame");
1570 return;
1574 // Get the player selected slot
1575 string sSlot = getParam(Params, "slot");
1576 if (sSlot != "ingame_auto")
1578 CInterfaceExprValue result;
1579 if (!CInterfaceExpr::eval(sSlot, result))
1580 return;
1581 PlayerSelectedSlot = (uint8)result.getInteger();
1582 if (PlayerSelectedSlot >= CharacterSummaries.size())
1583 return;
1585 ClientCfg.writeInt("SelectedSlot",PlayerSelectedSlot);
1586 if (ClientCfg.SaveConfig)
1587 ClientCfg.ConfigFile.save();
1592 static volatile bool isMainlandCharacter = false; // TMP until we can get this info
1593 if (isMainlandCharacter)
1595 nlassert(0); // use id="message_box" !!!
1596 if (AvailablePatchs != 0)
1598 im->messageBoxWithHelp(CI18N::get("uiBGD_MainlandCharFullPatchNeeded"), "ui:outgame");
1600 return;
1605 // Select the right sheet to create the user character.
1606 ClientCfg.UserSheet = CharacterSummaries[PlayerSelectedSlot].SheetId.toString();
1608 // If the user wants to enter its editing session, get the ring server to Far TP to.
1609 if (wantsEditMode)
1612 if (wantsNewScenario)
1614 CSessionBrowserImpl &sb = CSessionBrowserImpl::getInstance();
1615 sb.init(NULL);
1616 sb.closeEditSession(sb.getCharId());
1617 sb.waitOneMessage(CSessionBrowserImpl::getMessageName("on_invokeResult"));
1619 if (FarTP.requestFarTPToSession( (TSessionId)0, PlayerSelectedSlot, CFarTP::LaunchEditor, false ))
1621 WaitServerAnswer = true; // prepare to receive the character messages
1624 // // If the player clicked 'Launch Editor', there was no CONNECTION:SELECT_CHAR sent yet,
1625 // // so don't wait for the EGS to acknowledge our quit message as he does not know our character
1626 // LoginSM.pushEvent(CLoginStateMachine::ev_ingame_return);
1628 return;
1631 // Send CONNECTION:SELECT_CHAR
1632 CBitMemStream out;
1633 nlverify( GenericMsgHeaderMngr.pushNameToStream ("CONNECTION:SELECT_CHAR", out) );
1634 //nlinfo("impulseCallBack : CONNECTION:SELECT_CHAR '%d' sent.", PlayerSelectedSlot);
1637 CSelectCharMsg SelectCharMsg;
1638 SelectCharMsg.c = (uint8)PlayerSelectedSlot;
1639 out.serial (SelectCharMsg);
1640 if (!ClientCfg.Local/*ace!ClientCfg.Light*/)
1642 NetMngr.push(out);
1643 NetMngr.send(NetMngr.getCurrentServerTick());
1646 //PlayerWantToGoInGame = true;
1648 // CBitMemStream out2;
1649 // if(GenericMsgHeaderMngr.pushNameToStream("CONNECTION:ENTER", out2))
1650 // {
1651 // NetMngr.push(out2);
1652 // nlinfo("impulseCallBack : CONNECTION:ENTER sent");
1653 // }
1654 // else
1655 // nlwarning("unknown message name : 'CONNECTION:ENTER'.");
1657 WaitServerAnswer = true;
1658 if (ClientCfg.Local)
1659 serverReceivedReady = true;
1662 REGISTER_ACTION_HANDLER (CAHLaunchGame, "launch_game");
1665 // Ask the server to create a character
1666 // ------------------------------------------------------------------------------------------------
1667 class CAHAskCreateChar : public IActionHandler
1669 public:
1670 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
1672 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1674 // Create the message for the server to create the character.
1675 CBitMemStream out;
1676 if (!GenericMsgHeaderMngr.pushNameToStream("CONNECTION:CREATE_CHAR", out))
1678 nlwarning ("don't know message name CONNECTION:CREATE_CHAR");
1679 return;
1682 // Setup the name
1683 string sEditBoxPath = getParam (Params, "name");
1684 string sFirstName = "NotSet";
1685 string sSurName = "NotSet";
1686 CGroupEditBox *pGEB = dynamic_cast<CGroupEditBox*>(CWidgetManager::getInstance()->getElementFromId(sEditBoxPath));
1687 if (pGEB != NULL)
1688 sFirstName = pGEB->getInputString();
1689 else
1690 nlwarning ("can't get edit box name : %s",sEditBoxPath.c_str());
1692 // Build the character summary from the database branch ui:temp:char3d
1693 CCharacterSummary CS;
1694 string sCharSumPath = getParam(Params, "charsum");
1695 SCharacter3DSetup::setupCharacterSummaryFromDB(CS, sCharSumPath);
1696 CS.Mainland = MainlandSelected;
1697 CS.Name = ucstring::makeFromUtf8(sFirstName); // FIXME: UTF-8 (serial)
1698 //CS.Surname = sSurName;
1700 // Create the message to send to the server from the character summary
1701 CCreateCharMsg CreateCharMsg;
1703 CreateCharMsg.setupFromCharacterSummary(CS);
1705 // Slot
1707 string sSlot = getParam(Params, "slot");
1709 CInterfaceExprValue result;
1710 if (!CInterfaceExpr::eval(sSlot, result))
1711 return;
1713 CreateCharMsg.Slot = (uint8)result.getInteger();
1715 NLGUI::CDBManager::getInstance()->getDbProp("UI:SELECTED_SLOT")->setValue32(PlayerSelectedSlot);
1718 // Setup the new career
1719 string sCaracBasePath = getParam (Params, "caracs");
1720 CreateCharMsg.NbPointFighter = (uint8)NLGUI::CDBManager::getInstance()->getDbProp(sCaracBasePath+"FIGHT")->getValue32();
1721 CreateCharMsg.NbPointCaster = (uint8)NLGUI::CDBManager::getInstance()->getDbProp(sCaracBasePath+"MAGIC")->getValue32();
1722 CreateCharMsg.NbPointCrafter = (uint8)NLGUI::CDBManager::getInstance()->getDbProp(sCaracBasePath+"CRAFT")->getValue32();
1723 CreateCharMsg.NbPointHarvester = (uint8)NLGUI::CDBManager::getInstance()->getDbProp(sCaracBasePath+"FORAGE")->getValue32();
1725 // Setup starting point
1726 string sLocationPath = getParam(Params, "loc");
1728 CreateCharMsg.StartPoint = RYZOM_STARTING_POINT::borea;
1730 CCDBNodeLeaf *pNL = NLGUI::CDBManager::getInstance()->getDbProp (sLocationPath, false);
1731 if (pNL != NULL)
1732 CreateCharMsg.StartPoint = (RYZOM_STARTING_POINT::TStartPoint)(pNL->getValue64());
1733 else
1734 nlwarning(("Can't read starting point from the database : " + sLocationPath).c_str());
1736 if (CS.People == EGSPD::CPeople::Fyros)
1737 CreateCharMsg.StartPoint= (RYZOM_STARTING_POINT::TStartPoint)(((uint8)CreateCharMsg.StartPoint) + ((uint8)RYZOM_STARTING_POINT::fyros_start));
1738 else if (CS.People == EGSPD::CPeople::Matis)
1739 CreateCharMsg.StartPoint= (RYZOM_STARTING_POINT::TStartPoint)(((uint8)CreateCharMsg.StartPoint) + ((uint8)RYZOM_STARTING_POINT::matis_start));
1740 else if (CS.People == EGSPD::CPeople::Tryker)
1741 CreateCharMsg.StartPoint= (RYZOM_STARTING_POINT::TStartPoint)(((uint8)CreateCharMsg.StartPoint) + ((uint8)RYZOM_STARTING_POINT::tryker_start));
1742 else // if (CS.People == EGSPD::CPeople::Zorai)
1743 CreateCharMsg.StartPoint= (RYZOM_STARTING_POINT::TStartPoint)(((uint8)CreateCharMsg.StartPoint) + ((uint8)RYZOM_STARTING_POINT::zorai_start));
1747 // Send the message to the server
1748 CreateCharMsg.serialBitMemStream (out);
1749 if (!ClientCfg.Local/*!ClientCfg.Light*/)
1751 noUserChar = userChar = false;
1753 NetMngr.push(out);
1754 NetMngr.send(NetMngr.getCurrentServerTick());
1756 //nlinfo("impulseCallBack : CONNECTION:CREATE_CHAR sent");
1757 CreateCharMsg.dump();
1759 else
1761 userChar = true;
1762 if (CharacterSummaries.size() < 5)
1763 CharacterSummaries.push_back(CS);
1765 WaitServerAnswer = true;
1768 REGISTER_ACTION_HANDLER (CAHAskCreateChar, "ask_create_char");
1772 // Ask the server to delete a character
1773 // ------------------------------------------------------------------------------------------------
1774 class CAHAskDeleteChar : public IActionHandler
1776 public:
1777 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
1779 // Create the message for the server to create the character.
1780 CBitMemStream out;
1781 if (!GenericMsgHeaderMngr.pushNameToStream("CONNECTION:DELETE_CHAR", out))
1783 nlwarning ("don't know message name CONNECTION:DELETE_CHAR");
1784 return;
1787 // Get the selected slot
1788 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1790 string sSlot = getParam(Params, "slot");
1792 CInterfaceExprValue result;
1793 if (!CInterfaceExpr::eval(sSlot, result))
1794 return;
1796 uint8 nSelectedSlot = (uint8)result.getInteger();
1797 if (nSelectedSlot >= CharacterSummaries.size())
1798 return;
1800 out.serial (nSelectedSlot);
1802 // Yoyo: delete the Local files. To avoid problem if recreate a character with same name.
1803 string playerName = CharacterSummaries[nSelectedSlot].Name.toUtf8();
1804 string playerDeletedFileName = buildPlayerNameForSaveFile(playerName);
1805 // Delete the 2 Local files
1806 pIM->deletePlayerConfig(playerDeletedFileName);
1807 pIM->deletePlayerKeys(playerDeletedFileName);
1809 // Send the message to the server
1810 if (!ClientCfg.Local/*ace!ClientCfg.Light*/)
1812 noUserChar = userChar = false;
1813 NetMngr.push(out);
1814 NetMngr.send(NetMngr.getCurrentServerTick());
1816 //nlinfo("impulseCallBack : CONNECTION:DELETE_CHAR %d sent", nSelectedSlot);
1818 else
1820 if (nSelectedSlot < CharacterSummaries.size())
1821 CharacterSummaries.erase (CharacterSummaries.begin()+nSelectedSlot);
1822 if (CharacterSummaries.size() != 0)
1823 userChar = true;
1824 else
1825 noUserChar = true;
1827 WaitServerAnswer = true;
1830 REGISTER_ACTION_HANDLER (CAHAskDeleteChar, "ask_delete_char");
1832 // ------------------------------------------------------------------------------------------------
1833 string getTarget(CCtrlBase * /* ctrl */, const string &targetName)
1835 string sTmp = targetName;
1836 std::vector<CInterfaceLink::CTargetInfo> targetsVector;
1837 CInterfaceLink::splitLinkTargets(sTmp, NULL, targetsVector);
1839 CInterfaceLink::CTargetInfo &rTI = targetsVector[0];
1841 CInterfaceElement *elem = rTI.Elem;
1842 if (!elem)
1844 nlwarning("<CInterfaceExpr::getprop> : Element is NULL");
1845 return "";
1847 const CReflectedProperty *pRP = CReflectSystem ::getProperty(elem->getReflectedClassName(), rTI.PropertyName);
1849 if (pRP->Type == CReflectedProperty::String)
1850 return ((elem->*(pRP->GetMethod.GetString))());
1851 return "";
1854 #ifdef RYZOM_LUA_UCSTRING
1855 // ------------------------------------------------------------------------------------------------
1856 ucstring getUCTarget(CCtrlBase * /* ctrl */, const string &targetName)
1858 string sTmp = targetName;
1859 std::vector<CInterfaceLink::CTargetInfo> targetsVector;
1860 CInterfaceLink::splitLinkTargets(sTmp, NULL, targetsVector);
1862 CInterfaceLink::CTargetInfo &rTI = targetsVector[0];
1864 CInterfaceElement *elem = rTI.Elem;
1865 if (!elem)
1867 nlwarning("<CInterfaceExpr::getprop> : Element is NULL");
1868 return ucstring(""); // TODO: UTF-8 Lua
1870 const CReflectedProperty *pRP = elem->getReflectedProperty(rTI.PropertyName);
1872 if (pRP->Type == CReflectedProperty::UCString)
1873 return ((elem->*(pRP->GetMethod.GetUCString))());
1874 return ucstring(""); // TODO: UTF-8 Lua
1876 #endif
1878 /*// Ask the server to rename a character
1879 // ------------------------------------------------------------------------------------------------
1880 class CAHAskRenameChar : public IActionHandler
1882 public:
1883 virtual void execute (CCtrlBase *pCaller, const string &Params)
1885 string sName = getTarget(NULL,getParam(Params, "name"));
1886 string sSurname = getTarget(NULL,getParam(Params, "surname"));
1888 string sDBSlot = getParam(Params, "dbslot");
1890 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1891 uint8 nSelectedSlot = (uint8)NLGUI::CDBManager::getInstance()->getDbProp(sDBSlot,false)->getValue32();
1893 if (nSelectedSlot > CharacterSummaries.size())
1894 return;
1896 // Create the message for the server to create the character.
1897 CBitMemStream out;
1898 if (!GenericMsgHeaderMngr.pushNameToStream("CONNECTION:RENAME_CHAR", out))
1900 nlwarning ("don't know message name CONNECTION:RENAME_CHAR");
1901 return;
1904 // Get the selected slot
1905 out.serial (nSelectedSlot);
1906 out.serial (sName);
1907 out.serial (sSurname);
1909 // Send the message to the server
1910 if (!ClientCfg.Light)
1912 noUserChar = userChar = false;
1913 NetMngr.push (out);
1914 NetMngr.send (NetMngr.getCurrentServerTick());
1916 nldebug("impulseCallBack : CONNECTION:RENAME_CHAR sent");
1918 // Wait for the character message which describe all the characters on a server
1919 while (!noUserChar && !userChar)
1921 //NetMngr.waitForServer();
1922 NetMngr.update();
1923 NetMngr.send();
1924 nlSleep(100);
1927 else
1929 CharacterSummaries[nSelectedSlot].FirstName = sName;
1930 CharacterSummaries[nSelectedSlot].Surname = sSurname;
1934 REGISTER_ACTION_HANDLER (CAHAskRenameChar, "ask_rename_char");
1937 // Ask the server if the name is not already used
1938 // ------------------------------------------------------------------------------------------------
1939 class CAHAskValidName : public IActionHandler
1941 public:
1942 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
1944 string sTarget = getParam(Params, "target");
1945 string sDBLink = getParam(Params, "dblink");
1946 CharNameValidDBLink = sDBLink;
1948 #ifdef RYZOM_LUA_UCSTRING
1949 string sName = getUCTarget(NULL,sTarget).toUtf8(); // TODO: UTF-8 Lua
1950 #else
1951 string sName = getTarget(NULL, sTarget);
1952 #endif
1954 CInterfaceManager *pIM = CInterfaceManager::getInstance();
1955 if (sName.empty())
1957 NLGUI::CDBManager::getInstance()->getDbProp(sDBLink,false)->setValue32(0);
1958 return;
1961 // Ask the server
1962 CharNameValid = true;
1964 // PATCH DU BUG DE L'ESPACE !!!
1965 if (sName.find(' ') != ucstring::npos)
1966 CharNameValid = false;
1967 // PATCH DU BUG DE L'ESPACE !!!
1970 if (CharNameValid)
1972 if (!ClientCfg.Local/*ace!ClientCfg.Light*/)
1975 CBitMemStream out;
1976 if (!GenericMsgHeaderMngr.pushNameToStream("CONNECTION:ASK_NAME", out))
1978 nlwarning ("don't know message name CONNECTION:ASK_NAME");
1979 return;
1982 CCheckNameMsg checkNameMsg;
1983 checkNameMsg.Name = sName;
1984 checkNameMsg.HomeSessionId = MainlandSelected;
1985 checkNameMsg.serialBitMemStream(out);
1987 NewKeysCharNameWanted = sName;
1988 // append shard name
1989 for(uint k = 0; k < Mainlands.size(); ++k)
1991 if (Mainlands[k].Id == MainlandSelected)
1993 // extract name from mainland
1994 /*ucstring::size_type first = Mainlands[k].Name.find('('); // OLD
1995 ucstring::size_type last = Mainlands[k].Name.find(')');// OLD
1996 if (first != ucstring::npos && last != ucstring::npos && first < last)// OLD
1998 NewKeysCharNameWanted += Mainlands[k].Name.substr(first, last - first + 1);
2000 NewKeysCharNameWanted += ('(' + Mainlands[k].Name.toUtf8() + ')');
2001 break;
2005 NewKeysCharNameValidated.clear();
2007 NetMngr.push(out);
2008 NetMngr.send(NetMngr.getCurrentServerTick());
2010 //nlinfo("impulseCallBack : CONNECTION:ASK_NAME sent");
2012 // Wait for the valid character name message
2013 CharNameValidArrived = false;
2015 else
2018 CharNameValid = true;
2019 CharNameValidArrived = true;
2021 for (uint i = 0; i < CharacterSummaries.size(); ++i)
2023 string ls = CharacterSummaries[i].Name.toString();
2024 if (ls == sName)
2025 CharNameValid = false;
2029 else
2031 CharNameValidArrived = true;
2033 WaitServerAnswer = true;
2036 REGISTER_ACTION_HANDLER (CAHAskValidName, "ask_valid_name");
2038 // ------------------------------------------------------------------------------------------------
2039 class CAHPlaySound : public IActionHandler
2041 public:
2042 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
2044 string sName = getParam(Params, "name");
2045 TStringId id = CStringMapper::map(sName);
2046 if (SoundMngr != NULL)
2047 SoundMngr->spawnSource(id,CVector(0,0,0));
2050 REGISTER_ACTION_HANDLER (CAHPlaySound, "play_sound");
2052 // ------------------------------------------------------------------------------------------------
2053 class CAHPlayMusicOutgame : public IActionHandler
2055 public:
2056 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
2058 // get the name of the wanted music
2059 string sName = getParam(Params, "name");
2060 bool async;
2061 fromString(getParam(Params, "async"), async);
2063 // if empty name, return to default mode
2064 if (sName.empty())
2065 sName = ClientCfg.EmptySlotMusic;
2067 // change the music
2068 SoundGlobalMenu.setMusic(sName, async);
2071 REGISTER_ACTION_HANDLER (CAHPlayMusicOutgame, "play_music_outgame");
2073 // ------------------------------------------------------------------------------------------------
2074 class CAHRepeatUntil : public IActionHandler
2076 public:
2077 virtual void execute (CCtrlBase *pCaller, const string &Params)
2079 string sProc = getParam(Params, "proc");
2080 string sCond = getParam(Params, "cond");
2081 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2083 for(;;)
2085 vector<string> p;
2086 p.push_back(sProc);
2087 CWidgetManager::getInstance()->runProcedure(sProc, pCaller, p);
2089 CInterfaceExprValue result;
2090 if (CInterfaceExpr::eval(sCond, result))
2092 if (result.getBool())
2093 break;
2095 else
2097 break;
2103 REGISTER_ACTION_HANDLER (CAHRepeatUntil, "repeatuntil");
2106 // ------------------------------------------------------------------------------------------------
2107 class CAHDispInfo : public IActionHandler
2109 public:
2110 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
2112 string sStr = getParam(Params, "str");
2113 string sVal = getParam(Params, "val");
2115 string res;
2117 CInterfaceExprValue result;
2118 if (CInterfaceExpr::eval(sStr, result))
2120 if (result.toString())
2122 res += result.getString();
2125 if (CInterfaceExpr::eval(sVal, result))
2127 if (result.toString())
2129 res += result.getString();
2133 nlinfo(res.c_str());
2136 REGISTER_ACTION_HANDLER (CAHDispInfo, "disp_info");
2139 // ***************************************************************************
2140 class CAHInitMainlandList : public IActionHandler
2142 public:
2144 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
2146 //CInterfaceManager *pIM = CInterfaceManager::getInstance();
2148 CInterfaceGroup *pList = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_MAINLAND));
2149 if (pList == NULL)
2151 nlwarning("element " GROUP_LIST_MAINLAND " not found probably bad outgame.xml");
2152 return;
2155 CInterfaceGroup *pPrevLine = NULL;
2156 for(uint i = 0; i < Mainlands.size(); i++)
2158 vector< pair < string, string > > params;
2159 params.clear();
2160 params.push_back(pair<string,string>("id", toString(Mainlands[i].Id)));
2161 if (i>0)
2162 params.push_back(pair<string,string>("posref", "BL TL"));
2164 CInterfaceGroup *pNewLine = CWidgetManager::getInstance()->getParser()->createGroupInstance("t_mainland", GROUP_LIST_MAINLAND, params);
2165 if (pNewLine != NULL)
2167 CViewBase *pVBon = pNewLine->getView("online");
2168 CViewBase *pVBoff = pNewLine->getView("offline");
2169 if ((pVBon != NULL) && (pVBoff != NULL))
2171 pVBon->setActive(Mainlands[i].Online);
2172 pVBoff->setActive(!Mainlands[i].Online);
2175 CViewText *pVT = dynamic_cast<CViewText*>(pNewLine->getView("name"));
2176 if (pVT != NULL)
2178 std::string str = Mainlands[i].Name.toUtf8() + " " + Mainlands[i].Description.toUtf8();
2179 pVT->setTextLocalized(str, false);
2182 // Add to the list
2183 pNewLine->setParent(pList);
2184 pNewLine->setParentSize(pList);
2185 pNewLine->setParentPos(pPrevLine);
2186 pList->addGroup(pNewLine);
2188 pPrevLine = pNewLine;
2191 // UI Patch
2192 if (!Mainlands.empty())
2194 //choose default mainland from language code
2195 uint32 defaultMainland = 0;
2196 for(uint i = 0; i < Mainlands.size(); i++)
2198 if( Mainlands[i].LanguageCode == ClientCfg.LanguageCode )
2200 defaultMainland = i;
2201 break;
2205 CCtrlButton *pCB = dynamic_cast<CCtrlButton*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_MAINLAND ":"+toString(Mainlands[defaultMainland].Id)+":but"));
2206 if (pCB != NULL)
2208 pCB->setPushed(true);
2209 CAHManager::getInstance()->runActionHandler (pCB->getActionOnLeftClick(), pCB, pCB->getParamsOnLeftClick());
2212 pList->invalidateCoords();
2215 REGISTER_ACTION_HANDLER (CAHInitMainlandList, "init_mainland_list");
2218 // ***************************************************************************
2219 class CAHResetMainlandList : public IActionHandler
2221 public:
2223 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
2225 //CInterfaceManager *pIM = CInterfaceManager::getInstance();
2226 CInterfaceGroup *pList = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_MAINLAND));
2227 pList->clearGroups();
2230 REGISTER_ACTION_HANDLER (CAHResetMainlandList, "reset_mainland_list");
2233 // ***************************************************************************
2234 class CAHMainlandSelect : public IActionHandler
2236 virtual void execute (CCtrlBase *pCaller, const string &/* Params */)
2238 nlinfo("CAHMainlandSelect called");
2240 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2242 CCtrlButton *pCB = NULL;
2243 // Unselect
2244 if (MainlandSelected.asInt() != 0)
2246 pCB = dynamic_cast<CCtrlButton*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_MAINLAND ":"+toString(MainlandSelected)+":but"));
2247 if (pCB != NULL)
2248 pCB->setPushed(false);
2251 pCB = dynamic_cast<CCtrlButton*>(pCaller);
2252 if (pCB != NULL)
2254 string name = pCB->getId();
2255 name = name.substr(0,name.rfind(':'));
2256 uint32 mainland;
2257 fromString(name.substr(name.rfind(':')+1,name.size()), mainland);
2258 MainlandSelected = (TSessionId)mainland;
2260 pCB->setPushed(true);
2264 REGISTER_ACTION_HANDLER (CAHMainlandSelect, "mainland_select");
2267 // ***************************************************************************
2268 class CAHInitKeysetList : public IActionHandler
2270 public:
2274 CInterfaceGroup *PrevLine;
2275 CInterfaceGroup *List;
2276 bool First;
2278 CInterfaceGroup *buildTemplate(const std::string &templateName, const std::string &id)
2280 vector< pair < string, string > > params;
2281 params.clear();
2282 params.push_back(pair<string,string>("id", id));
2283 if (!First)
2285 params.push_back(pair<string,string>("posref", "BL TL"));
2287 First = false;
2288 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2289 return CWidgetManager::getInstance()->getParser()->createGroupInstance(templateName, GROUP_LIST_KEYSET, params);
2292 void addGroupInList(CInterfaceGroup *pNewLine)
2294 if (!pNewLine) return;
2295 // Add to the list
2296 pNewLine->setParent(List);
2297 pNewLine->setParentSize(List);
2298 pNewLine->setParentPos(PrevLine);
2299 List->addGroup(pNewLine);
2301 PrevLine = pNewLine;
2304 void addSeparator()
2306 addGroupInList(buildTemplate("t_keyseparator", ""));
2309 // add a new keyset in the list
2310 void addKeySet(const std::string &filename, const std::string &name, const std::string tooltip)
2312 nlassert(List);
2313 CInterfaceGroup *pNewLine = buildTemplate("t_keyset", toString(filename));
2314 if (pNewLine != NULL)
2316 CViewText *pVT = dynamic_cast<CViewText*>(pNewLine->getView("name"));
2317 if (pVT != NULL)
2319 pVT->setTextLocalized(name, false);
2322 CCtrlBase *pBut = pNewLine->getCtrl("but");
2323 if (pBut != NULL)
2325 pBut->setDefaultContextHelp(tooltip);
2327 addGroupInList(pNewLine);
2331 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
2333 NewKeysCharNameWanted.clear();
2334 NewKeysCharNameValidated.clear();
2335 GameKeySet = "keys.xml";
2336 RingEditorKeySet = "keys_r2ed.xml";
2337 First = true;
2338 PrevLine = NULL;
2339 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2341 List = dynamic_cast<CInterfaceGroup *>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_KEYSET));
2342 if (List == NULL)
2344 nlwarning("element " GROUP_LIST_KEYSET " not found probably bad outgame.xml");
2345 return;
2348 // built-in keysets
2349 CConfigFile::CVar *keySetVar = ClientCfg.ConfigFile.getVarPtr(KeySetVarName);
2350 sint wasdIndex = -1;
2351 sint zqsdIndex = -1;
2352 if (keySetVar && keySetVar->size() != 0)
2354 for (uint k = 0; k < keySetVar->size(); ++k)
2356 if (keySetVar->asString(k) == "zqsd") zqsdIndex = (sint) k;
2357 if (keySetVar->asString(k) == "wasd") wasdIndex = (sint) k;
2359 std::string strId = "uiCP_KeysetName_" + keySetVar->asString(k);
2360 strFindReplace(strId, ".", "_");
2361 const string &keySetName = CI18N::get(strId);
2362 strId = "uiCP_KeysetTooltip_" + keySetVar->asString(k);
2363 strFindReplace(strId, ".", "_");
2364 if (CI18N::hasTranslation(strId))
2366 const string &keySetTooltip = CI18N::get(strId);
2367 addKeySet(keySetVar->asString(k), keySetName, keySetTooltip);
2371 else
2373 nlwarning("'%s' var not found in config file, or list is empty, proposing default keyset only", KeySetVarName);
2374 std::string defaultKeySet = "keys";
2375 const string &keySetName = CI18N::get("uiCP_KeysetName_" + defaultKeySet);
2376 const string &keySetTooltip = CI18N::get("uiCP_KeysetTooltip_" + defaultKeySet);
2377 addKeySet(defaultKeySet, keySetName, keySetTooltip);
2380 // keyset from previous chars
2381 std::vector<std::string> savedFiles;
2382 CPath::getPathContent("save/", false, false, true, savedFiles);
2383 enum { GameKeys = 0x1, EditorKeys = 0x2 };
2384 typedef std::map<std::string, uint> TKeySetFileMap;
2385 TKeySetFileMap keySetFiles; // combination of 'GameKeys' & 'EditorKeys' flag for each character
2386 for (uint k = 0; k < savedFiles.size(); ++k)
2388 if (testWildCard(CFile::getFilename(savedFiles[k]), "keys_*.xml"))
2390 bool editorKeys = testWildCard(CFile::getFilename(savedFiles[k]), "keys_r2ed_*.xml");
2391 std::string baseName = CFile::getFilenameWithoutExtension(savedFiles[k]).substr(strlen(editorKeys ? "keys_r2ed_" : "keys_"));
2392 if(!keySetFiles.count(baseName)) keySetFiles[baseName] = 0;
2393 keySetFiles[baseName] |= editorKeys ? EditorKeys : GameKeys;
2397 bool separatorAdded = false;
2398 if (!keySetFiles.empty())
2400 for(TKeySetFileMap::iterator it = keySetFiles.begin(); it != keySetFiles.end(); ++it)
2402 string name;
2403 if (ClientCfg.Local)
2405 name = it->first;
2407 else
2409 // search matching utf-8 string name from character summaries
2410 for (uint k = 0; k < CharacterSummaries.size(); ++k)
2412 if (it->first == buildPlayerNameForSaveFile(CharacterSummaries[k].Name.toUtf8()))
2414 name = CharacterSummaries[k].Name.toUtf8();
2418 if (!name.empty())
2420 if (!separatorAdded)
2422 addSeparator();
2423 separatorAdded = true;
2425 addKeySet(it->first, it->first, CI18N::get(std::string("uiCP_KeysetImport") + (it->second & GameKeys ? "_Game" : "")
2426 + (it->second & EditorKeys ? "_Editor" : "")));
2431 // default to 'ZQSD' for French and Belgian keyboard, 'WASD' else
2432 bool wasd = !CSystemUtils::isAzertyKeyboard();
2434 /*sint startIndex = wasd ? wasdIndex : zqsdIndex;
2435 if (startIndex == -1) startIndex = 0;
2437 // TMP TMP : no way to have 2 keys for the same action for now -> default to 'arrows' setting.
2438 sint startIndex = 0;
2439 nlassert(startIndex >= 0);
2440 if (startIndex < (sint) List->getNumGroup())
2442 CInterfaceGroup *gr = dynamic_cast<CInterfaceGroup *>(List->getGroup(startIndex));
2443 if (gr)
2445 CCtrlButton *pCB = dynamic_cast<CCtrlButton*>(gr->getCtrl("but"));
2446 if (pCB != NULL)
2448 pCB->setPushed(true);
2449 CAHManager::getInstance()->runActionHandler (pCB->getActionOnLeftClick(), pCB, pCB->getParamsOnLeftClick());
2453 List->invalidateCoords();
2456 REGISTER_ACTION_HANDLER (CAHInitKeysetList, "init_keyset_list");
2459 // ***************************************************************************
2460 class CAHResetKeysetList : public IActionHandler
2462 public:
2464 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
2466 //CInterfaceManager *pIM = CInterfaceManager::getInstance();
2467 CInterfaceGroup *pList = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_KEYSET));
2468 pList->clearGroups();
2471 REGISTER_ACTION_HANDLER (CAHResetKeysetList, "reset_keyset_list");
2474 // ***************************************************************************
2475 class CAHResetKeysetSelect : public IActionHandler
2477 public:
2478 std::string getIdPostFix(const std::string fullId)
2480 std::string::size_type pos = fullId.find_last_of(":");
2481 if (pos != std::string::npos)
2483 return fullId.substr(pos + 1);
2485 return "";
2487 virtual void execute (CCtrlBase *pCaller, const string &/* Params */)
2489 if (!pCaller) return;
2490 // 'unpush' all groups but the caller
2492 struct CUnpush : public CInterfaceElementVisitor
2494 CCtrlBase *Ref;
2495 virtual void visitCtrl(CCtrlBase *ctrl)
2497 if (ctrl == Ref) return;
2498 CCtrlBaseButton *but = dynamic_cast<CCtrlBaseButton *>(ctrl);
2499 if (but)
2501 but->setPushed(false);
2505 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2506 CInterfaceGroup * list = dynamic_cast<CInterfaceGroup *>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_KEYSET));
2507 if (list)
2509 CUnpush unpusher;
2510 unpusher.Ref = pCaller;
2511 list->visit(&unpusher);
2513 CCtrlBaseButton *but = dynamic_cast<CCtrlBaseButton *>(pCaller);
2514 if (but)
2516 but->setPushed(true);
2519 GameKeySet = "keys.xml";
2520 RingEditorKeySet = "keys_r2ed.xml";
2521 if (!pCaller->getParent()) return;
2522 // compute the 2 filenames from the id
2523 // if id is in the built-in keysets :
2524 CConfigFile::CVar *keySetVar = ClientCfg.ConfigFile.getVarPtr(KeySetVarName);
2525 if (keySetVar && keySetVar->size() != 0)
2527 for (uint k = 0; k < keySetVar->size(); ++k)
2529 std::string id = getIdPostFix(pCaller->getParent()->getId());
2530 if (keySetVar->asString(k) == id)
2532 GameKeySet = "keys" + string(id.empty() ? "" : "_") + id + ".xml";
2533 RingEditorKeySet = "keys_r2ed" + string(id.empty() ? "" : "_") + id + ".xml";
2534 return;
2538 // ... else maybe from a previous character ?
2539 if (CFile::isExists("save/keys_" + getIdPostFix(pCaller->getParent()->getId()) + ".xml") )
2541 GameKeySet = "keys_" + getIdPostFix(pCaller->getParent()->getId()) + ".xml";
2543 if (CFile::isExists("save/keys_r2ed_" + getIdPostFix(pCaller->getParent()->getId()) + ".xml") )
2545 RingEditorKeySet = "keys_r2ed_" + getIdPostFix(pCaller->getParent()->getId()) + ".xml";
2547 // NB : key file will be copied for real when the new 'character summary' is
2551 REGISTER_ACTION_HANDLER (CAHResetKeysetSelect, "keyset_select");
2557 // *************************** SCENARIO CONTROL WINDOW ***********************
2558 // ***************************************************************************
2559 // helper function for "setScenarioInformation"
2560 static void setTextField(CInterfaceGroup* scenarioWnd, const std::string &uiName, const std::string &text)
2562 CInterfaceElement *result = scenarioWnd->findFromShortId(uiName);
2563 if(result)
2565 CViewText* viewText = dynamic_cast<CViewText*>(result);
2566 if(viewText)
2567 viewText->setTextLocalized(text, false);
2568 CGroupEditBox* editBox = dynamic_cast<CGroupEditBox*>(result);
2569 if(editBox)
2570 editBox->setInputString(text);
2574 // helper function for "setScenarioInformation"
2575 static void setTextField(CInterfaceGroup* scenarioWnd, const std::string &uiName, const ucstring &text) // TODO: UTF-8 Lua
2577 setTextField(scenarioWnd, uiName, text.toUtf8());
2579 // helper function for "setScenarioInformation"
2580 static std::string fieldLookup(const vector< pair< string, string > > &values, const std::string &id)
2582 for(uint i=0; i<values.size(); i++)
2584 if (values[i].first == id) return values[i].second;
2586 return "--";
2589 static void setScenarioInformation(CInterfaceGroup* scenarioWnd, const string scenarioName)
2591 vector< pair< string, string > > values;
2592 if(R2::getEditor().isInitialized())
2594 values = R2::getEditor().getDMC().getEditionModule().getScenarioHeader();
2596 else
2598 R2::CScenarioValidator sv;
2599 std::string md5, signature;
2600 sv.setScenarioToLoad(scenarioName, values, md5, signature, false);
2603 setTextField(scenarioWnd, "rules_value_text", fieldLookup(values, "Rules"));
2604 uint levelRange = 0;
2605 uint32 nLevel;
2606 fromString(fieldLookup(values, "Level"), nLevel);
2607 switch(nLevel)
2609 case 20: levelRange = 0; break;
2610 case 50: levelRange = 1; break;
2611 case 100: levelRange = 2; break;
2612 case 150: levelRange = 3; break;
2613 case 200: levelRange = 4; break;
2614 case 250: levelRange = 5; break;
2616 setTextField(scenarioWnd, "level_value_text", CI18N::get("uiRAP_Level" + toString(levelRange)));
2617 setTextField(scenarioWnd, "language_value_text", CI18N::get("uiR2ED" + fieldLookup(values, "Language")));
2618 setTextField(scenarioWnd, "type_value_text", CI18N::get("uiR2ED" + fieldLookup(values, "Type")));
2619 setTextField(scenarioWnd, "edit_small_description", fieldLookup(values, "ShortDescription"));
2620 if(R2::getEditor().isInitialized())
2622 setTextField(scenarioWnd, "scenario_value_text", "'" + fieldLookup(values, "Title") + "'");
2627 void getChildrenControls(CInterfaceGroup* group, std::vector<CCtrlBase*> & controls)
2629 for(uint i=0; i<group->getGroups().size(); i++)
2630 getChildrenControls(group->getGroups()[i], controls);
2632 for(uint i=0; i<group->getControls().size(); i++)
2633 controls.push_back(group->getControls()[i]);
2636 inline void setToggleButton(CInterfaceGroup* scenarioWnd, const string & buttonName, bool pushed)
2638 CInterfaceElement * result = scenarioWnd->findFromShortId(buttonName);
2639 if(result)
2641 CInterfaceGroup * group = dynamic_cast<CInterfaceGroup*>(result);
2642 if(group)
2644 result = group->findFromShortId(string("toggle_butt"));
2645 if(result)
2647 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
2648 if(baseButton)
2649 baseButton->setPushed(!pushed);
2656 class CAHScenarioControl : public IActionHandler
2658 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
2660 nlinfo("CAHScenarioControl called");
2662 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2663 CInterfaceGroup* scenarioWnd = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:r2ed_scenario_control"));
2664 if(!scenarioWnd) return;
2666 // -------- active some groups in function of Ryzom mode or Edition/Animation mode ----
2667 // active team toggle button?
2668 CInterfaceElement *result = scenarioWnd->findFromShortId(string("invite_team"));
2669 if(result)
2671 CInterfaceGroup* groupTeam = dynamic_cast<CInterfaceGroup*>(result);
2672 if(groupTeam)
2674 bool team = !(R2::getEditor().isInitialized());
2675 if(team)
2676 team = (NLGUI::CDBManager::getInstance()->getDbProp("SERVER:USER:TEAM_MEMBER")->getValue8())!=0;
2677 groupTeam->setActive(team);
2681 // set scenario name label
2682 result = scenarioWnd->findFromShortId(string("current_scenario_label_text"));
2683 if(result)
2685 CViewText* viewText = dynamic_cast<CViewText*>(result);
2686 if(viewText)
2688 viewText->setTextLocalized(R2::getEditor().isInitialized() ? "uiR2EDScenarioName" : "uiR2EDScenarioFileName", true);
2692 // ok button tranlation
2693 result = scenarioWnd->findFromShortId(string("ok_button"));
2694 if(result)
2696 CCtrlTextButton* okButton = dynamic_cast<CCtrlTextButton*>(result);
2697 if(okButton)
2699 if(R2::getEditor().getAccessMode()!=R2::CEditor::AccessDM)
2700 okButton->setHardText(CI18N::get("uiR2EDLaunchScenario"));
2701 else
2702 okButton->setHardText(CI18N::get("uiR2EDApplyScenarioFilters"));
2706 // init current scenario name and parameters
2707 if(!R2::getEditor().isInitialized())
2709 ScenarioFileName.clear();
2711 // empty scenario
2712 CInterfaceElement *result = scenarioWnd->findFromShortId(string("scenario_value_text"));
2713 if(result)
2715 CViewText* viewText= dynamic_cast<CViewText*>(result);
2717 if(viewText)
2718 viewText->setText(std::string());
2721 setScenarioInformation(scenarioWnd, "");
2723 // hide description and information?
2724 result = scenarioWnd->findFromShortId(string("scenario_info_prop"));
2725 if(result)
2726 result->setActive(R2::getEditor().isInitialized());
2728 result = scenarioWnd->findFromShortId(string("description_gr"));
2729 if(result)
2730 result->setActive(R2::getEditor().isInitialized());
2732 // mainlands list
2733 result = scenarioWnd->findFromShortId(string("shards"));
2734 if(result)
2736 CGroupList * shardList = dynamic_cast<CGroupList*>(result);
2737 if(shardList)
2739 shardList->deleteAllChildren();
2741 for(uint i = 0; i < Mainlands.size(); i++)
2743 vector< pair < string, string > > params;
2744 params.clear();
2745 params.push_back(pair<string,string>("id", toString(Mainlands[i].Id)));
2746 params.push_back(pair<string,string>("w", "1024"));
2747 params.push_back(pair<string,string>("tooltip", "uiRingFilterShard"));
2748 CInterfaceGroup *toggleGr = CWidgetManager::getInstance()->getParser()->createGroupInstance("label_toggle_button", shardList->getId(), params);
2749 shardList->addChild(toggleGr);
2750 // set unicode name
2751 CViewText *shardName = dynamic_cast<CViewText *>(toggleGr->getView("button_text"));
2752 if (shardName)
2754 shardName->setTextLocalized(Mainlands[i].Name.toUtf8(), false);
2760 // show/display "back" button
2761 result = scenarioWnd->findFromShortId(string("load_button"));
2762 if(result)
2764 CCtrlBaseButton * loadB = dynamic_cast<CCtrlBaseButton *>(result);
2765 if(loadB)
2767 loadB->setActive(!R2::getEditor().isInitialized());
2771 // fill toggle buttons
2772 if(R2::getEditor().getAccessMode()==R2::CEditor::AccessDM)
2774 CSessionBrowserImpl & sessionBrowser = CSessionBrowserImpl::getInstance();
2775 sessionBrowser.getSessionInfo(sessionBrowser.getCharId(), R2::getEditor().getDMC().getEditionModule().getCurrentAdventureId());
2777 if(sessionBrowser.waitOneMessage(sessionBrowser.getMessageName("on_sessionInfoResult")))
2779 TRaceFilter & raceFilter = sessionBrowser._LastRaceFilter;
2780 setToggleButton(scenarioWnd, "fyros", raceFilter.checkEnumValue(TRaceFilterEnum::rf_fyros));
2781 setToggleButton(scenarioWnd, "matis", raceFilter.checkEnumValue(TRaceFilterEnum::rf_matis));
2782 setToggleButton(scenarioWnd, "tryker", raceFilter.checkEnumValue(TRaceFilterEnum::rf_tryker));
2783 setToggleButton(scenarioWnd, "zorai", raceFilter.checkEnumValue(TRaceFilterEnum::rf_zorai));
2785 TReligionFilter & religionFilter = sessionBrowser._LastReligionFilter;
2786 setToggleButton(scenarioWnd, "kami", religionFilter.checkEnumValue(TReligionFilterEnum::rf_kami));
2787 setToggleButton(scenarioWnd, "karavan", religionFilter.checkEnumValue(TReligionFilterEnum::rf_karavan));
2788 setToggleButton(scenarioWnd, "neutral", religionFilter.checkEnumValue(TReligionFilterEnum::rf_neutral));
2790 TGuildFilter & guildFilter = sessionBrowser._LastGuildFilter;
2791 setToggleButton(scenarioWnd, "guild_gr", (guildFilter==TGuildFilter::gf_any_player));
2793 TShardFilter & shardFilter = sessionBrowser._LastShardFilter;
2794 for(uint i=0; i<Mainlands.size(); i++)
2795 setToggleButton(scenarioWnd, toString(Mainlands[i].Id), shardFilter.checkEnumValue((RSMGR::TShardFilterEnum::TValues) (1<<i)));
2797 TLevelFilter & levelFilter = sessionBrowser._LastLevelFilter;
2798 setToggleButton(scenarioWnd, "20", levelFilter.checkEnumValue(TLevelFilterEnum::lf_a));
2799 setToggleButton(scenarioWnd, "50", levelFilter.checkEnumValue(TLevelFilterEnum::lf_b));
2800 setToggleButton(scenarioWnd, "100", levelFilter.checkEnumValue(TLevelFilterEnum::lf_c));
2801 setToggleButton(scenarioWnd, "150", levelFilter.checkEnumValue(TLevelFilterEnum::lf_d));
2802 setToggleButton(scenarioWnd, "200", levelFilter.checkEnumValue(TLevelFilterEnum::lf_e));
2803 setToggleButton(scenarioWnd, "250", levelFilter.checkEnumValue(TLevelFilterEnum::lf_f));
2805 bool subscriptionClosed = sessionBrowser._LastSubscriptionClosed;
2806 result = scenarioWnd->findFromShortId(string("global_access_toggle_butt"));
2807 if(result)
2809 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
2810 if(baseButton)
2811 baseButton->setPushed(subscriptionClosed);
2814 bool autoInvite = sessionBrowser._LastAutoInvite;
2815 result = scenarioWnd->findFromShortId(string("auto_invite_toggle_butt"));
2816 if(result)
2818 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
2819 if(baseButton)
2820 baseButton->setPushed(!autoInvite);
2823 // description
2824 string description = sessionBrowser._LastDescription;
2825 if(!description.empty())
2827 result = scenarioWnd->findFromShortId(string("edit_small_description"));
2828 if(result)
2830 CGroupEditBox* editBox = dynamic_cast<CGroupEditBox*>(result);
2831 if(editBox)
2832 editBox->setInputString(description);
2836 else
2838 nlwarning("getSessionInfo callback return false");
2841 else
2843 result = scenarioWnd->findFromShortId(string("access_players_filter"));
2844 if(result)
2846 CInterfaceGroup* filtersGroup = dynamic_cast<CInterfaceGroup*>(result);
2847 if(filtersGroup)
2849 std::vector<CCtrlBase*> controls;
2850 getChildrenControls(filtersGroup, controls);
2851 for(uint i=0; i<controls.size(); i++)
2853 CCtrlBase* control = controls[i];
2854 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(control);
2855 if(baseButton && (baseButton->getType()==CCtrlBaseButton::ToggleButton))
2856 baseButton->setPushed(false);
2863 REGISTER_ACTION_HANDLER (CAHScenarioControl, "init_scenario_control");
2866 // ***************************************************************************
2867 class CAHScenarioInformation : public IActionHandler
2869 virtual void execute (CCtrlBase * /* pCaller */, const string &Params)
2871 nlinfo("CAHScenarioDescription called");
2873 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2874 CInterfaceGroup* scenarioWnd = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:r2ed_scenario_control"));
2875 if(!scenarioWnd) return;
2877 CInterfaceElement *result = scenarioWnd->findFromShortId(string("scenario_value_text"));
2878 if(result)
2880 CViewText* viewText= dynamic_cast<CViewText*>(result);
2882 if(viewText)
2884 ScenarioFileName = getParam(Params, "ScenarioName");
2885 setScenarioInformation(scenarioWnd, ScenarioFileName);
2887 string scenarioName = ScenarioFileName;
2888 string::size_type posScenarioName = 0;
2889 while(posScenarioName!=string::npos)
2891 scenarioName = scenarioName.substr(posScenarioName==0?posScenarioName:posScenarioName+1);
2892 posScenarioName = scenarioName.find('/');
2894 viewText->setTextLocalized(scenarioName, false);
2898 // active description and information
2899 result = scenarioWnd->findFromShortId(string("scenario_info_prop"));
2900 if(result)
2901 result->setActive(true);
2903 result = scenarioWnd->findFromShortId(string("description_gr"));
2904 if(result)
2905 result->setActive(true);
2908 REGISTER_ACTION_HANDLER (CAHScenarioInformation, "scenario_information");
2910 // ***************************************************************************
2911 class CAHHideCharsFilters : public IActionHandler
2913 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
2915 nlinfo("CAHHideCharsFilters called");
2917 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2918 CInterfaceGroup* scenarioWnd = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:r2ed_scenario_control"));
2919 if(!scenarioWnd) return;
2921 bool lookingForPlayers = true;
2922 CInterfaceElement *result = scenarioWnd->findFromShortId(string("global_access_toggle_butt"));
2923 if(result)
2925 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
2926 if(baseButton)
2927 lookingForPlayers = !baseButton->getPushed(); // warning : on / off textures are inverted !!!
2930 result = scenarioWnd->findFromShortId(string("access_body_gr"));
2931 if(result)
2932 result->setActive(lookingForPlayers);
2934 result = scenarioWnd->findFromShortId(string("sep_global_access"));
2935 if(result)
2936 result->setActive(lookingForPlayers);
2938 result = scenarioWnd->findFromShortId(string("auto_invite_label"));
2939 if(result)
2940 result->setActive(lookingForPlayers);
2942 result = scenarioWnd->findFromShortId(string("auto_invite_toggle_butt"));
2943 if(result)
2944 result->setActive(lookingForPlayers);
2946 result = scenarioWnd->findFromShortId(string("invite_team"));
2947 if(result)
2949 bool team = (NLGUI::CDBManager::getInstance()->getDbProp("SERVER:USER:TEAM_MEMBER")->getValue8())!=0;
2950 team = (team && !(R2::getEditor().isInitialized()) && lookingForPlayers);
2951 result->setActive(team);
2955 REGISTER_ACTION_HANDLER (CAHHideCharsFilters, "hide_chars_filters");
2957 // ***************************************************************************
2958 class CAHLoadScenario : public IActionHandler
2960 virtual void execute (CCtrlBase *pCaller, const string &/* Params */)
2962 nlinfo("CAHLoadScenario called");
2964 CInterfaceManager *pIM = CInterfaceManager::getInstance();
2965 CInterfaceGroup* scenarioWnd = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:r2ed_scenario_control"));
2966 if(!scenarioWnd) return;
2968 CInterfaceElement *result = NULL;
2970 // load scenario
2971 if(!R2::getEditor().isInitialized())
2973 R2::CEditor::setStartingAnimationFilename(ScenarioFileName);
2976 // description
2977 string description;
2978 result = scenarioWnd->findFromShortId(string("edit_small_description"));
2979 if(result)
2981 CGroupEditBox* editBox = dynamic_cast<CGroupEditBox*>(result);
2982 if(editBox)
2983 description = editBox->getInputString();
2986 // races
2987 map<string, bool> races;
2988 races["fyros"] = false;
2989 races["matis"] = false;
2990 races["tryker"] = false;
2991 races["zorai"] = false;
2992 for(map<string, bool>::iterator itRace=races.begin(); itRace!=races.end(); itRace++)
2994 result = scenarioWnd->findFromShortId(itRace->first);
2995 if(result)
2997 CInterfaceGroup * group = dynamic_cast<CInterfaceGroup*>(result);
2998 if(group)
3000 result = group->findFromShortId(string("toggle_butt"));
3001 if(result)
3003 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3004 if(baseButton)
3005 itRace->second = !baseButton->getPushed();
3011 // religion
3012 map<string, bool> religions;
3013 religions["kami"] = false;
3014 religions["karavan"] = false;
3015 religions["neutral"] = false;
3016 for(map<string, bool>::iterator itReligion=religions.begin(); itReligion!=religions.end(); itReligion++)
3018 result = scenarioWnd->findFromShortId(itReligion->first);
3019 if(result)
3021 CInterfaceGroup * group = dynamic_cast<CInterfaceGroup*>(result);
3022 if(group)
3024 result = group->findFromShortId(string("toggle_butt"));
3025 if(result)
3027 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3028 if(baseButton)
3029 itReligion->second = !baseButton->getPushed();
3035 // guild
3036 bool anyPlayer = false;
3037 result = scenarioWnd->findFromShortId(string("guild_gr"));
3038 if(result)
3040 CInterfaceGroup * group = dynamic_cast<CInterfaceGroup*>(result);
3041 if(group)
3043 result = group->findFromShortId(string("toggle_butt"));
3044 if(result)
3046 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3047 if(baseButton)
3048 anyPlayer = !baseButton->getPushed();
3053 // shards
3054 std::vector<bool> shards(Mainlands.size(), false);
3055 for(uint i=0; i<Mainlands.size(); i++)
3057 string firstKey = Mainlands[i].Description.toString();
3059 result = scenarioWnd->findFromShortId(toString(Mainlands[i].Id));
3060 if(result)
3062 CInterfaceGroup * group = dynamic_cast<CInterfaceGroup*>(result);
3063 if(group)
3065 result = group->findFromShortId(string("toggle_butt"));
3066 if(result)
3068 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3069 if(baseButton)
3070 shards[i] = !baseButton->getPushed();
3076 // levels
3077 map<string, bool> levels;
3078 levels["20"] = false;
3079 levels["50"] = false;
3080 levels["100"] = false;
3081 levels["150"] = false;
3082 levels["200"] = false;
3083 levels["250"] = false;
3084 for(map<string, bool>::iterator itLevel=levels.begin(); itLevel!=levels.end(); itLevel++)
3086 result = scenarioWnd->findFromShortId(itLevel->first);
3087 if(result)
3089 CInterfaceGroup * group = dynamic_cast<CInterfaceGroup*>(result);
3090 if(group)
3092 result = group->findFromShortId(string("toggle_butt"));
3093 if(result)
3095 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3096 if(baseButton)
3097 itLevel->second = !baseButton->getPushed();
3103 // global access
3104 bool globalAccess = false;
3105 result = scenarioWnd->findFromShortId(string("global_access_toggle_butt"));
3106 if(result)
3108 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3109 if(baseButton)
3110 globalAccess = !baseButton->getPushed();
3113 // auto invite
3114 bool autoInvite = false;
3115 result = scenarioWnd->findFromShortId(string("auto_invite_toggle_butt"));
3116 if(result)
3118 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3119 if(baseButton)
3120 autoInvite = !baseButton->getPushed();
3123 // invite your team
3124 bool inviteTeam = false;
3125 result = scenarioWnd->findFromShortId(string("team_toggle_butt"));
3126 if(result)
3128 CCtrlBaseButton * baseButton = dynamic_cast<CCtrlBaseButton*>(result);
3129 if(baseButton)
3130 inviteTeam = !baseButton->getPushed();
3133 bool launchScenarioFromRingAccessPoint = false;
3135 vector< pair< string, string > > values;
3136 if(R2::getEditor().isInitialized())
3138 values = R2::getEditor().getDMC().getEditionModule().getScenarioHeader();
3140 else
3142 R2::CScenarioValidator sv;
3143 std::string md5, signature;
3144 sv.setScenarioToLoad(ScenarioFileName, values, md5, signature, false);
3145 launchScenarioFromRingAccessPoint = true;
3148 string rules, level, title;
3149 string initialIsland, initialEntryPoint, initialSeason;
3150 std::string lang, scenarioType;
3151 std::string otherCharAccess;
3152 std::string nevraxScenario = "0";
3153 std::string trialAllowed = "0";
3154 for(uint i=0; i<values.size(); i++)
3156 std::pair<std::string, std::string> pair = values[i];
3158 if(pair.first == "Rules") rules = pair.second;
3159 else if(pair.first == "Level") level = pair.second;
3160 else if(pair.first == "Title") title = pair.second;
3161 else if(pair.first == "InitialIsland") initialIsland = pair.second;
3162 else if(pair.first == "InitialEntryPoint") initialEntryPoint = pair.second;
3163 else if(pair.first == "InitialSeason") initialSeason = pair.second;
3164 else if(pair.first == "Language") lang = pair.second;
3165 else if(pair.first == "Type") scenarioType = pair.second;
3166 else if(pair.first == "OtherCharAccess") otherCharAccess = pair.second;
3167 else if(pair.first == "NevraxScenario") nevraxScenario = pair.second;
3168 else if(pair.first == "TrialAllowed") trialAllowed = pair.second;
3171 uint nLevel;
3172 fromString(level, nLevel);
3173 R2::TSessionLevel sessionLevel = R2::TSessionLevel::TValues(nLevel/50 + 1);
3175 // ---- fix for old scenarii
3176 if (lang == "French")
3177 lang = "fr";
3178 else if (lang == "German" || lang == "Deutsch")
3179 lang = "de";
3180 else //if (lang == "English")
3181 lang = "en";
3183 if (nlstricmp(scenarioType, "Roleplay") == 0 || nlstricmp(scenarioType, "Role play") == 0)
3184 scenarioType = "so_story_telling";
3185 else if (nlstricmp(scenarioType, "Combat") == 0)
3186 scenarioType = "so_hack_slash";
3187 // --------------------------
3189 TRuleType ruleType(TRuleType::rt_strict);
3190 if(rules==CI18N::get("uiR2EDliberal"))
3191 ruleType = TRuleType(TRuleType::rt_liberal);
3192 else if(rules == CI18N::get("uiR2EDstrict"))
3193 ruleType = TRuleType(TRuleType::rt_strict);
3194 volatile static bool override = false;
3195 if (override)
3197 if(rules== "Masterless")
3198 ruleType = TRuleType(TRuleType::rt_liberal);
3199 else if(rules == "Mastered")
3200 ruleType = TRuleType(TRuleType::rt_strict);
3203 TRaceFilter raceFilter;
3204 if(races["fyros"])
3205 raceFilter.setEnumValue(TRaceFilterEnum::rf_fyros);
3206 if(races["matis"])
3207 raceFilter.setEnumValue(TRaceFilterEnum::rf_matis);
3208 if(races["tryker"])
3209 raceFilter.setEnumValue(TRaceFilterEnum::rf_tryker);
3210 if(races["zorai"])
3211 raceFilter.setEnumValue(TRaceFilterEnum::rf_zorai);
3213 TReligionFilter religionFilter;
3214 if(religions["kami"])
3215 religionFilter.setEnumValue(TReligionFilterEnum::rf_kami);
3216 if(religions["karavan"])
3217 religionFilter.setEnumValue(TReligionFilterEnum::rf_karavan);
3218 if(religions["neutral"])
3219 religionFilter.setEnumValue(TReligionFilterEnum::rf_neutral);
3221 TGuildFilter guildFilter(anyPlayer?TGuildFilter::gf_any_player:TGuildFilter::gf_only_my_guild);
3223 TShardFilter shardFilter;
3224 for (uint i = 0; i < shards.size(); ++i)
3226 if (shards[i]) shardFilter.setEnumValue((RSMGR::TShardFilterEnum::TValues) (1<<i));
3229 TLevelFilter levelFilter;
3230 if(levels["20"])
3231 levelFilter.setEnumValue(TLevelFilterEnum::lf_a);
3232 if(levels["50"])
3233 levelFilter.setEnumValue(TLevelFilterEnum::lf_b);
3234 if(levels["100"])
3235 levelFilter.setEnumValue(TLevelFilterEnum::lf_c);
3236 if(levels["150"])
3237 levelFilter.setEnumValue(TLevelFilterEnum::lf_d);
3238 if(levels["200"])
3239 levelFilter.setEnumValue(TLevelFilterEnum::lf_e);
3240 if(levels["250"])
3241 levelFilter.setEnumValue(TLevelFilterEnum::lf_f);
3243 uint32 charId = 0;
3244 if (!ClientCfg.Local)
3245 charId = (NetMngr.getLoginCookie().getUserId()<< 4) + (uint32) PlayerSelectedSlot;
3247 CSessionBrowserImpl & sessionBrowser = CSessionBrowserImpl::getInstance();
3249 if(R2::getEditor().getAccessMode() != R2::CEditor::AccessDM)
3251 bool noob = NLGUI::CDBManager::getInstance()->getDbProp("SERVER:USER:IS_NEWBIE")->getValueBool();
3252 if (FreeTrial && noob && (nevraxScenario != "1" || trialAllowed != "1"))
3254 CViewText* pVT = dynamic_cast<CViewText*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:warning_free_trial:text"));
3255 if (pVT != NULL)
3256 pVT->setTextLocalized("uiRingWarningFreeTrial", true);
3257 CAHManager::getInstance()->runActionHandler("enter_modal", pCaller, "group=ui:interface:warning_free_trial");
3259 return;
3264 if(R2::getEditor().getAccessMode()!=R2::CEditor::AccessDM)
3266 if (launchScenarioFromRingAccessPoint)
3268 // hibernate Edit Session if active
3269 sessionBrowser.hibernateEditSession(charId);
3270 if(!sessionBrowser.waitOneMessage(sessionBrowser.getMessageName("on_invokeResult")))
3272 nlwarning("hibernateEditSession callback return false");
3277 // schedule session
3278 bool launchSuccess = true;
3279 sessionBrowser.scheduleSession(charId, TSessionType::st_anim,
3280 title, description, sessionLevel,
3281 /*TAccessType::at_public,*/ ruleType, TEstimatedDuration::et_medium, 0, TAnimMode::am_dm,
3282 raceFilter, religionFilter, guildFilter, shardFilter, levelFilter, lang, RSMGR::TSessionOrientation(scenarioType),
3283 !globalAccess, autoInvite);
3285 if(sessionBrowser.waitOneMessage(sessionBrowser.getMessageName("on_scheduleSessionResult")))
3287 if(sessionBrowser._LastScheduleSessionResult==0)
3289 // start session
3290 sessionBrowser.startSession(sessionBrowser._LastScheduleSessionCharId,
3291 sessionBrowser._LastScheduleSessionId);
3293 if(sessionBrowser.waitOneMessage(sessionBrowser.getMessageName("on_invokeResult")))
3296 if (launchScenarioFromRingAccessPoint)
3298 if (!initialIsland.empty() && !initialEntryPoint.empty() && !initialSeason.empty())
3300 sessionBrowser.setSessionStartParams(charId, sessionBrowser._LastScheduleSessionId, initialIsland, initialEntryPoint, initialSeason);
3304 TSessionPartStatus sessionStatus;
3305 if(ruleType==TRuleType::rt_liberal)
3306 sessionStatus = TSessionPartStatus(TSessionPartStatus::sps_play_invited);
3307 else
3308 sessionStatus = TSessionPartStatus(TSessionPartStatus::sps_anim_invited);
3310 // invite player
3311 sessionBrowser.inviteCharacter(
3312 sessionBrowser._LastScheduleSessionCharId,
3313 sessionBrowser._LastScheduleSessionId,
3314 sessionBrowser._LastScheduleSessionCharId,
3315 sessionStatus.toString());
3317 if(sessionBrowser.waitOneMessage(sessionBrowser.getMessageName("on_invokeResult")))
3319 // request session
3320 FarTP.requestFarTPToSession(sessionBrowser._LastScheduleSessionId, PlayerSelectedSlot, CFarTP::JoinSession,
3321 !R2::getEditor().isInitialized());
3323 else
3325 nlwarning("inviteCharacter callback return false");
3328 if (sessionBrowser._LastInvokeResult != 0)
3330 nlwarning("inviteCharacter callback use error values %d", sessionBrowser._LastInvokeResult);
3333 if(sessionBrowser._LastInvokeResult == 14)
3335 CViewText* pVT = dynamic_cast<CViewText*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:warning_free_trial:text"));
3336 if (pVT != NULL)
3337 pVT->setTextLocalized("uiRingWarningFreeTrial", true);
3338 CAHManager::getInstance()->runActionHandler("enter_modal", pCaller, "group=ui:interface:warning_free_trial");
3342 // invite team
3343 if(inviteTeam)
3345 for (uint i = 0 ; i < 8 ; ++i)
3347 uint32 val = NLGUI::CDBManager::getInstance()->getDbProp(NLMISC::toString("SERVER:GROUP:%d:NAME",i))->getValue32();
3348 if(val!=0)
3350 STRING_MANAGER::CStringManagerClient *pSMC = STRING_MANAGER::CStringManagerClient::instance();
3351 string res;
3352 if (pSMC->getString(val,res))
3354 string charName = CEntityCL::removeTitleAndShardFromName(res);
3355 sessionBrowser.inviteCharacterByName(sessionBrowser._LastScheduleSessionCharId, charName);
3357 if(!sessionBrowser.waitOneMessage(sessionBrowser.getMessageName("on_invokeResult")))
3359 nlwarning("inviteCharacterByName callback return false");
3362 if(sessionBrowser._LastInvokeResult == 14)
3364 CViewText* pVT = dynamic_cast<CViewText*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:warning_free_trial:text"));
3365 if (pVT != NULL)
3366 pVT->setTextLocalized("uiRingWarningInviteFreeTrial", true);
3367 CAHManager::getInstance()->runActionHandler("enter_modal", pCaller, "group=ui:interface:warning_free_trial");
3374 else
3376 nlwarning("startSession callback return false");
3377 launchSuccess = false;
3380 else if(sessionBrowser._LastScheduleSessionResult==10)
3382 pIM->messageBoxWithHelp(CI18N::get("uiRingWarningBanishedPlayer"));
3384 else
3386 launchSuccess=false;
3389 else
3391 nlwarning("scheduleSession callback return false");
3392 launchSuccess = false;
3395 if(!launchSuccess)
3397 pIM->messageBoxWithHelp(CI18N::get("uiRingLaunchScenarioError"));
3399 else
3401 scenarioWnd->setActive(false);
3404 else
3406 // update session
3407 sessionBrowser.updateSessionInfo(charId, sessionBrowser._LastScheduleSessionId, title, 0, description, sessionLevel,
3408 /*TAccessType::at_public, */TEstimatedDuration::et_medium, 0, raceFilter, religionFilter,
3409 guildFilter, shardFilter, levelFilter, !globalAccess, autoInvite, lang, RSMGR::TSessionOrientation(scenarioType));
3411 if(!sessionBrowser.waitOneMessage(sessionBrowser.getMessageName("on_invokeResult")))
3413 nlwarning("updateSessionInfo callback return false");
3414 pIM->messageBoxWithHelp(CI18N::get("uiRingUpdateScenarioFiltersError"));
3416 else
3418 scenarioWnd->setActive(false);
3423 REGISTER_ACTION_HANDLER (CAHLoadScenario, "load_scenario");
3426 // ***************************************************************************
3427 class CAHOpenRingSessions : public IActionHandler
3429 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
3431 if(!R2::getEditor().isInitialized())
3433 CInterfaceManager *pIM = CInterfaceManager::getInstance();
3434 CInterfaceGroup* ringSessionsWnd = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId("ui:interface:ring_sessions"));
3435 if(!ringSessionsWnd) return;
3436 ringSessionsWnd->setActive(true);
3440 REGISTER_ACTION_HANDLER (CAHOpenRingSessions, "open_ring_sessions");
3442 // ***************************************************************************
3443 class CAHInitImportCharacter : public IActionHandler
3445 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
3447 CInterfaceGroup *list = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_CHARACTER));
3448 if (!list)
3450 nlwarning("element " GROUP_LIST_CHARACTER " not found probably bad outgame.xml");
3451 return;
3454 // retrieve saved files
3455 std::vector<string> savedCharacters;
3456 CPath::getPathContent("save/", false, false, true, savedCharacters);
3458 CInterfaceGroup *newLine;
3459 CInterfaceGroup *prevLine = NULL;
3461 for (uint i = 0; i < savedCharacters.size(); ++i)
3463 // search saved characters only
3464 if (testWildCard(CFile::getFilename(savedCharacters[i]), "character_*.save"))
3466 const std::string id = CFile::getFilenameWithoutExtension(savedCharacters[i]).substr(strlen("character_"));
3467 if (id.empty())
3468 continue;
3470 std::vector<pair<string, string>> params;
3471 params.clear();
3472 params.push_back(std::pair<string, string>("id", id));
3473 // adjust ref
3474 if (list->getNumGroup() > 0)
3475 params.push_back(std::pair<string, string>("posref", "BL TL"));
3477 newLine = CWidgetManager::getInstance()->getParser()->createGroupInstance("t_import", GROUP_LIST_CHARACTER, params);
3478 if (newLine)
3480 CViewText *text = dynamic_cast<CViewText*>(newLine->getView("name"));
3481 if (text)
3482 text->setText(string(savedCharacters[i]));
3484 // first button is pushed
3485 CCtrlButton *button = dynamic_cast<CCtrlButton*>(newLine->getCtrl("but"));
3486 if (button && list->getNumGroup() == 0)
3487 button->setPushed(true);
3489 // add to the list now
3490 newLine->setParent(list);
3491 newLine->setParentSize(list);
3492 newLine->setParentPos(prevLine);
3494 list->addGroup(newLine);
3496 prevLine = newLine;
3500 // none case
3501 if (list->getNumGroup() == 0)
3502 CLuaManager::getInstance().executeLuaScript("outgame:procCharselNotifaction(3)");
3504 list->invalidateCoords();
3507 REGISTER_ACTION_HANDLER( CAHInitImportCharacter, "import_char_init" );
3509 // ***************************************************************************
3510 class CAHResetImportCharacter : public IActionHandler
3512 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
3514 CInterfaceGroup *list = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_CHARACTER));
3515 if (list)
3516 list->clearGroups();
3518 if (!ImportCharacter.empty())
3519 ImportCharacter = "";
3522 REGISTER_ACTION_HANDLER( CAHResetImportCharacter, "import_char_reset" );
3524 // ***************************************************************************
3525 class CAHSelectImportCharacter : public IActionHandler
3527 virtual void execute (CCtrlBase *pCaller, const std::string &Params)
3529 struct CUnpush : public CInterfaceElementVisitor
3531 CCtrlBase *Ref;
3532 virtual void visitCtrl(CCtrlBase *ctrl)
3534 if (ctrl == Ref) return;
3535 CCtrlBaseButton *but = dynamic_cast<CCtrlBaseButton*>(ctrl);
3536 if (but)
3538 but->setPushed(false);
3542 CInterfaceGroup *list = dynamic_cast<CInterfaceGroup*>(CWidgetManager::getInstance()->getElementFromId(GROUP_LIST_CHARACTER));
3543 if (!list)
3544 return;
3546 // unselect
3547 if (Params.empty())
3549 CUnpush unpusher;
3550 unpusher.Ref = pCaller;
3551 list->visit(&unpusher);
3554 // now select
3555 std::string name;
3556 if (Params.empty())
3558 CCtrlButton *pCB = dynamic_cast<CCtrlButton*>(pCaller);
3559 if (!pCB)
3560 return;
3562 std::string id = pCB->getId();
3563 id = id.substr(0, id.rfind(':'));
3565 if (!fromString(id.substr(id.rfind(':')+1, id.size()), name))
3566 return;
3568 pCB->setPushed(true);
3570 else
3571 if (!fromString(Params, name))
3572 return;
3574 ImportCharacter = "";
3575 // check filename and store
3576 if (CFile::fileExists(toString("save/character_%s.save", name.c_str())))
3577 ImportCharacter = name;
3580 REGISTER_ACTION_HANDLER( CAHSelectImportCharacter, "import_char_select" );
3582 // ***************************************************************************
3583 class CAHImportCharacter : public IActionHandler
3585 virtual void execute (CCtrlBase * /* pCaller */, const string &/* Params */)
3587 if (ImportCharacter.empty())
3588 return;
3590 if (!CFile::fileExists(toString("save/character_%s.save", ImportCharacter.c_str())))
3591 return;
3593 bool success = false;
3595 CIFile fd;
3596 CCharacterSummary CS;
3597 // use temporary file until close()
3598 if (fd.open(toString("save/character_%s.save", ImportCharacter.c_str())))
3602 CS.serial(fd);
3603 SCharacter3DSetup::setupDBFromCharacterSummary("UI:TEMP:CHAR3D", CS);
3605 // validate import
3606 CDBManager::getInstance()->getDbProp("UI:TEMP:IMPORT")->setValue32(1);
3607 success = true;
3609 catch (const EStream &e)
3611 nlwarning(e.what());
3613 fd.close();
3615 else
3616 nlwarning("Failed to open file: save/character_%s.save", ImportCharacter.c_str());
3618 // user notification
3619 if (!success)
3620 CLuaManager::getInstance().executeLuaScript("outgame:procCharselNotifaction(2)");
3621 else
3622 CAHManager::getInstance()->runActionHandler("proc", NULL, "proc_charsel_create_new");
3625 REGISTER_ACTION_HANDLER( CAHImportCharacter, "import_char" );
3627 // ***************************************************************************
3628 class CAHExportCharacter : public IActionHandler
3630 virtual void execute (CCtrlBase * /* pCaller */, const std::string &Params)
3632 if (Params.empty())
3633 return;
3635 sint32 slot = -1;
3636 if (!fromString(getParam(Params, "slot"), slot))
3637 return;
3639 if (slot >= CharacterSummaries.size() || slot < 0)
3640 return;
3642 // retrieve infos
3643 CCharacterSummary &CS = CharacterSummaries[slot];
3644 if (CS.Name.empty())
3645 return;
3647 // extract name
3648 const std::string name = buildPlayerNameForSaveFile(CS.Name.toUtf8());
3650 COFile fd;
3651 bool success = false;
3652 // use temporary file until close()
3653 if (fd.open(toString("save/character_%s.save", name.c_str()), false, false, true))
3657 fd.serial(CS);
3658 fd.flush();
3659 // validate
3660 success = true;
3662 catch (const EStream &e)
3664 nlwarning(e.what());
3666 fd.close();
3668 else
3669 nlwarning("Failed to open file: save/character_%s.save", name.c_str());
3671 const uint8 val = (success == true) ? 0 : 1;
3672 // user notification
3673 CLuaManager::getInstance().executeLuaScript(toString("outgame:procCharselNotifaction(%i)", val));
3676 REGISTER_ACTION_HANDLER( CAHExportCharacter, "export_char" );