llstartup.cpp 115 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/** 
 * @file llstartup.cpp
 * @brief startup routines.
 *
 * $LicenseInfo:firstyear=2004&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

29
#include "llappviewer.h"
30
#include "llstartup.h"
31
#include "llcallstack.h"
32
33
34
35
36
37
38
39
40
41

#if LL_WINDOWS
#	include <process.h>		// _spawnl()
#else
#	include <sys/stat.h>		// mkdir()
#endif

#include "llviewermedia_streamingaudio.h"
#include "llaudioengine.h"

42
43
#ifdef LL_FMODEX
# include "llaudioengine_fmodex.h"
44
45
46
47
48
49
50
#endif

#ifdef LL_OPENAL
#include "llaudioengine_openal.h"
#endif

#include "llavatarnamecache.h"
51
#include "llexperiencecache.h"
52
53
54
#include "lllandmark.h"
#include "llcachename.h"
#include "lldir.h"
55
#include "lldonotdisturbnotificationstorage.h"
56
57
58
#include "llerrorcontrol.h"
#include "llfloaterreg.h"
#include "llfocusmgr.h"
59
#include "llfloatergridstatus.h"
60
#include "llfloaterimsession.h"
61
62
63
64
65
66
67
68
#include "lllocationhistory.h"
#include "llimageworker.h"

#include "llloginflags.h"
#include "llmd5.h"
#include "llmemorystream.h"
#include "llmessageconfig.h"
#include "llmoveview.h"
69
70
#include "llfloaterimcontainer.h"
#include "llfloaterimnearbychat.h"
71
72
#include "llnotifications.h"
#include "llnotificationsutil.h"
73
#include "llpersistentnotificationstorage.h"
74
75
76
77
78
79
80
81
82
#include "llteleporthistory.h"
#include "llregionhandle.h"
#include "llsd.h"
#include "llsdserialize.h"
#include "llsdutil_math.h"
#include "llstring.h"
#include "lluserrelations.h"
#include "llversioninfo.h"
#include "llviewercontrol.h"
83
#include "llviewerhelp.h"
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "llvfs.h"
#include "llxorcipher.h"	// saved password, MAC address
#include "llwindow.h"
#include "message.h"
#include "v3math.h"

#include "llagent.h"
#include "llagentcamera.h"
#include "llagentpicksinfo.h"
#include "llagentwearables.h"
#include "llagentpilot.h"
#include "llfloateravatarpicker.h"
#include "llcallbacklist.h"
#include "llcallingcard.h"
#include "llconsole.h"
#include "llcontainerview.h"
100
#include "llconversationlog.h"
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "lldebugview.h"
#include "lldrawable.h"
#include "lleventnotifier.h"
#include "llface.h"
#include "llfeaturemanager.h"
//#include "llfirstuse.h"
#include "llfloaterhud.h"
#include "llfloaterland.h"
#include "llfloaterpreference.h"
#include "llfloatertopobjects.h"
#include "llfloaterworldmap.h"
#include "llgesturemgr.h"
#include "llgroupmgr.h"
#include "llhudeffecttrail.h"
#include "llhudmanager.h"
#include "llimagebmp.h"
#include "llinventorybridge.h"
#include "llinventorymodel.h"
#include "llinventorymodelbackgroundfetch.h"
#include "llkeyboard.h"
#include "llloginhandler.h"			// gLoginHandler, SLURL support
#include "lllogininstance.h" // Host the login module.
#include "llpanellogin.h"
#include "llmutelist.h"
#include "llavatarpropertiesprocessor.h"
#include "llpanelclassified.h"
#include "llpanelpick.h"
#include "llpanelgrouplandmoney.h"
#include "llpanelgroupnotices.h"
#include "llpreview.h"
#include "llpreviewscript.h"
132
#include "llproxy.h"
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#include "llproductinforequest.h"
#include "llselectmgr.h"
#include "llsky.h"
#include "llstatview.h"
#include "llstatusbar.h"		// sendMoneyBalanceRequest(), owns L$ balance
#include "llsurface.h"
#include "lltexturecache.h"
#include "lltexturefetch.h"
#include "lltoolmgr.h"
#include "lltrans.h"
#include "llui.h"
#include "llurldispatcher.h"
#include "llurlentry.h"
#include "llslurl.h"
#include "llurlhistory.h"
#include "llurlwhitelist.h"
#include "llvieweraudio.h"
#include "llviewerassetstorage.h"
#include "llviewercamera.h"
#include "llviewerdisplay.h"
#include "llviewergenericmessage.h"
#include "llviewergesture.h"
#include "llviewertexturelist.h"
#include "llviewermedia.h"
#include "llviewermenu.h"
#include "llviewermessage.h"
#include "llviewernetwork.h"
#include "llviewerobjectlist.h"
#include "llviewerparcelmedia.h"
#include "llviewerparcelmgr.h"
#include "llviewerregion.h"
#include "llviewerstats.h"
#include "llviewerthrottle.h"
#include "llviewerwindow.h"
#include "llvoavatar.h"
#include "llvoavatarself.h"
#include "llweb.h"
#include "llworld.h"
#include "llworldmapmessage.h"
#include "llxfermanager.h"
#include "pipeline.h"
#include "llappviewer.h"
#include "llfasttimerview.h"
#include "llfloatermap.h"
#include "llweb.h"
#include "llvoiceclient.h"
#include "llnamelistctrl.h"
#include "llnamebox.h"
#include "llnameeditor.h"
#include "llpostprocess.h"
#include "llwlparammanager.h"
#include "llwaterparammanager.h"
#include "llagentlanguage.h"
#include "llwearable.h"
#include "llinventorybridge.h"
#include "llappearancemgr.h"
#include "llavatariconctrl.h"
#include "llvoicechannel.h"
191
#include "llpathfindingmanager.h"
192
193
194
195

#include "lllogin.h"
#include "llevents.h"
#include "llstartuplistener.h"
196
#include "lltoolbarview.h"
dolphin's avatar
dolphin committed
197
#include "llexperiencelog.h"
198
#include "llcleanup.h"
199

200
201
#include "llstacktrace.h"

202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#if LL_WINDOWS
#include "lldxhardware.h"
#endif

//
// exported globals
//
bool gAgentMovementCompleted = false;
S32  gMaxAgentGroups;

std::string SCREEN_HOME_FILENAME = "screen_home.bmp";
std::string SCREEN_LAST_FILENAME = "screen_last.bmp";

LLPointer<LLViewerTexture> gStartTexture;

//
// Imported globals
//
extern S32 gStartImageWidth;
extern S32 gStartImageHeight;

//
// local globals
//
static bool gGotUseCircuitCodeAck = false;
static std::string sInitialOutfit;
static std::string sInitialOutfitGender;	// "male" or "female"
static boost::signals2::connection sWearablesLoadedCon;

static bool gUseCircuitCallbackCalled = false;

EStartupState LLStartUp::gStartupState = STATE_FIRST;
LLSLURL LLStartUp::sStartSLURL;

static LLPointer<LLCredential> gUserCredential;
static std::string gDisplayName;
static BOOL gRememberPassword = TRUE;     

static U64 gFirstSimHandle = 0;
static LLHost gFirstSim;
static std::string gFirstSimSeedCap;
static LLVector3 gAgentStartLookAt(1.0f, 0.f, 0.f);
static std::string gAgentStartLocation = "safe";
static bool mLoginStatePastUI = false;

247
248
const S32 DEFAULT_MAX_AGENT_GROUPS = 42;
const S32 ALLOWED_MAX_AGENT_GROUPS = 500;
249
const F32 STATE_AGENT_WAIT_TIMEOUT = 240; //seconds
250
251
252

boost::scoped_ptr<LLEventPump> LLStartUp::sStateWatcher(new LLEventStream("StartupState"));
boost::scoped_ptr<LLStartupListener> LLStartUp::sListener(new LLStartupListener());
253
boost::scoped_ptr<LLViewerStats::PhaseMap> LLStartUp::sPhases(new LLViewerStats::PhaseMap);
254
255
256
257
258
259
260

//
// local function declaration
//

void login_show();
void login_callback(S32 option, void* userdata);
261
void show_release_notes_if_required();
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
void show_first_run_dialog();
bool first_run_dialog_callback(const LLSD& notification, const LLSD& response);
void set_startup_status(const F32 frac, const std::string& string, const std::string& msg);
bool login_alert_status(const LLSD& notification, const LLSD& response);
void login_packet_failed(void**, S32 result);
void use_circuit_callback(void**, S32 result);
void register_viewer_callbacks(LLMessageSystem* msg);
void asset_callback_nothing(LLVFS*, const LLUUID&, LLAssetType::EType, void*, S32);
bool callback_choose_gender(const LLSD& notification, const LLSD& response);
void init_start_screen(S32 location_id);
void release_start_screen();
void reset_login();
LLSD transform_cert_args(LLPointer<LLCertificate> cert);
void general_cert_done(const LLSD& notification, const LLSD& response);
void trust_cert_done(const LLSD& notification, const LLSD& response);
void apply_udp_blacklist(const std::string& csv);
bool process_login_success_response();
void transition_back_to_login_panel(const std::string& emsg);

void callback_cache_name(const LLUUID& id, const std::string& full_name, bool is_group)
{
	LLNameBox::refreshAll(id, full_name, is_group);
	LLNameEditor::refreshAll(id, full_name, is_group);
	
	// TODO: Actually be intelligent about the refresh.
	// For now, just brute force refresh the dialogs.
	dialog_refresh_all();
}

//
// exported functionality
//

//
// local classes
//

void update_texture_fetch()
{
	LLAppViewer::getTextureCache()->update(1); // unpauses the texture cache thread
	LLAppViewer::getImageDecodeThread()->update(1); // unpauses the image thread
	LLAppViewer::getTextureFetch()->update(1); // unpauses the texture fetch thread
	gTextureList.updateImages(0.10f);
}

307
308
309
310
311
312
void set_flags_and_update_appearance()
{
	LLAppearanceMgr::instance().setAttachmentInvLinkEnable(true);
	LLAppearanceMgr::instance().updateAppearanceFromCOF(true, true, no_op);
}

313
314
315
316
// Returns false to skip other idle processing. Should only return
// true when all initialization done.
bool idle_startup()
{
317
318
319
320
321
322
323
	if (gViewerWindow == NULL)
	{
		// We expect window to be initialized
		LL_WARNS_ONCE() << "gViewerWindow is not initialized" << LL_ENDL;
		return false; // No world yet
	}

324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
	const F32 PRECACHING_DELAY = gSavedSettings.getF32("PrecachingDelay");
	static LLTimer timeout;

	static LLTimer login_time;

	// until this is encapsulated, this little hack for the
	// auth/transform loop will do.
	static F32 progress = 0.10f;

	static std::string auth_desc;
	static std::string auth_message;

	static LLVector3 initial_sun_direction(1.f, 0.f, 0.f);
	static LLVector3 agent_start_position_region(10.f, 10.f, 10.f);		// default for when no space server

	// last location by default
	static S32  agent_location_id = START_LOCATION_ID_LAST;

	static bool show_connect_box = true;

	//static bool stipend_since_login = false;

	// HACK: These are things from the main loop that usually aren't done
	// until initialization is complete, but need to be done here for things
	// to work.
	gIdleCallbacks.callFunctions();
	gViewerWindow->updateUI();
	LLMortician::updateClass();

	const std::string delims (" ");
	std::string system;
	int begIdx, endIdx;
356
	std::string osString = LLOSInfo::instance().getOSStringSimple();
357
358
359
360
361
362
363
364

	begIdx = osString.find_first_not_of (delims);
	endIdx = osString.find_first_of (delims, begIdx);
	system = osString.substr (begIdx, endIdx - begIdx);
	system += "Locale";

	LLStringUtil::setLocale (LLTrans::getString(system));

365
366
	//note: Removing this line will cause incorrect button size in the login screen. -- bao.
	gTextureList.updateImages(0.01f) ;
367
368
369

	if ( STATE_FIRST == LLStartUp::getStartupState() )
	{
370
371
372
373
374
375
376
377
378
		static bool first_call = true;
		if (first_call)
		{
			// Other phases get handled when startup state changes,
			// need to capture the initial state as well.
			LLStartUp::getPhases().startPhase(LLStartUp::getStartupStateString());
			first_call = false;
		}

379
380
381
382
383
384
385
		gViewerWindow->showCursor(); 
		gViewerWindow->getWindow()->setCursor(UI_CURSOR_WAIT);

		/////////////////////////////////////////////////
		//
		// Initialize stuff that doesn't need data from simulators
		//
386
387
388
		std::string lastGPU = gSavedSettings.getString("LastGPUString");
		std::string thisGPU = LLFeatureManager::getInstance()->getGPUString();
		
389
390
391
392
393
394
395
		if (LLFeatureManager::getInstance()->isSafe())
		{
			LLNotificationsUtil::add("DisplaySetToSafe");
		}
		else if ((gSavedSettings.getS32("LastFeatureVersion") < LLFeatureManager::getInstance()->getVersion()) &&
				 (gSavedSettings.getS32("LastFeatureVersion") != 0))
		{
396
			LLNotificationsUtil::add("DisplaySetToRecommendedFeatureChange");
397
		}
398
		else if ( ! lastGPU.empty() && (lastGPU != thisGPU))
399
		{
400
401
402
403
			LLSD subs;
			subs["LAST_GPU"] = lastGPU;
			subs["THIS_GPU"] = thisGPU;
			LLNotificationsUtil::add("DisplaySetToRecommendedGPUChange", subs);
404
405
406
407
408
409
		}
		else if (!gViewerWindow->getInitAlert().empty())
		{
			LLNotificationsUtil::add(gViewerWindow->getInitAlert());
		}
			
Logan Dethrow's avatar
Logan Dethrow committed
410
411
412
413
414
415
416
417
		//-------------------------------------------------
		// Init the SOCKS 5 proxy if the user has configured
		// one. We need to do this early in case the user
		// is using SOCKS for HTTP so we get the login
		// screen and HTTP tables via SOCKS.
		//-------------------------------------------------
		LLStartUp::startLLProxy();

418
		gSavedSettings.setS32("LastFeatureVersion", LLFeatureManager::getInstance()->getVersion());
419
		gSavedSettings.setString("LastGPUString", thisGPU);
420

421

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
		std::string xml_file = LLUI::locateSkin("xui_version.xml");
		LLXMLNodePtr root;
		bool xml_ok = false;
		if (LLXMLNode::parseFile(xml_file, root, NULL))
		{
			if( (root->hasName("xui_version") ) )
			{
				std::string value = root->getValue();
				F32 version = 0.0f;
				LLStringUtil::convertToF32(value, version);
				if (version >= 1.0f)
				{
					xml_ok = true;
				}
			}
		}
		if (!xml_ok)
		{
			// If XML is bad, there's a good possibility that notifications.xml is ALSO bad.
			// If that's so, then we'll get a fatal error on attempting to load it, 
			// which will display a nontranslatable error message that says so.
			// Otherwise, we'll display a reasonable error message that IS translatable.
			LLAppViewer::instance()->earlyExit("BadInstallation");
		}
		//
		// Statistics stuff
		//

		// Load autopilot and stats stuff
451
		gAgentPilot.load();
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482

		//gErrorStream.setTime(gSavedSettings.getBOOL("LogTimestamps"));

		// Load the throttle settings
		gViewerThrottle.load();

		//
		// Initialize messaging system
		//
		LL_DEBUGS("AppInit") << "Initializing messaging system..." << LL_ENDL;

		std::string message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message_template.msg");

		LLFILE* found_template = NULL;
		found_template = LLFile::fopen(message_template_path, "r");		/* Flawfinder: ignore */
		
		#if LL_WINDOWS
			// On the windows dev builds, unpackaged, the message_template.msg 
			// file will be located in:
			// build-vc**/newview/<config>/app_settings
			if (!found_template)
			{
				message_template_path = gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", "message_template.msg");
				found_template = LLFile::fopen(message_template_path.c_str(), "r");		/* Flawfinder: ignore */
			}	
		#elif LL_DARWIN
			// On Mac dev builds, message_template.msg lives in:
			// indra/build-*/newview/<config>/Second Life/Contents/Resources/app_settings
			if (!found_template)
			{
				message_template_path =
483
					gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
												   "message_template.msg");
				found_template = LLFile::fopen(message_template_path.c_str(), "r");		/* Flawfinder: ignore */
			}		
		#endif

		if (found_template)
		{
			fclose(found_template);

			U32 port = gSavedSettings.getU32("UserConnectionPort");

			if ((NET_USE_OS_ASSIGNED_PORT == port) &&   // if nothing specified on command line (-port)
			    (gSavedSettings.getBOOL("ConnectionPortEnabled")))
			  {
			    port = gSavedSettings.getU32("ConnectionPort");
			  }

			// TODO parameterize 
			const F32 circuit_heartbeat_interval = 5;
			const F32 circuit_timeout = 100;

			const LLUseCircuitCodeResponder* responder = NULL;
			bool failure_is_fatal = true;
			
			if(!start_messaging_system(
				   message_template_path,
				   port,
				   LLVersionInfo::getMajor(),
				   LLVersionInfo::getMinor(),
				   LLVersionInfo::getPatch(),
				   FALSE,
				   std::string(),
				   responder,
				   failure_is_fatal,
				   circuit_heartbeat_interval,
				   circuit_timeout))
			{
				std::string diagnostic = llformat(" Error: %d", gMessageSystem->getErrorCode());
				LL_WARNS("AppInit") << diagnostic << LL_ENDL;
				LLAppViewer::instance()->earlyExit("LoginFailedNoNetwork", LLSD().with("DIAGNOSTIC", diagnostic));
			}

			#if LL_WINDOWS
				// On the windows dev builds, unpackaged, the message.xml file will 
				// be located in indra/build-vc**/newview/<config>/app_settings.
				std::string message_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS,"message.xml");
							
				if (!LLFile::isfile(message_path.c_str())) 
				{
					LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_EXECUTABLE, "app_settings", ""));
				}
				else
				{
					LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
				}
			#else			
				LLMessageConfig::initClass("viewer", gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));
			#endif

		}
		else
		{
			LLAppViewer::instance()->earlyExit("MessageTemplateNotFound", LLSD().with("PATH", message_template_path));
		}

		if(gMessageSystem && gMessageSystem->isOK())
		{
			// Initialize all of the callbacks in case of bad message
			// system data
			LLMessageSystem* msg = gMessageSystem;
			msg->setExceptionFunc(MX_UNREGISTERED_MESSAGE,
								  invalid_message_callback,
								  NULL);
			msg->setExceptionFunc(MX_PACKET_TOO_SHORT,
								  invalid_message_callback,
								  NULL);

			// running off end of a packet is now valid in the case
			// when a reader has a newer message template than
			// the sender
			/*msg->setExceptionFunc(MX_RAN_OFF_END_OF_PACKET,
								  invalid_message_callback,
								  NULL);*/
			msg->setExceptionFunc(MX_WROTE_PAST_BUFFER_SIZE,
								  invalid_message_callback,
								  NULL);

			if (gSavedSettings.getBOOL("LogMessages"))
			{
				LL_DEBUGS("AppInit") << "Message logging activated!" << LL_ENDL;
				msg->startLogging();
			}

			// start the xfer system. by default, choke the downloads
			// a lot...
			const S32 VIEWER_MAX_XFER = 3;
			start_xfer_manager(gVFS);
			gXferManager->setMaxIncomingXfers(VIEWER_MAX_XFER);
			F32 xfer_throttle_bps = gSavedSettings.getF32("XferThrottle");
			if (xfer_throttle_bps > 1.f)
			{
				gXferManager->setUseAckThrottling(TRUE);
				gXferManager->setAckThrottleBPS(xfer_throttle_bps);
			}
			gAssetStorage = new LLViewerAssetStorage(msg, gXferManager, gVFS, gStaticVFS);


			F32 dropPercent = gSavedSettings.getF32("PacketDropPercentage");
			msg->mPacketRing.setDropPercentage(dropPercent);

            F32 inBandwidth = gSavedSettings.getF32("InBandwidth"); 
            F32 outBandwidth = gSavedSettings.getF32("OutBandwidth"); 
			if (inBandwidth != 0.f)
			{
				LL_DEBUGS("AppInit") << "Setting packetring incoming bandwidth to " << inBandwidth << LL_ENDL;
				msg->mPacketRing.setUseInThrottle(TRUE);
				msg->mPacketRing.setInBandwidth(inBandwidth);
			}
			if (outBandwidth != 0.f)
			{
				LL_DEBUGS("AppInit") << "Setting packetring outgoing bandwidth to " << outBandwidth << LL_ENDL;
				msg->mPacketRing.setUseOutThrottle(TRUE);
				msg->mPacketRing.setOutBandwidth(outBandwidth);
			}
		}

		LL_INFOS("AppInit") << "Message System Initialized." << LL_ENDL;
611

612
613
614
615
616
617
618
		//-------------------------------------------------
		// Init audio, which may be needed for prefs dialog
		// or audio cues in connection UI.
		//-------------------------------------------------

		if (FALSE == gSavedSettings.getBOOL("NoAudio"))
		{
619
			delete gAudiop;
620
621
			gAudiop = NULL;

622
#ifdef LL_FMODEX		
623
#if !LL_WINDOWS
maksymsproductengine's avatar
maksymsproductengine committed
624
			if (NULL == getenv("LL_BAD_FMODEX_DRIVER"))
625
626
#endif // !LL_WINDOWS
			{
627
				gAudiop = (LLAudioEngine *) new LLAudioEngine_FMODEX(gSavedSettings.getBOOL("FMODExProfilerEnable"));
628
629
630
631
632
			}
#endif

#ifdef LL_OPENAL
#if !LL_WINDOWS
maksymsproductengine's avatar
maksymsproductengine committed
633
			if (NULL == getenv("LL_BAD_OPENAL_DRIVER"))
634
635
636
637
638
#endif // !LL_WINDOWS
			{
				gAudiop = (LLAudioEngine *) new LLAudioEngine_OpenAL();
			}
#endif
Richard Linden's avatar
Richard Linden committed
639
            
640
641
642
			if (gAudiop)
			{
#if LL_WINDOWS
643
				// FMOD Ex on Windows needs the window handle to stop playing audio
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
				// when window is minimized. JC
				void* window_handle = (HWND)gViewerWindow->getPlatformWindow();
#else
				void* window_handle = NULL;
#endif
				bool init = gAudiop->init(kAUDIO_NUM_SOURCES, window_handle);
				if(init)
				{
					gAudiop->setMuted(TRUE);
				}
				else
				{
					LL_WARNS("AppInit") << "Unable to initialize audio engine" << LL_ENDL;
					delete gAudiop;
					gAudiop = NULL;
				}

				if (gAudiop)
				{
					// if the audio engine hasn't set up its own preferred handler for streaming audio then set up the generic streaming audio implementation which uses media plugins
					if (NULL == gAudiop->getStreamingAudioImpl())
					{
						LL_INFOS("AppInit") << "Using media plugins to render streaming audio" << LL_ENDL;
						gAudiop->setStreamingAudioImpl(new LLStreamingAudio_MediaPlugins());
					}
				}
			}
		}
		
		LL_INFOS("AppInit") << "Audio Engine Initialized." << LL_ENDL;
		
		if (LLTimer::knownBadTimer())
		{
			LL_WARNS("AppInit") << "Unreliable timers detected (may be bad PCI chipset)!!" << LL_ENDL;
		}

		//
		// Log on to system
		//
		if (gUserCredential.isNull())
		{
			gUserCredential = gLoginHandler.initializeLoginInfo();
		}
687
		// Previous initializeLoginInfo may have generated user credentials.  Re-check them.
688
689
690
691
692
693
		if (gUserCredential.isNull())
		{
			show_connect_box = TRUE;
		}
		else if (gSavedSettings.getBOOL("AutoLogin"))  
		{
694
			// Log into last account
695
696
697
698
			gRememberPassword = TRUE;
			gSavedSettings.setBOOL("RememberPassword", TRUE);                                                      
			show_connect_box = false;    			
		}
699
700
701
702
703
704
		else if (gSavedSettings.getLLSD("UserLoginInfo").size() == 3)
		{
			// Console provided login&password
			gRememberPassword = gSavedSettings.getBOOL("RememberPassword");
			show_connect_box = false;
		}
705
706
707
708
709
		else 
		{
			gRememberPassword = gSavedSettings.getBOOL("RememberPassword");
			show_connect_box = TRUE;
		}
710
711
712
713
714

		//setup map of datetime strings to codes and slt & local time offset from utc
		// *TODO: Does this need to be here?
		LLStringOps::setupDatetimeInfo(false);

715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
		// Go to the next startup state
		LLStartUp::setStartupState( STATE_BROWSER_INIT );
		return FALSE;
	}

	
	if (STATE_BROWSER_INIT == LLStartUp::getStartupState())
	{
		LL_DEBUGS("AppInit") << "STATE_BROWSER_INIT" << LL_ENDL;
		std::string msg = LLTrans::getString("LoginInitializingBrowser");
		set_startup_status(0.03f, msg.c_str(), gAgent.mMOTD.c_str());
		display_startup();
		// LLViewerMedia::initBrowser();
		LLStartUp::setStartupState( STATE_LOGIN_SHOW );
		return FALSE;
	}


	if (STATE_LOGIN_SHOW == LLStartUp::getStartupState())
	{
735
736
		LL_DEBUGS("AppInit") << "Initializing Window, show_connect_box = "
							 << show_connect_box << LL_ENDL;
737
738
739
740
741

		// if we've gone backwards in the login state machine, to this state where we show the UI
		// AND the debug setting to exit in this case is true, then go ahead and bail quickly
		if ( mLoginStatePastUI && gSavedSettings.getBOOL("QuitOnLoginActivated") )
		{
742
			LL_DEBUGS("AppInit") << "taking QuitOnLoginActivated exit" << LL_ENDL;
743
744
745
746
747
748
			// no requirement for notification here - just exit
			LLAppViewer::instance()->earlyExitNoNotify();
		}

		gViewerWindow->getWindow()->setCursor(UI_CURSOR_ARROW);

749
750
751
752
		// Login screen needs menus for preferences, but we can enter
		// this startup phase more than once.
		if (gLoginMenuBarView == NULL)
		{
753
			LL_DEBUGS("AppInit") << "initializing menu bar" << LL_ENDL;
754
			initialize_spellcheck_menu();
755
756
			init_menus();
		}
757
		show_release_notes_if_required();
758

759
760
		if (show_connect_box)
		{
761
			LL_DEBUGS("AppInit") << "show_connect_box on" << LL_ENDL;
762
763
764
765
			// Load all the name information out of the login view
			// NOTE: Hits "Attempted getFields with no login view shown" warning, since we don't
			// show the login view until login_show() is called below.  
			if (gUserCredential.isNull())                                                                          
766
			{                                                  
767
				LL_DEBUGS("AppInit") << "loading credentials from gLoginHandler" << LL_ENDL;
768
769
770
771
772
773
774
				gUserCredential = gLoginHandler.initializeLoginInfo();                 
			}     
			// Make sure the process dialog doesn't hide things
			gViewerWindow->setShowProgress(FALSE);
			// Show the login dialog
			login_show();
			// connect dialog is already shown, so fill in the names
775
			if (gUserCredential.notNull() && !LLPanelLogin::isCredentialSet())
776
777
778
			{
				LLPanelLogin::setFields( gUserCredential, gRememberPassword);
			}
779
780
			LLPanelLogin::giveFocus();

781
782
			// MAINT-3231 Show first run dialog only for Desura viewer
			if (gSavedSettings.getString("sourceid") == "1208_desura")
783
			{
784
785
786
787
788
789
790
791
792
				if (gSavedSettings.getBOOL("FirstLoginThisInstall"))
				{
					LL_INFOS("AppInit") << "FirstLoginThisInstall, calling show_first_run_dialog()" << LL_ENDL;
					show_first_run_dialog();
				}
				else
				{
					LL_DEBUGS("AppInit") << "FirstLoginThisInstall off" << LL_ENDL;
				}
793
			}
794
			display_startup();
795
796
797
798
			LLStartUp::setStartupState( STATE_LOGIN_WAIT );		// Wait for user input
		}
		else
		{
799
			LL_DEBUGS("AppInit") << "show_connect_box off, skipping to STATE_LOGIN_CLEANUP" << LL_ENDL;
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
			// skip directly to message template verification
			LLStartUp::setStartupState( STATE_LOGIN_CLEANUP );
		}

		gViewerWindow->setNormalControlsVisible( FALSE );	
		gLoginMenuBarView->setVisible( TRUE );
		gLoginMenuBarView->setEnabled( TRUE );
		show_debug_menus();

		// Hide the splash screen
		LLSplashScreen::hide();
		// Push our window frontmost
		gViewerWindow->getWindow()->show();

		// DEV-16927.  The following code removes errant keystrokes that happen while the window is being 
		// first made visible.
#ifdef _WIN32
		MSG msg;
818
		while( PeekMessage( &msg, /*All hWnds owned by this thread */ NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE ) )
819
		{ }
820
#endif
821
822
        display_startup();
        timeout.reset();
823
824
825
826
827
828
829
830
831
832
833
834
		return FALSE;
	}

	if (STATE_LOGIN_WAIT == LLStartUp::getStartupState())
	{
		// when we get to this state, we've already been past the login UI
		// (possiblely automatically) - flag this so we can test in the 
		// STATE_LOGIN_SHOW state if we've gone backwards
		mLoginStatePastUI = true;

		// Don't do anything.  Wait for the login view to call the login_callback,
		// which will push us to the next state.
835
836

		// display() function will be the one to run display_startup()
837
838
839
840
841
842
843
		// Sleep so we don't spin the CPU
		ms_sleep(1);
		return FALSE;
	}

	if (STATE_LOGIN_CLEANUP == LLStartUp::getStartupState())
	{
844
845
846
		// Post login screen, we should see if any settings have changed that may
		// require us to either start/stop or change the socks proxy. As various communications
		// past this point may require the proxy to be up.
Logan Dethrow's avatar
Logan Dethrow committed
847
		if (!LLStartUp::startLLProxy())
848
		{
Logan Dethrow's avatar
Logan Dethrow committed
849
			// Proxy start up failed, we should now bail the state machine
Logan Dethrow's avatar
Logan Dethrow committed
850
			// startLLProxy() will have reported an error to the user
Logan Dethrow's avatar
Logan Dethrow committed
851
852
853
854
855
			// already, so we just go back to the login screen. The user
			// could then change the preferences to fix the issue.

			LLStartUp::setStartupState(STATE_LOGIN_SHOW);
			return FALSE;
856
857
		}

858
		// reset the values that could have come in from a slurl
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
		// DEV-42215: Make sure they're not empty -- gUserCredential
		// might already have been set from gSavedSettings, and it's too bad
		// to overwrite valid values with empty strings.

		if (show_connect_box)
		{
			// TODO if not use viewer auth
			// Load all the name information out of the login view
			LLPanelLogin::getFields(gUserCredential, gRememberPassword); 
			// end TODO
	 
			// HACK: Try to make not jump on login
			gKeyboard->resetKeys();
		}

		// when we get to this state, we've already been past the login UI
		// (possiblely automatically) - flag this so we can test in the 
		// STATE_LOGIN_SHOW state if we've gone backwards
		mLoginStatePastUI = true;

		// save the credentials                                                                                        
		std::string userid = "unknown";                                                                                
		if(gUserCredential.notNull())                                                                                  
		{  
			userid = gUserCredential->userID();                                                                    
			gSecAPIHandler->saveCredential(gUserCredential, gRememberPassword);  
		}
		gSavedSettings.setBOOL("RememberPassword", gRememberPassword);                                                 
		LL_INFOS("AppInit") << "Attempting login as: " << userid << LL_ENDL;                                           
		gDebugInfo["LoginName"] = userid;                                                                              
         
		// create necessary directories
		// *FIX: these mkdir's should error check
		gDirUtilp->setLindenUserDir(userid);
		LLFile::mkdir(gDirUtilp->getLindenUserDir());

895
		// As soon as directories are ready initialize notification storages
896
897
898
899
900
901
902
		if (!LLPersistentNotificationStorage::instanceExists())
		{
			// check existance since this part of code can be reached
			// twice due to login failures
			LLPersistentNotificationStorage::initParamSingleton();
			LLDoNotDisturbNotificationStorage::initParamSingleton();
		}
903

904
905
906
907
908
909
910
911
912
913
		// Set PerAccountSettingsFile to the default value.
		gSavedSettings.setString("PerAccountSettingsFile",
			gDirUtilp->getExpandedFilename(LL_PATH_PER_SL_ACCOUNT, 
				LLAppViewer::instance()->getSettingsFilename("Default", "PerAccount")));

		// Note: can't store warnings files per account because some come up before login
		
		// Overwrite default user settings with user settings								 
		LLAppViewer::instance()->loadSettingsFromDirectory("Account");

914
915
916
917
918
919
920
		// Convert 'LogInstantMessages' into 'KeepConversationLogTranscripts' for backward compatibility (CHUI-743).
		LLControlVariablePtr logInstantMessagesControl = gSavedPerAccountSettings.getControl("LogInstantMessages");
		if (logInstantMessagesControl.notNull())
		{
			gSavedPerAccountSettings.setS32("KeepConversationLogTranscripts", logInstantMessagesControl->getValue() ? 2 : 1);
		}

921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
		// Need to set the LastLogoff time here if we don't have one.  LastLogoff is used for "Recent Items" calculation
		// and startup time is close enough if we don't have a real value.
		if (gSavedPerAccountSettings.getU32("LastLogoff") == 0)
		{
			gSavedPerAccountSettings.setU32("LastLogoff", time_corrected());
		}

		//Default the path if one isn't set.
		// *NOTE: unable to check variable differ from "InstantMessageLogPath" because it was
		// provided in pre 2.0 viewer. See EXT-6661
		if (gSavedPerAccountSettings.getString("InstantMessageLogPath").empty())
		{
			gDirUtilp->setChatLogsDir(gDirUtilp->getOSUserAppDir());
			gSavedPerAccountSettings.setString("InstantMessageLogPath", gDirUtilp->getChatLogsDir());
		}
		else
		{
			gDirUtilp->setChatLogsDir(gSavedPerAccountSettings.getString("InstantMessageLogPath"));		
		}
		gDirUtilp->setPerAccountChatLogsDir(userid);  
		
		LLFile::mkdir(gDirUtilp->getChatLogsDir());
		LLFile::mkdir(gDirUtilp->getPerAccountChatLogsDir());

945
946
947
948
949
950
		//Initialize conversation log only when chat log directories are ready
		if (!LLConversationLog::instanceExists())
		{
			// Check existance since this part can be reached twice if login fails
			LLConversationLog::initParamSingleton();
		}
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968

		//good a place as any to create user windlight directories
		std::string user_windlight_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight", ""));
		LLFile::mkdir(user_windlight_path_name.c_str());		

		std::string user_windlight_skies_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/skies", ""));
		LLFile::mkdir(user_windlight_skies_path_name.c_str());

		std::string user_windlight_water_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/water", ""));
		LLFile::mkdir(user_windlight_water_path_name.c_str());

		std::string user_windlight_days_path_name(gDirUtilp->getExpandedFilename( LL_PATH_USER_SETTINGS , "windlight/days", ""));
		LLFile::mkdir(user_windlight_days_path_name.c_str());


		if (show_connect_box)
		{
			LLSLURL slurl;
969
			//LLPanelLogin::closePanel();
970
971
972
973
974
975
976
977
978
979
980
		}

		
		// Load URL History File
		LLURLHistory::loadFile("url_history.xml");
		// Load location history 
		LLLocationHistory::getInstance()->load();

		// Load Avatars icons cache
		LLAvatarIconIDCache::getInstance()->load();
		
981
982
		LLRenderMuteList::getInstance()->loadFromFile();

983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
		//-------------------------------------------------
		// Handle startup progress screen
		//-------------------------------------------------

		// on startup the user can request to go to their home,
		// their last location, or some URL "-url //sim/x/y[/z]"
		// All accounts have both a home and a last location, and we don't support
		// more locations than that.  Choose the appropriate one.  JC
		switch (LLStartUp::getStartSLURL().getType())
		  {
		  case LLSLURL::LOCATION:
		    agent_location_id = START_LOCATION_ID_URL;
		    break;
		  case LLSLURL::LAST_LOCATION:
		    agent_location_id = START_LOCATION_ID_LAST;
		    break;
		  default:
		    agent_location_id = START_LOCATION_ID_HOME;
		    break;
		  }

		gViewerWindow->getWindow()->setCursor(UI_CURSOR_WAIT);

1006
		init_start_screen(agent_location_id);
1007
1008
1009
1010
1011

		// Display the startup progress bar.
		gViewerWindow->setShowProgress(TRUE);
		gViewerWindow->setProgressCancelButtonVisible(TRUE, LLTrans::getString("Quit"));

1012
1013
		gViewerWindow->revealIntroPanel();

1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
		// Poke the VFS, which could potentially block for a while if
		// Windows XP is acting up
		set_startup_status(0.07f, LLTrans::getString("LoginVerifyingCache"), LLStringUtil::null);
		display_startup();

		gVFS->pokeFiles();

		LLStartUp::setStartupState( STATE_LOGIN_AUTH_INIT );

		return FALSE;
	}

	if(STATE_LOGIN_AUTH_INIT == LLStartUp::getStartupState())
	{
1028
		gDebugInfo["GridName"] = LLGridManager::getInstance()->getGridId();
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041

		// Update progress status and the display loop.
		auth_desc = LLTrans::getString("LoginInProgress");
		set_startup_status(progress, auth_desc, auth_message);
		progress += 0.02f;
		display_startup();

		// Setting initial values...
		LLLoginInstance* login = LLLoginInstance::getInstance();
		login->setNotificationsInterface(LLNotifications::getInstance());

		login->setSerialNumber(LLAppViewer::instance()->getSerialNumber());
		login->setLastExecEvent(gLastExecEvent);
1042
		login->setLastExecDuration(gLastExecDuration);
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064

		// This call to LLLoginInstance::connect() starts the 
		// authentication process.
		login->connect(gUserCredential);

		LLStartUp::setStartupState( STATE_LOGIN_CURL_UNSTUCK );
		return FALSE;
	}

	if(STATE_LOGIN_CURL_UNSTUCK == LLStartUp::getStartupState())
	{
		// If we get here we have gotten past the potential stall
		// in curl, so take "may appear frozen" out of progress bar. JC
		auth_desc = LLTrans::getString("LoginInProgressNoFrozen");
		set_startup_status(progress, auth_desc, auth_message);

		LLStartUp::setStartupState( STATE_LOGIN_PROCESS_RESPONSE );
		return FALSE;
	}

	if(STATE_LOGIN_PROCESS_RESPONSE == LLStartUp::getStartupState()) 
	{
1065
		// Generic failure message
1066
1067
1068
1069
1070
1071
1072
1073
		std::ostringstream emsg;
		emsg << LLTrans::getString("LoginFailed") << "\n";
		if(LLLoginInstance::getInstance()->authFailure())
		{
			LL_INFOS("LLStartup") << "Login failed, LLLoginInstance::getResponse(): "
			                      << LLLoginInstance::getInstance()->getResponse() << LL_ENDL;
			LLSD response = LLLoginInstance::getInstance()->getResponse();
			// Still have error conditions that may need some 
1074
			// sort of handling - dig up specific message
1075
1076
			std::string reason_response = response["reason"];
			std::string message_response = response["message"];
1077
1078
1079
1080
			std::string message_id = response["message_id"];
			std::string message; // actual string to show the user

			if(!message_id.empty() && LLTrans::findString(message, message_id, response["message_args"]))
1081
			{
1082
				// message will be filled in with the template and arguments
Christian Goetze's avatar
Christian Goetze committed
1083
			}
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
			else if(!message_response.empty())
			{
				// *HACK: "no_inventory_host" sent as the message itself.
				// Remove this clause when server is sending message_id as well.
				message = LLAgent::sTeleportErrorMessages[ message_response ];
			}

			if (message.empty())
			{
				// Fallback to server-supplied string; necessary since server
				// may add strings that this viewer is not yet aware of
				message = message_response;
1096
1097
			}

1098
1099
			emsg << message;

Christian Goetze's avatar
Christian Goetze committed
1100

1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
			if(reason_response == "key")
			{
				// Couldn't login because user/password is wrong
				// Clear the credential
				gUserCredential->clearAuthenticator();
			}

			if(reason_response == "update" 
				|| reason_response == "optional")
			{
				// In the case of a needed update, quit.
				// Its either downloading or declined.
				// If optional was skipped this case shouldn't 
				// be reached.
				LLLoginInstance::getInstance()->disconnect();
				LLAppViewer::instance()->forceQuit();
			}
			else 
			{
				if (reason_response != "tos") 
				{
					// Don't pop up a notification in the TOS case because
					// LLFloaterTOS::onCancel() already scolded the user.
					std::string error_code;
					if(response.has("errorcode"))
					{
						error_code = response["errorcode"].asString();
					}
					if ((reason_response == "CURLError") && 
						(error_code == "SSL_CACERT" || error_code == "SSL_PEER_CERTIFICATE") && 
						response.has("certificate"))
					{
						// This was a certificate error, so grab the certificate
						// and throw up the appropriate dialog.
						LLPointer<LLCertificate> certificate = gSecAPIHandler->getCertificate(response["certificate"]);
						if(certificate)
						{
							LLSD args = transform_cert_args(certificate);

							if(error_code == "SSL_CACERT")
							{
								// if we are handling an untrusted CA, throw up the dialog                             
								// with the 'trust this CA' button.                                                    
								LLNotificationsUtil::add("TrustCertificateError", args, response,
														trust_cert_done);
								
								show_connect_box = true;
							}
							else
							{
								// the certificate exception returns a unique string for each type of exception.       
								// we grab this string via the LLUserAuth object, and use that to grab the localized   
								// string.                                                                             
								args["REASON"] = LLTrans::getString(message_response);
								
								LLNotificationsUtil::add("GeneralCertificateError", args, response,
														 general_cert_done);
								
								reset_login();
								gSavedSettings.setBOOL("AutoLogin", FALSE);
								show_connect_box = true;
								
							}

						}
					}
1167
					else if (!message.empty())
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
					{
						// This wasn't a certificate error, so throw up the normal
						// notificatioin message.
						LLSD args;
						args["ERROR_MESSAGE"] = emsg.str();
						LL_INFOS("LLStartup") << "Notification: " << args << LL_ENDL;
						LLNotificationsUtil::add("ErrorMessage", args, LLSD(), login_alert_done);
					}
				}
				transition_back_to_login_panel(emsg.str());
				show_connect_box = true;
			}
		}
		else if(LLLoginInstance::getInstance()->authSuccess())
		{
			if(process_login_success_response())
			{
				// Pass the user information to the voice chat server interface.
				LLVoiceClient::getInstance()->userAuthorized(gUserCredential->userID(), gAgentID);
				// create the default proximal channel
				LLVoiceChannel::initClass();
				LLStartUp::setStartupState( STATE_WORLD_INIT);
Richard Linden's avatar
Richard Linden committed
1190
				LLTrace::get_frame_recording().reset();
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
			}
			else
			{
				LLSD args;
				args["ERROR_MESSAGE"] = emsg.str();
				LL_INFOS("LLStartup") << "Notification: " << args << LL_ENDL;
				LLNotificationsUtil::add("ErrorMessage", args, LLSD(), login_alert_done);
				transition_back_to_login_panel(emsg.str());
				show_connect_box = true;
				return FALSE;
			}
		}
		return FALSE;
	}

	//---------------------------------------------------------------------
	// World Init
	//---------------------------------------------------------------------
	if (STATE_WORLD_INIT == LLStartUp::getStartupState())
	{
		set_startup_status(0.30f, LLTrans::getString("LoginInitializingWorld"), gAgent.mMOTD);
		display_startup();
		// We should have an agent id by this point.
		llassert(!(gAgentID == LLUUID::null));

		// Finish agent initialization.  (Requires gSavedSettings, builds camera)
		gAgent.init();
1218
		display_startup();
1219
		gAgentCamera.init();
1220
		display_startup();
1221
		set_underclothes_menu_options();
1222
		display_startup();
1223
1224
1225
1226
1227
1228

		// Since we connected, save off the settings so the user doesn't have to
		// type the name/password again if we crash.
		gSavedSettings.saveToFile(gSavedSettings.getString("ClientSettingsFile"), TRUE);
		LLUIColorTable::instance().saveUserSettings();

1229
1230
		display_startup();

1231
1232
1233
1234
		//
		// Initialize classes w/graphics stuff.
		//
		gTextureList.doPrefetchImages();		
1235
1236
		display_startup();

1237
		LLSurface::initClasses();
1238
1239
1240
		display_startup();

		display_startup();
1241
1242

		LLDrawable::initClass();
1243
		display_startup();
1244
1245
1246

		// init the shader managers
		LLPostProcess::initClass();
1247
		display_startup();
1248

1249
        LLAvatarAppearance::initClass("avatar_lad.xml","avatar_skeleton.xml");
1250
1251
		display_startup();

1252
		LLViewerObject::initVOClasses();
1253
		display_startup();
1254
1255
1256
1257

		// Initialize all our tools.  Must be done after saved settings loaded.
		// NOTE: This also is where gToolMgr used to be instantiated before being turned into a singleton.
		LLToolMgr::getInstance()->initTools();
1258
		display_startup();
1259
1260
1261
1262

		// Pre-load floaters, like the world map, that are slow to spawn
		// due to XML complexity.
		gViewerWindow->initWorldUI();
1263
		
1264
1265
1266
1267
1268
1269
1270
		display_startup();

		// This is where we used to initialize gWorldp. Original comment said:
		// World initialization must be done after above window init

		// User might have overridden far clip
		LLWorld::getInstance()->setLandFarClip(gAgentCamera.mDrawDistance);
1271
		display_startup();
1272
1273
1274
1275
1276
		// Before we create the first region, we need to set the agent's mOriginGlobal
		// This is necessary because creating objects before this is set will result in a
		// bad mPositionAgent cache.

		gAgent.initOriginGlobal(from_region_handle(gFirstSimHandle));
1277
		display_startup();
1278
1279

		LLWorld::getInstance()->addRegion(gFirstSimHandle, gFirstSim);
1280
		display_startup();
1281
1282
1283
1284

		LLViewerRegion *regionp = LLWorld::getInstance()->getRegionFromHandle(gFirstSimHandle);
		LL_INFOS("AppInit") << "Adding initial simulator " << regionp->getOriginGlobal() << LL_ENDL;
		
1285
1286
		LL_DEBUGS("CrossingCaps") << "Calling setSeedCapability from init_idle(). Seed cap == "
		<< gFirstSimSeedCap << LL_ENDL;
1287
1288
		regionp->setSeedCapability(gFirstSimSeedCap);
		LL_DEBUGS("AppInit") << "Waiting for seed grant ...." << LL_ENDL;
1289
		display_startup();
1290
1291
		// Set agent's initial region to be the one we just created.
		gAgent.setRegion(regionp);
1292
		display_startup();
1293
1294
1295
1296
		// Set agent's initial position, which will be read by LLVOAvatar when the avatar
		// object is created.  I think this must be done after setting the region.  JC
		gAgent.setPositionAgent(agent_start_position_region);

dolphin's avatar
dolphin committed
1297
1298
1299
		display_startup();
		LLStartUp::initExperiences();

1300
1301
		display_startup();
		LLStartUp::setStartupState( STATE_MULTIMEDIA_INIT );
1302

1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
		return FALSE;
	}


	//---------------------------------------------------------------------
	// Load QuickTime/GStreamer and other multimedia engines, can be slow.
	// Do it while we're waiting on the network for our seed capability. JC
	//---------------------------------------------------------------------
	if (STATE_MULTIMEDIA_INIT == LLStartUp::getStartupState())
	{
		LLStartUp::multimediaInit();
		LLStartUp::setStartupState( STATE_FONT_INIT );
1315
		display_startup();
1316
1317
1318
1319
1320
1321
1322
1323
		return FALSE;
	}

	// Loading fonts takes several seconds
	if (STATE_FONT_INIT == LLStartUp::getStartupState())
	{
		LLStartUp::fontInit();
		LLStartUp::setStartupState( STATE_SEED_GRANTED_WAIT );
1324
		display_startup();
1325
1326
1327
1328
1329
1330
1331
1332
		return FALSE;
	}

	//---------------------------------------------------------------------
	// Wait for Seed Cap Grant
	//---------------------------------------------------------------------
	if(STATE_SEED_GRANTED_WAIT == LLStartUp::getStartupState())
	{
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
		LLViewerRegion *regionp = LLWorld::getInstance()->getRegionFromHandle(gFirstSimHandle);
		if (regionp->capabilitiesReceived())
		{
			LLStartUp::setStartupState( STATE_SEED_CAP_GRANTED );
		}
		else
		{
			U32 num_retries = regionp->getNumSeedCapRetries();
			if (num_retries > 0)
			{
				LLStringUtil::format_map_t args;
				args["[NUMBER]"] = llformat("%d", num_retries + 1);
1345
				set_startup_status(0.4f, LLTrans::getString("LoginRetrySeedCapGrant", args), gAgent.mMOTD.c_str());
1346
1347
1348
			}
			else
			{
1349
				set_startup_status(0.4f, LLTrans::getString("LoginRequestSeedCapGrant"), gAgent.mMOTD.c_str());
1350
1351
			}
		}
1352
		display_startup();
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
		return FALSE;
	}


	//---------------------------------------------------------------------
	// Seed Capability Granted
	// no newMessage calls should happen before this point
	//---------------------------------------------------------------------
	if (STATE_SEED_CAP_GRANTED == LLStartUp::getStartupState())
	{
1363
		display_startup();
1364
		update_texture_fetch();
1365
		display_startup();
1366
1367
1368
1369
1370
1371
1372

		if ( gViewerWindow != NULL)
		{	// This isn't the first logon attempt, so show the UI
			gViewerWindow->setNormalControlsVisible( TRUE );
		}	
		gLoginMenuBarView->setVisible( FALSE );
		gLoginMenuBarView->setEnabled( FALSE );
1373
		display_startup();
1374

1375
1376
		// direct logging to the debug console's line buffer
		LLError::logToFixedBuffer(gDebugView->mDebugConsolep);
1377
		display_startup();
1378
1379
1380
		
		// set initial visibility of debug console
		gDebugView->mDebugConsolep->setVisible(gSavedSettings.getBOOL("ShowDebugConsole"));
1381
		display_startup();
1382
1383
1384
1385
1386
1387
1388
1389

		//
		// Set message handlers
		//
		LL_INFOS("AppInit") << "Initializing communications..." << LL_ENDL;

		// register callbacks for messages. . . do this after initial handshake to make sure that we don't catch any unwanted
		register_viewer_callbacks(gMessageSystem);
1390
		display_startup();
1391
1392
1393

		// Debugging info parameters
		gMessageSystem->setMaxMessageTime( 0.5f );			// Spam if decoding all msgs takes more than 500 ms
1394
		display_startup();
1395
1396
1397
1398
1399

		#ifndef	LL_RELEASE_FOR_DOWNLOAD
			gMessageSystem->setTimeDecodes( TRUE );				// Time the decode of each msg
			gMessageSystem->setTimeDecodesSpamThreshold( 0.05f );  // Spam if a single msg takes over 50ms to decode
		#endif
1400
		display_startup();
1401
1402

		gXferManager->registerCallbacks(gMessageSystem);
1403
		display_startup();
1404
1405

		LLStartUp::initNameCache();
1406
		display_startup();
1407
1408
1409
1410

		// update the voice settings *after* gCacheName initialization
		// so that we can construct voice UI that relies on the name cache
		LLVoiceClient::getInstance()->updateSettings();
1411
		display_startup();
1412

1413
1414
		// create a container's instance for start a controlling conversation windows
		// by the voice's events
1415
		LLFloaterIMContainer::getInstance();
1416
1417
1418
1419
1420
1421

		// *Note: this is where gWorldMap used to be initialized.

		// register null callbacks for audio until the audio system is initialized
		gMessageSystem->setHandlerFuncFast(_PREHASH_SoundTrigger, null_message_callback, NULL);
		gMessageSystem->setHandlerFuncFast(_PREHASH_AttachedSound, null_message_callback, NULL);
1422
		display_startup();
1423
1424

		//reset statistics
1425
		LLViewerStats::instance().resetStats();
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436

		display_startup();
		//
		// Set up region and surface defaults
		//


		// Sets up the parameters for the first simulator

		LL_DEBUGS("AppInit") << "Initializing camera..." << LL_ENDL;
		gFrameTime    = totalTime();
1437
		F32Seconds last_time = gFrameTimeSeconds;
1438
		gFrameTimeSeconds = (gFrameTime - gStartTime);
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451

		gFrameIntervalSeconds = gFrameTimeSeconds - last_time;
		if (gFrameIntervalSeconds < 0.f)
		{
			gFrameIntervalSeconds = 0.f;
		}

		// Make sure agent knows correct aspect ratio
		// FOV limits depend upon aspect ratio so this needs to happen before initializing the FOV below
		LLViewerCamera::getInstance()->setViewHeightInPixels(gViewerWindow->getWorldViewHeightRaw());
		LLViewerCamera::getInstance()->setAspect(gViewerWindow->getWorldViewAspectRatio());
		// Initialize FOV
		LLViewerCamera::getInstance()->setDefaultFOV(gSavedSettings.getF32("CameraAngle")); 
1452
		display_startup();
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462

		// Move agent to starting location. The position handed to us by
		// the space server is in global coordinates, but the agent frame
		// is in region local coordinates. Therefore, we need to adjust
		// the coordinates handed to us to fit in the local region.

		gAgent.setPositionAgent(agent_start_position_region);
		gAgent.resetAxes(gAgentStartLookAt);
		gAgentCamera.stopCameraAnimation();
		gAgentCamera.resetCamera();
1463
		display_startup();
1464
1465

		// Initialize global class data needed for surfaces (i.e. textures)
1466
1467
1468
1469
		LL_DEBUGS("AppInit") << "Initializing sky..." << LL_ENDL;
		// Initialize all of the viewer object classes for the first time (doing things like texture fetches.
		LLGLState::checkStates();
		LLGLState::checkTextureChannels();
1470

1471
		LLEnvManagerNew::getInstance()->usePrefs(); // Load all presets and settings
1472
		gSky.init(initial_sun_direction);
1473

1474
1475
		LLGLState::checkStates();
		LLGLState::checkTextureChannels();
1476

1477
1478
		display_startup();

1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
		LL_DEBUGS("AppInit") << "Decoding images..." << LL_ENDL;
		// For all images pre-loaded into viewer cache, decode them.
		// Need to do this AFTER we init the sky
		const S32 DECODE_TIME_SEC = 2;
		for (int i = 0; i < DECODE_TIME_SEC; i++)
		{
			F32 frac = (F32)i / (F32)DECODE_TIME_SEC;
			set_startup_status(0.45f + frac*0.1f, LLTrans::getString("LoginDecodingImages"), gAgent.mMOTD);
			display_startup();
			gTextureList.decodeAllImages(1.f);
		}
		LLStartUp::setStartupState( STATE_WORLD_WAIT );

1492
1493
		display_startup();

1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
		// JC - Do this as late as possible to increase likelihood Purify
		// will run.
		LLMessageSystem* msg = gMessageSystem;
		if (!msg->mOurCircuitCode)
		{
			LL_WARNS("AppInit") << "Attempting to connect to simulator with a zero circuit code!" << LL_ENDL;
		}

		gUseCircuitCallbackCalled = false;

		msg->enableCircuit(gFirstSim, TRUE);
		// now, use the circuit info to tell simulator about us!
		LL_INFOS("AppInit") << "viewer: UserLoginLocationReply() Enabling " << gFirstSim << " with code " << msg->mOurCircuitCode << LL_ENDL;
		msg->newMessageFast(_PREHASH_UseCircuitCode);
		msg->nextBlockFast(_PREHASH_CircuitCode);
		msg->addU32Fast(_PREHASH_Code, msg->mOurCircuitCode);
		msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID());
		msg->addUUIDFast(_PREHASH_ID, gAgent.getID());
		msg->sendReliable(
			gFirstSim,
			gSavedSettings.getS32("UseCircuitCodeMaxRetries"),
			FALSE,
1516
			(F32Seconds)gSavedSettings.getF32("UseCircuitCodeTimeout"),
1517
1518
1519
1520
			use_circuit_callback,
			NULL);

		timeout.reset();
1521
		display_startup();
1522
1523
1524
1525
1526

		return FALSE;
	}

	//---------------------------------------------------------------------
1527
	// World Wait
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
	//---------------------------------------------------------------------
	if(STATE_WORLD_WAIT == LLStartUp::getStartupState())
	{
		LL_DEBUGS("AppInit") << "Waiting for simulator ack...." << LL_ENDL;
		set_startup_status(0.59f, LLTrans::getString("LoginWaitingForRegionHandshake"), gAgent.mMOTD);
		if(gGotUseCircuitCodeAck)
		{
			LLStartUp::setStartupState( STATE_AGENT_SEND );
		}
		LLMessageSystem* msg = gMessageSystem;
		while (msg->checkAllMessages(gFrameCount, gServicePump))
		{
1540
			display_startup();
1541
1542
		}
		msg->processAcks();
1543
		display_startup();
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
		return FALSE;
	}

	//---------------------------------------------------------------------
	// Agent Send
	//---------------------------------------------------------------------
	if (STATE_AGENT_SEND == LLStartUp::getStartupState())
	{
		LL_DEBUGS("AppInit") << "Connecting to region..." << LL_ENDL;
		set_startup_status(0.60f, LLTrans::getString("LoginConnectingToRegion"), gAgent.mMOTD);
1554
		display_startup();
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
		// register with the message system so it knows we're
		// expecting this message
		LLMessageSystem* msg = gMessageSystem;
		msg->setHandlerFuncFast(
			_PREHASH_AgentMovementComplete,
			process_agent_movement_complete);
		LLViewerRegion* regionp = gAgent.getRegion();
		if(regionp)
		{
			send_complete_agent_movement(regionp->getHost());
			gAssetStorage->setUpstream(regionp->getHost());
			gCacheName->setUpstream(regionp->getHost());
			msg->newMessageFast(_PREHASH_EconomyDataRequest);
			gAgent.sendReliableMessage();
		}
1570
		display_startup();
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584

		// Create login effect
		// But not on first login, because you can't see your avatar then
		if (!gAgent.isFirstLogin())
		{
			LLHUDEffectSpiral *effectp = (LLHUDEffectSpiral *)LLHUDManager::getInstance()->createViewerEffect(LLHUDObject::LL_HUD_EFFECT_POINT, TRUE);
			effectp->setPositionGlobal(gAgent.getPositionGlobal());
			effectp->setColor(LLColor4U(gAgent.getEffectColor()));
			LLHUDManager::getInstance()->sendEffects();
		}

		LLStartUp::setStartupState( STATE_AGENT_WAIT );		// Go to STATE_AGENT_WAIT

		timeout.reset();
1585
		display_startup();