Subversion Repositories spk

Rev

Rev 102 | Rev 106 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 cycrow 1
#include "spk.h"
2
#include "emp.h"
3
 
4
#include <time.h>
5
#include <vector>
6
 
93 cycrow 7
#include "OriginalFiles.h"
98 cycrow 8
#include "spkdef.h"
93 cycrow 9
 
1 cycrow 10
#ifdef _RAR
11
#include <unrar.h>
12
#endif
13
 
14
enum {READ_START, READ_GLOBAL, READ_SCRIPT, READ_SCRIPTFILE, READ_WARES};
15
enum { EXTRACT, TEST, PRINT, LIST };
16
 
17
typedef struct SDummyEntry {
18
	CyString		sSection;
19
	CyStringList	lEntries;
20
} SDummyEntry;
21
 
22
typedef struct SComponantEntry2 {
23
	CyString		sSection;
24
	CyStringList	lEntries;
25
} SComponantEntry2;
26
 
27
typedef struct SComponantEntry {
28
	CyString		sSection;
29
	CLinkList<SComponantEntry2>	lEntries;
30
} SComponantEntry;
31
 
79 cycrow 32
CyString CPackages::m_sTempDir;
33
 
93 cycrow 34
CPackages::CPackages() : m_pCurrentGameExe(NULL),
35
	_pOriginalFiles(NULL)
1 cycrow 36
{
37
	m_bRenameText = false;
38
	m_iLanguage = 0;
39
	m_iGame = -1;
40
	m_iGameVersion = -1;
41
	m_iGameFlags = 0;
42
	m_bSurpressProtectedWarning = false;
43
	m_iMaxPatch = 1;
44
	m_iLastUpdated = 0;
45
	m_iFakePatch = -1;
46
	m_bVanilla = true;
47
	m_pEnabledMod = NULL;
48
	m_bForceModInstall = false;
49
	m_bLoaded = false;
50
	m_bRedo = false;
51
	m_bOldPlugin = false;
52
	m_bUsedWare = false;
53
	m_pPackageNode = NULL;
54
	m_bRemoveDir = false;
55
	m_bDisableVanilla = false;
56
	m_bLoadVFS = true;
57
	m_iSaveGame = -1;
58
	m_iSaveGameManager = -1;
59
	m_bForceEMP = false;
60
 
61
	for ( int i = 0; i < WAREBUFFERS; i++ )
62
		m_iWareBuffer[i] = 0;
63
	m_iShipBuffer = 0;
64
}
65
 
66
CPackages::~CPackages ()
67
{
68
	m_lDisableList.clear();
69
	m_lEnableList.clear();
70
	this->Reset();
71
}
72
 
73
void CPackages::SetVanilla(bool b)
74
{
75
	if ( m_bVanilla != b && b ) {
76
		for ( CListNode<CBaseFile> *pNode = m_lPackages.Front(); pNode; pNode = pNode->next() ) {
77
			pNode->Data()->SetModifiedEnabled(pNode->Data()->IsEnabled());
78
		}
79
	}
80
	m_bVanilla = b;
81
}
82
 
83
void CPackages::Reset()
84
{
85
	m_lFiles.MemoryClear();
86
	m_lUninstallFiles.MemoryClear();
87
	for ( CListNode<CBaseFile> *pNode = m_lPackages.Front(); pNode; pNode = pNode->next() )
88
		pNode->Data()->GetFileList()->clear();
89
	m_lPackages.MemoryClear();
93 cycrow 90
 
91
	SafeDelete(_pOriginalFiles);
92
 
1 cycrow 93
	m_iFakePatch = -1;
94
	m_bVanilla = false;
95
	m_pEnabledMod = NULL;
96
	m_bLoaded = false;
97
	m_iLanguage = 0;
98
	m_bOldPlugin = false;
99
	m_bRemoveDir = false;
100
	m_bDisableVanilla = false;
101
	m_bSurpressProtectedWarning = false;
102
	m_iSaveGame = -1;
103
	m_iSaveGameManager = -1;
104
	m_sSetMod = "";
105
 
106
	for ( int i = 0; i < WAREBUFFERS; i++ )
107
	{
108
		m_iWareBuffer[i] = 0;
109
		m_lGameWares[i].MemoryClear();
110
	}
111
	m_iShipBuffer = 0;
112
 
113
	m_lGameShips.MemoryClear();
114
	m_lAvailablePackages.MemoryClear();
115
	m_lInstallList.MemoryClear();
116
	m_lEnableList.MemoryClear();
117
	m_lDisableList.MemoryClear();
118
 
119
	m_lCreatedFiles.Clear();
120
	m_lNonRemovedFiles.Clear();
121
	m_lGlobals.Clear();
122
	m_lFakePatchOrder.Clear();
123
}
124
 
125
void CPackages::LoadVirtualFileSystem()
126
{
127
	if ( !m_bLoadVFS )
128
		return;
129
 
101 cycrow 130
	m_pGameVFS.setAddon(this->GetAddonDir().ToString());
1 cycrow 131
	if ( m_pEnabledMod )
132
	{
133
		C_File *f;
134
		for ( f = m_pEnabledMod->GetFirstFile(FILETYPE_MOD); f; f = m_pEnabledMod->GetNextFile(f) )
135
		{
136
			if ( f->IsFakePatch() ) continue;
137
			if ( f->CheckFileExt("cat") ) break;
138
		}
139
 
140
		if ( f )
35 cycrow 141
			m_pGameVFS.LoadFilesystem(m_sCurrentDir.ToString(), f->GetFilePointer().ToString(), 0);
1 cycrow 142
		else
35 cycrow 143
			m_pGameVFS.LoadFilesystem(m_sCurrentDir.ToString(), 0);
1 cycrow 144
	}
145
	else
35 cycrow 146
		m_pGameVFS.LoadFilesystem(m_sCurrentDir.ToString(), 0);
1 cycrow 147
}
148
 
83 cycrow 149
bool CPackages::isOldDir(const Utils::String &dir)
1 cycrow 150
{
151
	bool oldPlugin = false;
152
 
153
	CFileIO datFile(dir + "/PluginManager/pluginmanager.dat");
52 cycrow 154
	if ( datFile.exists() )
1 cycrow 155
	{
83 cycrow 156
		std::vector<Utils::String> *readFile = datFile.readLines();
1 cycrow 157
		if ( readFile )
158
		{
159
			for ( int i = 0; i < (int)readFile->size(); i++ )
160
			{
83 cycrow 161
				Utils::String line(readFile->at(i));
162
				Utils::String cmd = line.token(":", 1);
163
				if ( cmd.Compare("<script>") || cmd.Compare("</scripts>") )
1 cycrow 164
					break;
83 cycrow 165
				else if ( cmd.Compare("spkinstaller") || cmd.Compare("globalfiles") )
1 cycrow 166
					break;
83 cycrow 167
				else if ( cmd.Compare("pluginmanager") )
1 cycrow 168
				{
169
					oldPlugin = true;
170
					break;
171
				}
172
			}
173
 
174
			delete readFile;
175
		}
176
	}
177
 
178
	return oldPlugin;
179
}
180
 
181
bool CPackages::Read ( CyString dir, CProgressInfo *progress )
182
{
183
	m_sCurrentDir = dir;
184
	m_sCurrentDir = m_sCurrentDir.FindReplace("\\", "/");
185
	m_bOldPlugin = false;
186
	m_lCreatedFiles.Clear();
187
	m_bRemoveDir = false;
188
	m_bSurpressProtectedWarning = false;
189
	m_iSaveGame = -1;
190
	m_iSaveGameManager = -1;
191
	m_lNonRemovedFiles.Clear();
192
	m_lGlobals.Clear();
193
	m_lFakePatchOrder.Clear();
194
 
93 cycrow 195
	if ( _pOriginalFiles ) delete _pOriginalFiles;
196
	_pOriginalFiles = new COriginalFiles(m_sCurrentDir.ToString());
197
 
1 cycrow 198
	m_bVanilla = true;
199
 
200
	// check the pluginmanager data file exists
201
	CFileIO datFile(m_sCurrentDir + "/PluginManager/pluginmanager.dat");
52 cycrow 202
	if ( datFile.exists() )
1 cycrow 203
	{
83 cycrow 204
		std::vector<Utils::String> *readFile = datFile.readLines();
1 cycrow 205
		if ( readFile )
206
		{
207
			float fVersion = 0;
208
			bool spkinstaller = false;
209
			float fBeta = 0;
210
 
211
			int iStatus = READ_START;
212
			int iCount = 0;
213
			int iWare = -1;
214
			int iShip = -1;
215
 
216
			CBaseFile *packageFile = 0;
217
 
218
			for ( int i = 0; i < (int)readFile->size(); i++ )
219
			{
83 cycrow 220
				Utils::String line(readFile->at(i));
1 cycrow 221
 
83 cycrow 222
				Utils::String cmd = line.token(":", 1).lower();
223
				Utils::String rest = line.tokens(":", 2).removeFirstSpace();
1 cycrow 224
 
225
				if ( iStatus == READ_GLOBAL )
226
				{
227
					if ( cmd == "<script>" )
228
					{
229
						packageFile = new CSpkFile();
230
						iStatus = READ_SCRIPT;
231
					}
232
					else if ( cmd == "<ship>" )
233
					{
234
						packageFile = new CXspFile();
235
						iStatus = READ_SCRIPT;
236
					}
237
					else if ( cmd == "<base>" )
238
					{
239
						packageFile = new CBaseFile();
240
						iStatus = READ_SCRIPT;
241
					}
242
					else if ( cmd == "<archive>" )
243
					{
244
						packageFile = new CArchiveFile();
245
						iStatus = READ_SCRIPT;
246
					}
247
					else if ( cmd != "</scripts>" )
248
					{
249
						int game = 0;
250
						bool disabled = false;
83 cycrow 251
						Utils::String fileName = line.tokens(":", 5);
252
						Utils::String origName;
253
						if ( fileName.left(2) == "D#" )
1 cycrow 254
						{
83 cycrow 255
							fileName.erase(0, 2);
1 cycrow 256
							disabled = true;
257
						}
83 cycrow 258
						if ( fileName.left(2) == "G#" ) {
259
							fileName.erase(0, 2);
260
							game = fileName.token("#", 1).toLong();
261
							fileName = fileName.tokens("#", 2);
1 cycrow 262
						}
83 cycrow 263
						if ( fileName.isin("O#") )
1 cycrow 264
						{
83 cycrow 265
							origName = fileName.token("O#", 2);
266
							fileName = fileName.token("O#", 1);
1 cycrow 267
						}
268
 
269
						C_File *newFile = new C_File( m_sCurrentDir + fileName );
270
						newFile->SetGame(game);
271
						newFile->SetOriginalName(origName);
272
						newFile->SetDisabled(disabled);
83 cycrow 273
						newFile->SetFileType(line.token(":", 1).toLong());
274
						newFile->SetCreationTime((time_t)line.token(":", 2).toLong());
275
						newFile->SetDir(line.token(":", 3));
276
						if ( line.token(":", 4).toLong() )
1 cycrow 277
							newFile->SetShared(true);
278
						newFile->UpdateSigned();
279
 
280
						m_lFiles.push_back(newFile);
281
					}
282
				}
283
				else if ( iStatus == READ_SCRIPT )
284
				{
285
					if ( cmd == "installspk" )
83 cycrow 286
						packageFile->setFilename(rest);
1 cycrow 287
					else if ( cmd == "files" )
288
					{
289
						iStatus = READ_SCRIPTFILE;
290
						if ( spkinstaller )
291
						{
292
							int max;
83 cycrow 293
							Utils::String *files = rest.tokenise(" ", &max);
1 cycrow 294
 
295
							for ( int i = 0; i < max; i++ )
296
							{
83 cycrow 297
								int fileNum = files[i].toLong();
1 cycrow 298
								if ( fileNum >= 0 && fileNum < m_lFiles.size() )
299
									packageFile->AddFile(m_lFiles[fileNum]);
300
							}
301
 
302
							CLEANSPLIT(files, max);
303
						}
304
					}
305
					else if ( cmd == "disabled" )
306
						packageFile->SetEnabled(false);
307
					else if ( cmd == "modifieddisabled" )
308
						packageFile->SetModifiedEnabled(false);
309
					else if ( cmd == "icon" )
310
					{
83 cycrow 311
						C_File *icon = new C_File(CyString(rest.tokens(" ", 2)));
312
						packageFile->SetIcon(icon, rest.token(" ", 1));
1 cycrow 313
					}
314
					else
83 cycrow 315
						packageFile->ParseValueLine(line);
1 cycrow 316
				}
317
				else if ( iStatus == READ_SCRIPTFILE )
318
				{
319
					if ( cmd == "<script>" )
320
					{
321
						if ( packageFile->IsMod() && packageFile->IsEnabled() )
322
							m_pEnabledMod = packageFile;
323
 
324
						m_lPackages.push_back(packageFile);
325
						this->ConvertOldPackage(packageFile);
326
						packageFile = new CSpkFile();
327
						iStatus = READ_SCRIPT;
328
 
329
					}
330
					else if ( cmd == "<ship>" )
331
					{
332
						m_lPackages.push_back(packageFile);
333
						this->ConvertOldPackage(packageFile);
334
						packageFile = new CXspFile();
335
						iStatus = READ_SCRIPT;
336
					}
337
					else if ( cmd == "<base>" )
338
					{
339
						m_lPackages.push_back(packageFile);
340
						this->ConvertOldPackage(packageFile);
341
						packageFile = new CBaseFile();
342
						iStatus = READ_SCRIPT;
343
					}
344
					else if ( cmd == "<archive>" )
345
					{
346
						m_lPackages.push_back(packageFile);
347
						this->ConvertOldPackage(packageFile);
348
						packageFile = new CArchiveFile();
349
						iStatus = READ_SCRIPT;
350
					}
351
					else if ( cmd == "</scripts>" )
352
					{
353
						if ( packageFile->IsMod() && packageFile->IsEnabled() )
354
							m_pEnabledMod = packageFile;
355
 
356
						m_lPackages.push_back(packageFile);
357
						this->ConvertOldPackage(packageFile);
358
					}
359
					else
360
					{
83 cycrow 361
						int fileNum = line.token("::", 1).toLong();
1 cycrow 362
						if ( fileNum >= 0 && fileNum < m_lFiles.size() )
363
							packageFile->AddFile(m_lFiles[fileNum]);
364
					}
365
				}
366
				else if ( iWare != -1 )
367
				{
368
					--iCount;
369
 
370
					SGameWare *gm = new SGameWare;
83 cycrow 371
					gm->iPos = line.token(" ", 1).toLong();
372
					gm->iType = line.token(" ", 2).toLong();
373
					gm->cType = line.token(" ", 3)[0];
1 cycrow 374
					gm->pWare = NULL;
83 cycrow 375
					gm->sWareName = line.tokens(" ", 4);
1 cycrow 376
					m_lGameWares[iWare].push_back(gm);
377
					if ( iCount <= 0 )
378
						iWare = -1;
379
				}
380
				else if ( iShip != -1 )
381
				{
382
					--iCount;
383
 
384
					SGameShip *gm = new SGameShip;
83 cycrow 385
					gm->iType = line.token(" ", 1).toLong();
386
					if ( line.token(" ", 2).left(4) == "$#C:" )
1 cycrow 387
					{
83 cycrow 388
						gm->sShipClass = line.token(" ", 2).right(-4);
389
						gm->sShipID = line.tokens(" ", 3);
1 cycrow 390
					}
391
					else
392
					{
83 cycrow 393
						gm->sShipID = line.tokens(" ", 2);
1 cycrow 394
						gm->sShipClass = "OBJ_SHIP_M5";
395
					}
396
					gm->pPackage = NULL;
397
					m_lGameShips.push_back(gm);
398
					if ( iCount <= 0 )
399
						iShip = -1;
400
				}
401
				else if ( cmd.Compare("savegamemanager") )
83 cycrow 402
					m_iSaveGameManager = rest.toLong();
1 cycrow 403
				else if ( cmd.Compare("savegame") )
83 cycrow 404
					m_iSaveGame = rest.toLong();
1 cycrow 405
				else if ( cmd == "fakepatch" )
83 cycrow 406
					m_iFakePatch = rest.toLong();
1 cycrow 407
				else if ( cmd == "updatetime" )
83 cycrow 408
					m_iLastUpdated = rest.toLong();
1 cycrow 409
				else if ( cmd == "surpressprotectedwarning" )
410
					m_bSurpressProtectedWarning = true;
411
				else if ( cmd == "pluginmanager" )
412
				{
83 cycrow 413
					fVersion = rest.toFloat();
1 cycrow 414
					m_bOldPlugin = true;
415
				}
416
				else if ( cmd == "setmod" )
417
					m_sSetMod = rest;
418
				else if ( cmd == "shipbuffer" )
83 cycrow 419
					m_iShipBuffer = rest.toLong();
1 cycrow 420
				else if ( cmd == "warebuffers" )
421
				{
83 cycrow 422
					int max = rest.countToken(" ");
1 cycrow 423
					for ( int i = 0; i < WAREBUFFERS; i++ )
424
					{
425
						if ( i > max )
426
							m_iWareBuffer[i] = 0;
427
						else
83 cycrow 428
							m_iWareBuffer[i] = rest.token(" ", i + 1).toLong();
1 cycrow 429
					}
430
				}
431
				else if ( cmd == "createdfile" )
83 cycrow 432
					m_lCreatedFiles.PushBack(CyString(rest));
1 cycrow 433
				else if ( cmd == "wares" )
434
				{
83 cycrow 435
					iWare = rest.token(" ", 1).toLong();
436
					iCount = rest.token(" ", 2).toLong();
1 cycrow 437
				}
438
				else if ( cmd == "ships" )
439
				{
440
					iShip = 1;
83 cycrow 441
					iCount = rest.token(" ", 1).toLong();
1 cycrow 442
				}
443
				else if ( cmd == "modified" )
444
					m_bVanilla = false;
445
				else if ( cmd == "spkinstaller" )
446
				{
83 cycrow 447
					fVersion = rest.toFloat();
1 cycrow 448
					spkinstaller = true;
449
				}
93 cycrow 450
				else if ( cmd == "betaversion" )
83 cycrow 451
					fBeta = rest.toFloat();
93 cycrow 452
				else if ( cmd == "uninstall" )
1 cycrow 453
				{
454
					C_File *uf = new C_File();
455
					uf->SetFileType(FILETYPE_SCRIPT);
83 cycrow 456
					uf->SetCreationTime(rest.token(" ", 1).toLong());
457
					uf->SetFilename(m_sCurrentDir + "/Scripts/" + rest.tokens(" ", 2));
1 cycrow 458
					m_lUninstallFiles.push_back(uf);
459
				}
93 cycrow 460
				else if ( cmd == "nonremovedfile" )
1 cycrow 461
				{
83 cycrow 462
					if ( !CFileIO::Remove(rest) )
463
						m_lNonRemovedFiles.PushBack(CyString(rest));
1 cycrow 464
				}
93 cycrow 465
				else if ( cmd == "original" )
466
					_pOriginalFiles->parse(rest);
1 cycrow 467
				else if ( cmd.Compare("GlobalSetting") )
83 cycrow 468
					m_lGlobals.PushBack(CyString(rest.token(":", 1)), CyString(rest.tokens(":", 2)));
1 cycrow 469
				else if ( cmd.Compare("FakePatchOrder") )
83 cycrow 470
					m_lFakePatchOrder.PushBack(CyString(rest.token(":", 1)), CyString(rest.tokens(":", 2)));
88 cycrow 471
				else if ( cmd.Compare("EMPPriceOverride") )
472
					this->addEMPPriceOverride(rest.token(" ", 1).toLong(), rest.token(" ", 2).toLong());
473
				else if ( cmd.Compare("EMPNotoOverride") )
474
					this->addEMPNotoOverride(rest.token(" ", 1).toLong(), rest.token(" ", 2).toLong());
475
				else if ( cmd.Compare("BuiltInWarePriceOverride") )
476
					this->addBuiltInWarePriceOverride(rest.token(" ", 1).toLong(), rest.token(" ", 2).toLong());
477
				else if ( cmd.Compare("BuiltInWareNotoOverride") )
478
					this->addBuiltInWareNotoOverride(rest.token(" ", 1).toLong(), rest.token(" ", 2).toLong());
479
				else if ( cmd.Compare("CustomWarePriceOverride") )
480
					this->addCustomWarePriceOverride(rest.token(";", 1), rest.token(";", 2).toLong());
481
				else if ( cmd.Compare("CustomWareNotoOverride") )
482
					this->addCustomWareNotoOverride(rest.token(";", 1), rest.token(";", 2).toLong());
1 cycrow 483
				else if ( cmd == "globalfiles" )
484
					iStatus = READ_GLOBAL;
485
 
486
				if ( progress )
487
				{
488
					progress->UpdateProgress((long)i, (long)readFile->size());
489
				}
490
			}
491
			readFile->clear();
492
 
493
			if ( !spkinstaller )
494
				m_bRedo = true;
495
 
496
			delete readFile;
497
		}
498
	}
499
 
500
	if ( m_pEnabledMod && !m_pEnabledMod->IsEnabled() )
501
		m_pEnabledMod = NULL;
502
 
56 cycrow 503
	m_iGame = m_gameExe.GetGameType(m_sCurrentDir.ToString()) + 1;
504
	m_pCurrentGameExe = m_gameExe.GetGame(m_gameExe.GetGameType(m_sCurrentDir.ToString()));
505
	Utils::String sGameVersion;
506
	m_iGameVersion = m_gameExe.GetGameVersion(m_sCurrentDir.ToString(), &sGameVersion) + 1;
507
	m_sGameVersion = sGameVersion;
1 cycrow 508
	m_iGameFlags = m_gameExe.GetGameFlags(m_iGame - 1);
509
	m_iMaxPatch = m_gameExe.GetMaxPatch(m_iGame - 1);
510
 
511
	// find the fake patch
512
	if ( !ReadyFakePatch() )
513
		return false;
514
 
515
	this->RemoveCreatedFiles();
87 cycrow 516
	this->createPluginManagerOpenText();
1 cycrow 517
 
518
	// match up wares
519
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
520
	{
521
		if ( node->Data()->GetType() == TYPE_SPK )
522
		{
523
			CSpkFile *p = (CSpkFile *)node->Data();
524
			for ( CListNode<SWares> *wNode = p->GetWaresList()->Front(); wNode; wNode = wNode->next() )
525
			{
526
				SWares *w = wNode->Data();
527
				for ( CListNode<SGameWare> *gNode = m_lGameWares[CPackages::ConvertWareType(w->cType)].Front(); gNode; gNode = gNode->next() )
528
				{
10 cycrow 529
					if ( w->sID == gNode->Data()->sWareName.ToString() )
1 cycrow 530
					{
531
						gNode->Data()->pWare = w;
532
						break;
533
					}
534
				}
535
			}
536
		}
537
		else if ( node->Data()->GetType() == TYPE_XSP )
538
		{
539
			CXspFile *p = (CXspFile *)node->Data();
540
			for ( CListNode<SGameShip> *gNode = m_lGameShips.Front(); gNode; gNode = gNode->next() )
541
			{
14 cycrow 542
				if ( p->GetShipID().Compare(gNode->Data()->sShipID.ToString()) )
1 cycrow 543
				{
544
					gNode->Data()->pPackage = p;
545
					break;
546
				}
547
			}
548
		}
549
	}
550
 
551
	// check the purged time
552
	this->PurgeGameObjects();
553
 
554
	m_bLoaded = true;
555
 
556
	return true;
557
}
558
 
559
void CPackages::RemoveCreatedFiles()
560
{
561
	for ( SStringList *node = m_lCreatedFiles.Head(); node; node = node->next )
562
	{
52 cycrow 563
		if ( CFileIO(node->str).ExistsOld() )
564
			CFileIO::Remove(node->str.ToString());
565
		else if ( CFileIO(m_sCurrentDir + "/" + node->str).ExistsOld() )
566
			CFileIO::Remove((m_sCurrentDir + "/" + node->str).ToString());
1 cycrow 567
	}
568
 
569
	m_lCreatedFiles.Clear();
570
}
571
 
572
void CPackages::PurgeGameObjects()
573
{
574
	// check for the log file
102 cycrow 575
	Utils::String logDir = logDirectory();
576
	CFileIO LogFile(logDir + "/log0" + Utils::String::PadNumber(PMTEXTFILE, 4) + ".txt");
52 cycrow 577
	if ( LogFile.exists() )
1 cycrow 578
	{
579
		// read the log file to memory
580
		std::vector<CyString> *lines = LogFile.ReadLines();
581
		if ( lines )
582
		{
583
			for ( int i = 0; i < (int)lines->size(); i++ )
584
			{
585
				CyString line(lines->at(i));
586
				CyString start = line.GetToken(":", 1, 1).ToLower();
587
				CyString rest = line.GetToken(":", 2, 2).RemoveFirstSpace();
588
				if ( start.Compare("purged") )
589
				{
590
					long time = rest.ToLong();
591
					if ( time == m_iLastUpdated )
592
					{
593
						this->PurgeWares();
594
						this->PurgeShips();
595
						this->RemoveUninstallScripts();
596
					}
597
				}
598
			}
599
 
600
			delete lines;
601
		}
602
		// remove the log file
52 cycrow 603
		LogFile.remove();
1 cycrow 604
	}
605
}
606
 
607
void CPackages::PurgeWares()
608
{
609
	// mark all delete wares as available
610
	for ( int i = 0; i < WAREBUFFERS; i++ )
611
	{
612
		for ( CListNode<SGameWare> *node = m_lGameWares[i].Front(); node; node = node->next() )
613
		{
614
			SGameWare *w = node->Data();
615
			if ( !w ) continue;
616
			if ( w->iType == WARETYPE_DELETED )
617
				w->iType = WARETYPE_NONE;
618
		}
619
		m_lGameWares[i].RemoveEmpty();
620
	}
621
}
622
 
623
void CPackages::PurgeShips()
624
{
625
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
626
	{
627
		if ( !node->Data() )
628
			continue;
629
		if ( node->Data()->iType == WARETYPE_DELETED )
630
			node->Data()->iType = WARETYPE_NONE;
631
	}
632
	m_lGameShips.RemoveEmpty();
633
}
634
 
102 cycrow 635
Utils::String CPackages::logDirectory()
1 cycrow 636
{
102 cycrow 637
	Utils::String logDir = m_sCurrentDir.ToString();
56 cycrow 638
	if ( m_iGameFlags & EXEFLAG_MYDOCLOG ) {
1 cycrow 639
		SGameExe *exe = m_gameExe.GetGame(m_iGame - 1);
56 cycrow 640
		if ( exe ) {
641
			if ( !exe->sMyDoc.empty() )
102 cycrow 642
				logDir = m_sMyDoc.ToString() + "/" + exe->sMyDoc;
1 cycrow 643
		}
644
	}
645
 
646
	return logDir;
647
}
648
 
102 cycrow 649
Utils::String CPackages::logDirectory(const Utils::String &gameExe)
1 cycrow 650
{
102 cycrow 651
	Utils::String logDir = m_sCurrentDir.ToString();
1 cycrow 652
	if ( m_iGameFlags & EXEFLAG_MYDOCLOG )
653
	{
57 cycrow 654
		SGameExe *exe = m_gameExe.gameExe(CFileIO(gameExe).filename());
1 cycrow 655
		if ( exe )
656
		{
56 cycrow 657
			if ( !exe->sMyDoc.empty() )
102 cycrow 658
				logDir = m_sMyDoc.ToString() + "/" + exe->sMyDoc;
1 cycrow 659
		}
660
	}
661
 
102 cycrow 662
	return CFileIO(logDir).fullFilename();
1 cycrow 663
}
664
 
102 cycrow 665
Utils::String CPackages::saveDirectory()
1 cycrow 666
{
102 cycrow 667
	Utils::String logDir = this->logDirectory();
1 cycrow 668
	if ( m_iGameFlags & EXEFLAG_NOSAVESUBDIR )
669
		return logDir;
670
 
671
	return logDir + "/save";
672
}
673
 
674
bool CPackages::ReadyFakePatch()
675
{
676
	// already exists, lets skip it
52 cycrow 677
	if ( CFileIO(m_sCurrentDir + "/PluginManager/PlugMan_Fake.cat").ExistsOld() && CFileIO(m_sCurrentDir + "/PluginManager/PlugMan_Fake.dat").ExistsOld() )
1 cycrow 678
		return true;
679
 
680
	// if only one of them exists, lets remove them
52 cycrow 681
	if ( CFileIO(m_sCurrentDir + "/PluginManager/PlugMan_Fake.cat").ExistsOld() )
682
		CFileIO::Remove(m_sCurrentDir.ToString() + "/PluginManager/PlugMan_Fake.cat");
683
	if ( CFileIO(m_sCurrentDir + "/PluginManager/PlugMan_Fake.dat").ExistsOld() )
684
		CFileIO::Remove(m_sCurrentDir.ToString() + "/PluginManager/PlugMan_Fake.dat");
1 cycrow 685
 
85 cycrow 686
	// fake patch is not being used
687
	if ( m_iFakePatch < 0 ) return true;
1 cycrow 688
	// now lets find the fake patch
689
	CyString useFile;
690
	if ( m_iFakePatch > 0 )
691
	{
692
		CyString file = CyString::Number(m_iFakePatch).PadNumber(2);
693
		if ( CheckValidPluginManagerFile(file) )
694
			useFile = file;
695
		else if ( CheckIfPluginManagerFile(file) )
696
			useFile = file;
697
	}
698
 
699
	if ( useFile.Empty() )
700
	{
701
		int nextfree = this->FindNextFakePatch();
702
		--nextfree; // gets the end fake patch
703
 
704
		// work backwards till we find a valid one
705
		while ( nextfree > m_iMaxPatch )
706
		{
707
			CyString file = CyString::Number(nextfree).PadNumber(2);
708
			if ( CheckValidPluginManagerFile(file) )
709
			{
710
				useFile = file;
711
				break;
712
			}
713
			--nextfree;
714
		}
715
	}
716
 
717
	CyString addonDir = this->GetAddonDir();
718
 
719
	// couldn't find the correct file, lets search for it
720
	if ( useFile.Empty() ) {
721
		int nextfree = this->FindNextFakePatch();
722
		--nextfree; // gets the end fake patch
723
 
724
		// work backwards till we find a valid one
725
		while ( nextfree > m_iMaxPatch )
726
		{
727
			CyString file = CyString::Number(nextfree).PadNumber(2);
728
			if ( CheckIfPluginManagerFile(file) )
729
			{
730
				useFile = file;
731
				break;
732
			}
733
			--nextfree;
734
		}		
735
	}
736
 
737
	if ( !useFile.Empty() )
738
	{
739
		// lets check whats in the file first
740
		CCatFile openCat;
741
		if ( openCat.Open(m_sCurrentDir + "/" + useFile + ".cat", addonDir, CATREAD_CATDECRYPT, false) == CATERR_NONE )
742
		{
743
			CLinkList<SInCatFile> *files = openCat.GetFiles();
744
			bool found = false;
745
			if ( files )
746
			{
747
				CyString useAddonDir = addonDir;
748
				if ( !useAddonDir.Empty() ) useAddonDir += "\\";
749
				for ( SInCatFile *inCat = files->First(); inCat; inCat = files->Next() )
750
				{
751
					if ( inCat->sFile.Compare("PlugMan\\TFake.pck") )
752
						continue;
753
					if ( inCat->sFile.Compare(useAddonDir + "t\\44" + CyString::Number(PMTEXTFILE).PadNumber(4) + ".pck") )
754
						continue;
755
					if ( inCat->sFile.Compare(useAddonDir + "t\\" + CyString::Number(PMTEXTFILE).PadNumber(4) + "-L044.pck") )
756
						continue;
757
 
758
					found = true;
759
					break;
760
				}
761
			}
762
 
763
			// no files, jsut delete them
764
			CFileIO catFile(m_sCurrentDir + "/" + useFile + ".cat");
765
			if ( !files || !found )
766
			{
52 cycrow 767
				if ( catFile.remove() )
1 cycrow 768
				{
769
					CFileIO datFile(m_sCurrentDir + "/" + useFile + ".dat");
52 cycrow 770
					if ( datFile.remove() )
1 cycrow 771
						return true;
772
				}
773
			}
774
			else
775
			{
776
				if ( catFile.Rename(m_sCurrentDir + "/PluginManager/PlugMan_Fake.cat") )
777
				{
778
					CFileIO datFile(m_sCurrentDir + "/" + useFile + ".dat");
779
 
780
					if ( datFile.Rename(m_sCurrentDir + "/PluginManager/PlugMan_Fake.dat") )
781
						return true;
782
 
783
					// TODO: it failed, restore cat file and do error
784
				}
785
			}
786
		}
787
 
788
		// if we're here, we tryed, and failed
789
		return false;
790
	}
85 cycrow 791
	// no files found, but we have a fake patch ? restore from backup
792
	else if ( m_iFakePatch > 0 ) {
793
		CLog::log(CLog::Log_Directory, 1, "PlugMan FakePatch seems to be missing (" + Utils::String::Number(m_iFakePatch) + "), Restoring from backup");
794
		CFileIO catFile(m_sCurrentDir + "/PluginManager/Backup/PlugMan_Fake.cat");
795
		if ( catFile.exists() ) {
796
			catFile.copy(m_sCurrentDir.ToString() + "/PluginManager/PlugMan_Fake.cat");
797
			CFileIO datFile(m_sCurrentDir + "/PluginManager/Backup/PlugMan_Fake.dat");
798
			if ( datFile.exists() ) datFile.copy(m_sCurrentDir.ToString() + "/PluginManager/PlugMan_Fake.dat");
799
		}
800
	}
1 cycrow 801
 
802
	// otherwise we didn't need to (hopefully)
803
	return true;
804
}
805
 
806
 
807
bool CPackages::CheckIfPluginManagerFile(CyString filename)
808
{
809
	bool found = false;
810
 
811
	CFileIO catFile(m_sCurrentDir + "/" + filename + ".cat");
52 cycrow 812
	if ( catFile.exists() && CFileIO(m_sCurrentDir + "/" + filename + ".dat").ExistsOld() )
1 cycrow 813
	{
814
		CCatFile openFile;
102 cycrow 815
		if ( openFile.Open(catFile.fullFilename(), this->GetAddonDir(), CATREAD_CATDECRYPT, false) == CATERR_NONE )
1 cycrow 816
		{
85 cycrow 817
//			if ( openFile.internaldatFilename().Compare("PlugMan_Fake.dat") ) return true;
1 cycrow 818
			int count = 0;
819
			int noncount = 0;
820
 
821
			// check for some of the files
822
			for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() ) {
823
				if ( node->Data()->GetFullDir().IsIn("::") ) {
824
					if (CFileIO(node->Data()->GetFullDir().GetToken("::", 1, 1)).GetFilename().Compare("PlugMan_Fake.cat") ) {
825
						CyString filename = node->Data()->GetFilePointer().GetToken("::", 2, 2);
826
						filename = filename.findreplace("/", "\\");
827
						if ( openFile.FindData(filename) )
828
							++count;
829
						else
830
							++noncount;
831
					}
832
				}
833
			}
834
 
835
			if ( (count && !noncount) || (count > noncount) )
836
				found = true;
837
		}
838
	}
839
 
840
	return found;
841
}
842
 
843
bool CPackages::CheckValidPluginManagerFile(CyString filename)
844
{
845
	// both the cat file and dat file exists, lets open it
846
	CFileIO catFile(m_sCurrentDir + "/" + filename + ".cat");
52 cycrow 847
	if ( catFile.exists() && CFileIO(m_sCurrentDir + "/" + filename + ".dat").ExistsOld() )
1 cycrow 848
	{
849
		CCatFile openFile;
102 cycrow 850
		if ( openFile.Open(catFile.fullFilename(), this->GetAddonDir(), CATREAD_CATDECRYPT, false) == CATERR_NONE )
1 cycrow 851
		{
852
			if ( openFile.FindData("PlugMan\\TFake.pck") )
853
				return true;
854
			if ( openFile.FindData("pluginmanagerfake.pck") )
855
				return true;
856
		}
857
	}
858
 
85 cycrow 859
	return false;
1 cycrow 860
}
861
 
862
/**
863
 * Converts a package in old format
864
 *
865
 * Some entries in older packages need to be changed for the new installer
866
 * These Include:
867
 *		- Game Version, old format is an id of position in the Data/exe file, new is 2 values, one for game, one for the version
868
 */
869
void CPackages::ConvertOldPackage(CBaseFile *package)
870
{
871
	for ( CListNode<SGameCompat> *gNode = package->GetGameCompatabilityList()->Front(); gNode; gNode = gNode->next() ) {
872
		if ( gNode->Data()->iGame == -1 ) {
873
			// all versions
874
			if ( gNode->Data()->iVersion == 0 )
875
				gNode->Data()->iGame = 0;
876
			else
877
			{
878
				int version = 0;
879
				gNode->Data()->iGame = m_gameExe.ConvertGameType(gNode->Data()->iVersion, &version);
880
				gNode->Data()->iVersion = version;
881
			}
882
		}
883
	}
884
 
49 cycrow 885
	if ( package->forumLink().empty() && package->webSite().isin("forum.egosoft")) {
886
		package->setForumLink(package->webSite());
887
		package->setWebSite("");
1 cycrow 888
	}
889
 
890
	// convert the version
891
	if ( package->GetType() == TYPE_SPK )
892
	{
893
		CSpkFile *spk = (CSpkFile *)package;
6 cycrow 894
		if ( spk->GetScriptType() == CSpkFile::SCRIPTTYPE_CUSTOM )
1 cycrow 895
		{
896
			CyString type = spk->GetScriptTypeString(44);
897
			if ( type.Compare("Ship Upgrade") )
6 cycrow 898
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_SHIPUPGRADE);
1 cycrow 899
			else if ( type.Compare("Trade Script") )
6 cycrow 900
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_TRADE);
1 cycrow 901
			else if ( type.Compare("Fleet Management") )
6 cycrow 902
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_FLEET);
1 cycrow 903
			else if ( type.Compare("Navigation Script") )
6 cycrow 904
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_NAVIGATION);
1 cycrow 905
			else if ( type.Compare("Piracy") )
6 cycrow 906
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_PIRACY);
1 cycrow 907
			else if ( type.Compare("Other") )
6 cycrow 908
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_OTHER);
1 cycrow 909
			else if ( type.Compare("Ship Command") )
6 cycrow 910
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_SHIPCOMMAND);
1 cycrow 911
			else if ( type.Compare("Station Command") )
6 cycrow 912
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_STATIONCOMMAND);
1 cycrow 913
			else if ( type.Compare("al plugin") )
6 cycrow 914
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_ALPLUGIN);
1 cycrow 915
			else if ( type.Compare("combat script") )
6 cycrow 916
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_COMBAT);
1 cycrow 917
			else if ( type.Compare("bbs and missions") )
6 cycrow 918
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_MISSION);
1 cycrow 919
			else if ( type.Compare("extension mod") )
6 cycrow 920
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_EXTENSION);
1 cycrow 921
			else if ( type.Compare("rebalance mod") )
6 cycrow 922
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_REBALANCE);
1 cycrow 923
			else if ( type.Compare("general mod") )
6 cycrow 924
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_GENERALMOD);
1 cycrow 925
			else if ( type.Compare("total conversion") )
6 cycrow 926
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_TOTAL);
1 cycrow 927
			else if ( type.Compare("cheat script") )
6 cycrow 928
				spk->SetScriptType(CSpkFile::SCRIPTTYPE_CHEAT);
1 cycrow 929
			else if ( type == "Library Script" )
930
			{
931
				spk->SetScriptType("");
932
				spk->SetLibrary();
933
			}
934
 
6 cycrow 935
			if ( spk->GetScriptType() != CSpkFile::SCRIPTTYPE_CUSTOM )
1 cycrow 936
				spk->SetScriptType("");
937
		}
938
	}
939
	else if ( package->GetType() == TYPE_XSP )
940
	{
941
		CXspFile *xsp = (CXspFile *)package;
14 cycrow 942
		Utils::String data = xsp->GetShipData();
1 cycrow 943
 
944
		for ( int i = 17; i <= 18; i++ )
945
		{
14 cycrow 946
			Utils::String model = data.token(";", i);
947
			Utils::String modelExt = model.right(4);
1 cycrow 948
			// check file extension
949
			if ( modelExt.Compare(".bod") || modelExt.Compare(".pbd") )
14 cycrow 950
				data = data.replaceToken(";", i, model.left(-4));
1 cycrow 951
		}
952
 
953
		xsp->SetShipData(data);
954
	}
955
 
956
	// any extra files that are in director folder
957
	if ( package->AnyFileType(FILETYPE_EXTRA) )
958
	{
959
		for ( C_File *f = package->GetFirstFile(FILETYPE_EXTRA); f; f = package->GetNextFile(f) )
960
		{
961
			if ( !f->GetDir().Compare("director") )
962
				continue;
963
			if ( f->CheckFileExt("xml") || f->CheckFileExt("pck") )
964
			{
965
				f->SetDir("");
966
				f->SetFileType(FILETYPE_MISSION);
967
			}
968
		}
969
	}
970
}
971
 
972
void CPackages::UpdatePackage(CBaseFile *p)
973
{
974
	if ( p->GetType() != TYPE_SPK )
975
		return;
976
 
977
	CSpkFile *package = (CSpkFile *)p;
978
 
979
	// update the signed status
980
	package->UpdateSigned(true);
981
 
982
	// check for another mod
983
	if ( !package->IsAnotherMod() )
984
		return;
985
 
986
	package->SetParent((CSpkFile *)FindSpkPackage(package->GetOtherName(), package->GetOtherAuthor()));
987
}
988
 
989
/**
990
 * Updates the package list once data has been read
991
 *
992
 * Finds any original Files
993
 * Updates Signed status of all packages
994
 */
995
bool CPackages::UpdatePackages(int doStatus, bool individual)
996
{
997
	// if theres no original files, then set the current structure as the base
998
	if ( doStatus == 0 || doStatus == -1 )
999
	{
93 cycrow 1000
		_pOriginalFiles->update(m_bRedo, &m_lFiles);
1 cycrow 1001
	}
1002
 
1003
	// update each package
1004
	// parent/child, signed status
1005
	if ( doStatus == -1 || doStatus == 1 )
1006
	{
1007
		if ( individual )
1008
		{
1009
			// no package, most likly none installed
1010
			if ( !m_pPackageNode )
1011
				return false;
1012
 
1013
			this->UpdatePackage(m_pPackageNode->Data());
1014
 
1015
			// move to the next package
1016
			m_pPackageNode = m_pPackageNode->next();
1017
			if ( !m_pPackageNode )
1018
				return false;
1019
		}
1020
		else
1021
		{
1022
			for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
1023
				this->UpdatePackage(node->Data());
1024
		}
1025
	}
1026
 
1027
	if ( doStatus == -1 || doStatus == 2 )
1028
		this->LoadVirtualFileSystem();
1029
 
1030
	// adjust save games
1031
	if ( doStatus == -1 || doStatus == 3 )
1032
	{
1033
	}
1034
 
1035
	m_bRedo = false;
1036
	return true;
1037
}
1038
 
1039
int CPackages::CheckOpenPackage(CyString file, int *error)
1040
{
1041
	// first check if it exists
52 cycrow 1042
	if ( !CFileIO(file).ExistsOld() )
1 cycrow 1043
	{
1044
		*error = INSTALLERR_NOEXIST;
1045
		return -1;
1046
	}
1047
 
1048
	// open the spk file
1049
	float fVersion = 0.0f;
1050
	int check = CBaseFile::CheckFile(file, &fVersion);
1051
 
1052
	// wrong version
1053
	if ( fVersion > (float)FILEVERSION )
1054
	{
1055
		*error = INSTALLERR_VERSION;
1056
		return -1;
1057
	}
1058
 
1059
	return check;
1060
}
1061
 
1062
CMultiSpkFile *CPackages::OpenMultiPackage(CyString file, int *error, CProgressInfo *progress)
1063
{
1064
	int check = CheckOpenPackage(file, error);
1065
	if ( *error == -1 )
1066
		return false;
1067
 
1068
	if ( check != SPKFILE_MULTI )
1069
	{
1070
		*error = INSTALLERR_NOMULTI;
1071
		return false;
1072
	}
1073
 
1074
	*error = INSTALLERR_NONE;
1075
 
1076
	CMultiSpkFile *package = new CMultiSpkFile;
1077
 
1078
	bool ret = false;
1079
	if ( package->ReadFile(file, true) )
1080
	{
1081
		if ( package->ReadAllPackages(SPKREAD_NODATA) )
1082
		{
1083
			for ( CListNode<SMultiSpkFile> *node = package->GetFileList()->Front(); node; node = node->next() )
1084
				this->ConvertOldPackage(node->Data()->pFile);
1085
 
1086
			ret = true;
1087
		}
1088
	}
1089
 
1090
	if ( ret )
1091
		return package;
1092
 
1093
	delete package;
1094
	return NULL;
1095
}
1096
 
1097
bool CPackages::OpenMultiPackage ( CyString file, CLinkList<CBaseFile> *packageList, int *error, CProgressInfo *progress )
1098
{
1099
	int check = CheckOpenPackage(file, error);
1100
	if ( *error == -1 )
1101
		return false;
1102
 
1103
	if ( check != SPKFILE_MULTI )
1104
	{
1105
		*error = INSTALLERR_NOMULTI;
1106
		return false;
1107
	}
1108
 
1109
	*error = INSTALLERR_NONE;
1110
 
1111
	CMultiSpkFile *package = new CMultiSpkFile;
1112
 
1113
	bool ret = false;
1114
	if ( package->ReadFile(file, true) )
1115
	{
1116
		if ( package->ReadAllPackages(SPKREAD_ALL, packageList) )
1117
		{
1118
			for ( CListNode<CBaseFile> *node = packageList->Front(); node; node = node->next() )
1119
				this->ConvertOldPackage(node->Data());
1120
 
1121
 
1122
			ret = true;
1123
		}
1124
	}
1125
 
1126
	delete package;
1127
 
1128
	return ret;
1129
}
1130
 
1131
int CPackages::PrepareMultiPackage ( CyString file, CLinkList<CBaseFile> *errorPackageList, int *error, CProgressInfo *progress )
1132
{
1133
	int check = CheckOpenPackage(file, error);
1134
	if ( *error == -1 )
1135
		return 0;
1136
 
1137
	if ( check != SPKFILE_MULTI )
1138
	{
1139
		*error = INSTALLERR_NOMULTI;
1140
		return 0;
1141
	}
1142
 
1143
	*error = INSTALLERR_NONE;
1144
 
1145
	CMultiSpkFile *package = new CMultiSpkFile;
1146
 
1147
	int count = 0;
1148
	if ( package->ReadFile(file, true) )
1149
	{
1150
		CLinkList<CBaseFile> packageList;
1151
		if ( package->ReadAllPackages(SPKREAD_ALL, &packageList) )
1152
		{
1153
			for ( CListNode<CBaseFile> *node = packageList.Front(); node; node = node->next() )
1154
			{
1155
				CBaseFile *p = node->Data();
1156
				this->ConvertOldPackage(p);
1157
				int error = this->PrepareInstallPackage(p);
1158
				if ( error )
1159
				{
1160
					node->Data()->SetLoadError(error);
1161
					errorPackageList->push_back(p);
1162
				}
1163
				else
1164
					++count;
1165
			}
1166
		}
1167
		packageList.clear();
1168
	}
1169
 
1170
	for ( SMultiSpkFile *ms = package->GetFileList()->First(); ms; ms = package->GetFileList()->Next() )
1171
		ms->pFile = NULL;
1172
	delete package;
1173
 
1174
	return count;
1175
}
1176
 
1177
CBaseFile *CPackages::OpenPackage(CyString file, int *error, CProgressInfo *progress, int readtype, int flags)
1178
{
1179
	int check = CheckOpenPackage(file, error);
1180
	if ( *error == -1 )
1181
		return NULL;
1182
 
1183
	CBaseFile *installFile = 0;
1184
 
1185
	if ( progress )
1186
		progress->DoHalf();
1187
 
1188
	switch (check)
1189
	{
1190
		case SPKFILE_OLD:
1191
			*error = INSTALLERR_OLD;
1192
			return NULL;
1193
		case SPKFILE_INVALID:
1194
			// convert xsp
1195
			if ( CFileIO(file).CheckFileExtension("xsp") )
1196
			{
1197
				installFile = new CXspFile();
39 cycrow 1198
				if ( !((CXspFile *)installFile)->ConvertOld(file.ToString()) )
1 cycrow 1199
				{
1200
					delete installFile;
1201
					return NULL;
1202
				}
1203
				break;
1204
			}
1205
			*error = INSTALLERR_INVALID;
1206
			return NULL;
1207
		case SPKFILE_BASE:
1208
			installFile = new CBaseFile();
1209
			if ( !installFile->ReadFile(file, readtype, progress) )
1210
			{
1211
				delete installFile;
1212
				return NULL;
1213
			}
1214
			break;
1215
		case SPKFILE_SINGLE:
1216
			installFile = new CSpkFile();
1217
			if ( !((CSpkFile *)installFile)->ReadFile(file, readtype, progress) )
1218
			{
1219
				delete installFile;
1220
				return NULL;
1221
			}
1222
			break;
1223
		case SPKFILE_MULTI:
1224
			*error = INSTALLERR_NOMULTI;
1225
			return NULL;
1226
		case SPKFILE_SINGLESHIP:
1227
			installFile = new CXspFile();
1228
			if ( !((CXspFile *)installFile)->ReadFile(file, readtype, progress) )
1229
			{
1230
				delete installFile;
1231
				return NULL;
1232
			}
1233
			break;
1234
 
1235
		default:
1236
			*error = INSTALLERR_UNKNOWN;
1237
			return NULL;
1238
	}
1239
 
1240
	if ( progress )
1241
		progress->SecondHalf();
1242
 
1243
	// now uncomress all files
1244
	if ( !(flags & READFLAG_NOUNCOMPRESS) )
1245
		installFile->UncompressAllFiles(progress);
1246
 
1247
	this->ConvertOldPackage (installFile);
1248
 
1249
	return installFile;
1250
}
1251
 
1252
void CPackages::PurgeUninstallScripts(CBaseFile *package, CyStringList *errors)
1253
{
1254
	for ( CListNode<C_File> *fNode = m_lUninstallFiles.Front(); fNode; fNode = fNode->next() )
1255
	{
1256
		C_File *uf = fNode->Data();
1257
		// check against any script files
1258
		for ( CListNode<C_File> *checkNode = package->GetFileList()->Front(); checkNode; checkNode = checkNode->next() )
1259
		{
1260
			C_File *checkFile = checkNode->Data();
1261
			if ( !checkFile ) continue;
1262
 
1263
			if ( checkFile->GetFileType() != FILETYPE_UNINSTALL && checkFile->GetFileType() != FILETYPE_SCRIPT )
1264
				continue;
1265
 
1266
			if ( uf->GetFilename().Compare(checkFile->GetFilename()) )
1267
			{
1268
				if ( RemoveUninstallFile(uf, errors) )
1269
					fNode->DeleteData();
1270
				break;
1271
			}
1272
		}
1273
	}
1274
 
1275
	m_lUninstallFiles.RemoveEmpty();
1276
 
1277
	this->WriteData();
1278
}
1279
 
1280
int CPackages::InstallPreparedPackages(CyStringList *errors, CProgressInfo *progress, CLinkList<CBaseFile> *errored, CLinkList<CBaseFile> *installedList)
1281
{
1282
	if ( m_lInstallList.empty() ) return false;
1283
 
1284
	int installed = 0;
1285
	for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
1286
	{
1287
		CBaseFile *p = node->Data();
1288
		if ( this->InstallPackage(p, errors, progress, !p->IsEnabled()) )
1289
		{
1290
			++installed;
1291
			if ( installedList )
1292
				installedList->push_back(p);
1293
		}
1294
		else if ( errored )
1295
		{
1296
			m_lPackages.remove(p);
1297
			errored->push_back(p);
1298
		}
1299
	}
1300
 
1301
	m_lInstallList.clear();
1302
 
1303
	this->WriteData();
1304
 
1305
	return installed;
1306
}
1307
 
50 cycrow 1308
void CPackages::_addToFakePatch(CBaseFile *pPackage)
1309
{
1310
	CCatFile cat;
1311
	if ( CCatFile::Opened(cat.Open(m_sCurrentDir + "/PluginManager/PlugMan_Fake.cat", this->GetAddonDir(), CATREAD_DAT)) ) {
1312
		for ( CListNode<C_File> *f = pPackage->GetFileList()->Front(); f; f = f->next() ) {
51 cycrow 1313
			if ( f->Data()->GetFileType() != FILETYPE_SHIPSCENE && f->Data()->GetFileType() != FILETYPE_COCKPITSCENE && f->Data()->GetFileType() != FILETYPE_SHIPMODEL && f->Data()->GetFileType() != FILETYPE_SHIPOTHER ) {
50 cycrow 1314
				continue;
51 cycrow 1315
			}
1316
			if ( CCatFile::IsAddonDir(f->Data()->GetNameDirectory(pPackage)) ) {
50 cycrow 1317
				continue;
51 cycrow 1318
			}
1319
			// check if its already in the fake patch
1320
			if ( f->Data()->GetFullDir().IsIn("::") ) {
1321
				continue;
1322
			}
52 cycrow 1323
			Utils::String toFile;
54 cycrow 1324
			if ( cat.AppendFile(f->Data()->GetFilePointer().ToString(), f->Data()->GetNameDirectory(pPackage).ToString(), true, (m_iGameFlags & EXEFLAG_NOXOR) ? false : true, &toFile) ) {
1325
				CLog::logf(CLog::Log_Install, 2, "Adding file: %s into the fake patch", f->Data()->GetNameDirectory(pPackage).c_str());
52 cycrow 1326
				CFileIO::Remove(f->Data()->GetFilePointer().ToString());
50 cycrow 1327
				f->Data()->SetFilename(m_sCurrentDir + "/PluginManager/PlugMan_Fake.cat::" + toFile);
1328
			}
1329
		}
1330
	}
1331
}
1332
 
85 cycrow 1333
bool CPackages::_checkForDisable(CBaseFile *package, bool disabled, CBaseFile *oldPackage)
1 cycrow 1334
{
85 cycrow 1335
	bool prevDisabled = disabled;
1336
 
1 cycrow 1337
	// first check if we are installed a mod
50 cycrow 1338
	if ( package->IsMod() && m_pEnabledMod && !m_bForceModInstall ) {
1 cycrow 1339
		disabled = true;
50 cycrow 1340
		CLog::log(CLog::Log_Install, 2, "Package is a mod and another mod is already enabled, setting to disabled");
1341
	}
1 cycrow 1342
	// if vanilla nad package aint signed
50 cycrow 1343
	if ( m_bVanilla && !package->IsSigned() ) {
1 cycrow 1344
		disabled = true;
50 cycrow 1345
		CLog::log(CLog::Log_Install, 2, "Package is a not signed and are we in vanilla mode, setting to disabled");
1346
	}
1 cycrow 1347
 
1348
	// check any depancies
50 cycrow 1349
	if ( !disabled && !this->CheckEnabledDependacy(package) ) {
1 cycrow 1350
		disabled = true;
50 cycrow 1351
		CLog::log(CLog::Log_Install, 2, "Dependacies missing for package, setting to disabled");
1352
	}
1 cycrow 1353
 
1354
	// search for an old version
1355
	if ( oldPackage && oldPackage == m_pEnabledMod && disabled )
1356
		disabled = prevDisabled;
1357
 
85 cycrow 1358
	return disabled;
1359
}
1360
 
1361
bool CPackages::InstallPackage ( CBaseFile *package, CyStringList *errors, CProgressInfo *progress, bool disabled )
1362
{
1363
	CLog::logf(CLog::Log_Install, 1, "Starting to install new package, %s by %s (Version: %s)", package->name().c_str(), package->author().c_str(), package->version().c_str());
1364
 
1365
	CBaseFile *oldPackage = FindPackage(package);
1366
	disabled = _checkForDisable(package, disabled, oldPackage);
1367
 
1 cycrow 1368
	// update packages must have an old package installed already (should have been checked for already)
1369
	if ( package->GetType() == TYPE_SPK )
1370
	{
1371
		if ( ((CSpkFile *)package)->IsPackageUpdate() )
1372
		{
50 cycrow 1373
			CLog::log(CLog::Log_Install, 3, "Package is an Update, checking for existing package installed");
1374
			if ( !oldPackage ) {
1375
				CLog::log(CLog::Log_Install, 2, "Package is an Update but no existing package found, cancelling install");
1 cycrow 1376
				return false;
50 cycrow 1377
			}
1 cycrow 1378
			// change any mods to temp ones
1379
			for ( CListNode<C_File> *f = package->GetFileList()->Front(); f; f = f->next() )
1380
			{
1381
				if ( f->Data()->GetFileType() != FILETYPE_MOD )
1382
					continue;
1383
 
1384
				f->Data()->SetDir("temp");
50 cycrow 1385
				if ( f->Data()->IsFakePatch() ) {
1386
					CLog::logf(CLog::Log_Install, 2, "Moving fake package to temporary location to preper for update, %s", f->Data()->GetFilePointer().c_str());
1 cycrow 1387
					f->Data()->SetName(CyString("Fake_") + f->Data()->GetName());
50 cycrow 1388
				}
1 cycrow 1389
			}
1390
		}
1391
	}
1392
 
1393
	// no need to backup if we're disabling them
1394
	if ( !disabled )
1395
	{
1396
		// find any uninstall files and remove them
50 cycrow 1397
		CLog::log(CLog::Log_Install, 3, "Purging uninstall scripts");
1 cycrow 1398
		this->PurgeUninstallScripts(package, errors);
1399
 
1400
		// backup any original files before installing
93 cycrow 1401
		_pOriginalFiles->backup(package, errors);
1 cycrow 1402
	}
1403
 
1404
	// install all the files
50 cycrow 1405
	CLog::log(CLog::Log_Install, 3, "Checking for any existing files");
1 cycrow 1406
	if ( oldPackage )
1407
	{
50 cycrow 1408
		CLog::logf(CLog::Log_Install, 3, "Excluding existing package (%s) from file check list", oldPackage->version().c_str());
1 cycrow 1409
		CLinkList<CBaseFile> excludeList;
1410
		excludeList.push_back(oldPackage);
1411
		this->UpdateUsedFiles(&excludeList, true);
1412
	}
1413
	else
1414
		this->UpdateUsedFiles(0, true);
1415
 
50 cycrow 1416
	CLog::log(CLog::Log_Install, 3, "Reading all files into memory");
1 cycrow 1417
	package->ReadAllFilesToMemory();
50 cycrow 1418
 
1419
	CLog::log(CLog::Log_Install, 3, "Starting to install files");
1 cycrow 1420
	if ( !package->InstallFiles (m_sCurrentDir, progress, &m_lFiles, errors, !disabled, this) )
1421
	{
50 cycrow 1422
		CLog::log(CLog::Log_Install, 2, "There was an error installing files!!");
1423
 
1 cycrow 1424
		// TODO: clear up installed files
1425
		return false;
1426
	}
1427
 
105 cycrow 1428
	_pOriginalFiles->installed(package);
1429
 
1 cycrow 1430
	// if we're installing an addon, lets use the fake patch method for object files
50 cycrow 1431
	if ( m_iGameFlags & EXEFLAG_ADDON ) this->_addToFakePatch(package);
1 cycrow 1432
 
1433
	bool shuffle = false;
1434
 
1435
	// merge the update into the old package
1436
	bool dontAdd = false;
1437
	if ( package->GetType() == TYPE_SPK )
1438
	{
1439
		if ( ((CSpkFile *)package)->IsPackageUpdate() )
1440
		{
1441
			// now copy any files from a mod
1442
			for ( CListNode<C_File> *f = package->GetFileList()->Front(); f; f = f->next() )
1443
			{
1444
				if ( !f->Data() )
1445
					continue;
1446
				if ( f->Data()->GetFileType() != FILETYPE_MOD )
1447
					continue;
1448
				// we only need the cat file
1449
				if ( !f->Data()->CheckFileExt("cat") )
1450
					continue;
1451
 
1452
				// if fake patch, find first fake patch in package
1453
				C_File *findMatching = NULL;
1454
				if ( f->Data()->GetBaseName().Left(5).Compare("fake_") )
1455
				{
1456
					for ( CListNode<C_File> *node = oldPackage->GetFileList()->Front(); node; node = node->next() )
1457
					{
1458
						if ( !node->Data() )
1459
							continue;
1460
						if ( node->Data()->GetFileType() != FILETYPE_MOD )
1461
							continue;
1462
						// we only need the cat file
1463
						if ( !node->Data()->CheckFileExt("cat") )
1464
							continue;
1465
						if ( !node->Data()->IsFakePatch() )
1466
							continue;
1467
 
1468
						findMatching = node->Data();
1469
						break;
1470
					}
1471
				}
1472
				// otherwise, just add to the mod of the same name
1473
				else
1474
				{
1475
					for ( CListNode<C_File> *node = oldPackage->GetFileList()->Front(); node; node = node->next() )
1476
					{
1477
						if ( !node->Data() )
1478
							continue;
1479
						if ( node->Data()->GetFileType() != FILETYPE_MOD )
1480
							continue;
1481
						// we only need the cat file
1482
						if ( !node->Data()->CheckFileExt("cat") )
1483
							continue;
1484
 
1485
						if ( node->Data()->GetName().Compare(f->Data()->GetName()) )
1486
						{
1487
							findMatching = node->Data();
1488
							break;
1489
						}
1490
					}
1491
				}
1492
 
1493
				if ( findMatching )
1494
				{
1495
					// copy accross all mods
1496
					CCatFile catTo, catFrom;
1497
					if ( catFrom.Open(f->Data()->GetFilePointer(), this->GetAddonDir(), CATREAD_CATDECRYPT, false) == CATERR_NONE )
1498
					{
1499
						if ( catTo.Open(findMatching->GetFilePointer(), this->GetAddonDir(), CATREAD_CATDECRYPT, false) == CATERR_NONE )
1500
						{
1501
							for ( int i = 0; i < catFrom.GetNumFiles(); i++ )
1502
							{
1503
								SInCatFile *c = catFrom.GetFile(i);								 
52 cycrow 1504
								catTo.AppendFile((f->Data()->GetFilePointer() + "::" + c->sFile).ToString(), c->sFile.ToString());
1 cycrow 1505
							}
1506
						}
1507
					}
1508
 
1509
					// now remove the files
1510
					C_File *m = package->FindMatchingMod(f->Data());
1511
					RemoveFile(f->Data(), errors);
1512
					m_lFiles.remove(f->Data());
1513
					f->ChangeData(NULL);
1514
					if ( m )
1515
					{
1516
						int pos = package->GetFileList()->FindPos(m);
1517
						RemoveFile(m, errors);
1518
						m_lFiles.remove(m);
1519
						if ( pos != -1 )
1520
							package->GetFileList()->GetNode(pos)->ChangeData(NULL);
1521
					}
1522
				}
1523
				// no matching file, then we shall just renaming back
1524
				else
1525
				{
1526
					if ( f->Data()->GetBaseName().Left(5).Compare("fake_") )
1527
					{
1528
						shuffle = true;
1529
						C_File *match = package->FindMatchingMod(f->Data());
1530
						CyString next = CyString::Number(this->FindNextFakePatch()).PadNumber(2);
1531
 
1532
						CyString oldFilePointer = f->Data()->GetFilePointer();
1533
						f->Data()->SetDir("");
1534
						f->Data()->ChangeBaseName(next);
1535
						if ( CFileIO(oldFilePointer).Rename(m_sCurrentDir + "/" + f->Data()->GetNameDirectory(package)) )
1536
							f->Data()->SetFilename(m_sCurrentDir + "/" + f->Data()->GetNameDirectory(package));
1537
 
1538
						if ( match )
1539
						{
1540
							CyString oldFilePointer = match->GetFilePointer();
1541
							match->SetDir("");
1542
							match->ChangeBaseName(next);
1543
							if ( CFileIO(oldFilePointer).Rename(m_sCurrentDir + "/" + match->GetNameDirectory(package)) )
1544
								match->SetFilename(m_sCurrentDir + "/" + match->GetNameDirectory(package));
1545
						}
1546
					}
1547
					else
1548
					{
1549
						C_File *match = package->FindMatchingMod(f->Data());
1550
 
1551
						f->Data()->SetDir("");
1552
						if ( CFileIO(f->Data()->GetFilePointer()).Rename(m_sCurrentDir + "/" + f->Data()->GetNameDirectory(package)) )
1553
							f->Data()->SetFilename(m_sCurrentDir + "/" + f->Data()->GetNameDirectory(package));
1554
						if ( match )
1555
						{
1556
							match->SetDir("");
1557
							if ( CFileIO(match->GetFilePointer()).Rename(m_sCurrentDir + "/" + match->GetNameDirectory(package)) )
1558
								match->SetFilename(m_sCurrentDir + "/" + match->GetNameDirectory(package));
1559
						}
1560
					}
1561
				}
1562
			}
1563
 
1564
			package->GetFileList()->RemoveEmpty();
1565
			((CSpkFile *)oldPackage)->MergePackage(package);
1566
			delete package;
1567
			package = oldPackage;
1568
			oldPackage = false;
1569
			dontAdd = true;
1570
 
1571
			CDirIO(m_sCurrentDir).RemoveDir("temp");
1572
			CDirIO(m_sCurrentDir).RemoveDir("Mods/temp");
1573
		}
1574
	}
1575
 
1576
	// if theres an icon, write it
1577
	if ( package->GetIcon() )
1578
	{
50 cycrow 1579
		CLog::log(CLog::Log_Install, 3, "Checking to install icon display file");
1 cycrow 1580
		C_File *icon = package->GetIcon();
50 cycrow 1581
		if ( !icon->GetData() || !icon->GetDataSize() ) {
1 cycrow 1582
			package->SetIcon(NULL, "");
50 cycrow 1583
			CLog::log(CLog::Log_Install, 2, "Unable to extract icon, clearing");
1584
		}
1 cycrow 1585
		else
1586
		{
1587
			CDirIO Dir(m_sCurrentDir);
1588
			bool ready = true;
1589
			if ( !Dir.Exists("PluginManager") )
1590
			{
1591
				if ( !Dir.Create("PluginManager") )
1592
					ready = false;
1593
			}
1594
			if ( ready && !Dir.Exists("PluginManager/Icons") )
1595
			{
1596
				if ( !Dir.Create("PluginManager/Icons") )
1597
					ready = false;
1598
			}
1599
 
1600
			if ( ready )
1601
			{
1602
				if ( !icon->UncompressData() )
1603
					package->SetIcon(NULL, "");
1604
				else
1605
				{
50 cycrow 1606
					CFileIO iconFile(m_sCurrentDir + "/PluginManager/Icons/" + package->author() + "_" + package->name() + "." + package->GetIconExt());
1 cycrow 1607
					if ( iconFile.WriteData((const char *)icon->GetData(), icon->GetDataSize()) )
1608
					{
50 cycrow 1609
						icon->SetFilename(CyString(package->author()) + "_" + package->name() + "." + package->GetIconExt());
1 cycrow 1610
						icon->SetFullDir(m_sCurrentDir + "/PluginManager/Icons");
1611
					}
1612
					else
1613
						package->SetIcon(NULL, "");
1614
				}
1615
			}
1616
 
1617
			if ( package->GetIcon() )
1618
				package->GetIcon()->DeleteData();
1619
		}
1620
	}
1621
 
1622
	// remove all data
50 cycrow 1623
	CLog::log(CLog::Log_Install, 3, "Clearing all unneeded file data");
1 cycrow 1624
	package->ClearFileData();
1625
 
1626
	// add to list
1627
	if ( !dontAdd )
1628
	{
50 cycrow 1629
		CLog::log(CLog::Log_Install, 1, "Adding package into main list");
1 cycrow 1630
		if ( oldPackage )
1631
		{
98 cycrow 1632
			// find all other packages that has the old package as parent and switch to new
1633
			for(CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next()) {
1634
				if ( node->Data()->GetParent() == oldPackage ) {
1635
					node->Data()->SetParent(package);
1636
				}
1637
			}
1638
 
1639
			// remove olld package from list, and replace it with the new one
1 cycrow 1640
			m_lPackages.insert(oldPackage, package);
1641
			m_lPackages.remove(oldPackage, false);
1642
		}
1643
		else
1644
			m_lPackages.push_back (package);
1645
	}
1646
 
50 cycrow 1647
	CLog::log(CLog::Log_Install, 2, "Updating file used count");
1 cycrow 1648
	UpdateUsedFiles();
1649
 
50 cycrow 1650
	if ( disabled ) package->SetEnabled(false);
1 cycrow 1651
 
1652
	// remove any files no longer used by old package
1653
	if ( oldPackage )
1654
	{
50 cycrow 1655
		CLog::log(CLog::Log_Install, 3, "Removing any unused files from previous package");
1656
 
1 cycrow 1657
		CListNode<C_File> *fnode = oldPackage->GetFileList()->Front();
1658
		while ( fnode )
1659
		{
1660
			C_File *f = fnode->Data();
1661
 
1662
			// no longer used
1663
			if ( !f->GetUsed() )
1664
			{
1665
				// remove from file list
1666
				m_lFiles.remove(f, false);
1667
 
85 cycrow 1668
				// if its a readme file, then check if its in the new package
1669
				bool dontRemove = false;
1670
				if ( f->GetFileType() == FILETYPE_README ) {
1671
					if ( package->FindFile(f->GetFilename(), FILETYPE_README) )
1672
						dontRemove = true;
1673
				}
1674
 
1 cycrow 1675
				// remove from hard drive
85 cycrow 1676
				if ( !dontRemove && RemoveFile(f, errors) )
1 cycrow 1677
				{
50 cycrow 1678
					CLog::logf(CLog::Log_Install, 1, "Removed unused file: %s", f->GetFilePointer().c_str());
1 cycrow 1679
					// if a fake patch, we need to shufle
1680
					if ( f->IsFakePatch() )
1681
						shuffle = true;
1682
					else if ( f->IsAutoTextFile() )
1683
						shuffle = true;
1684
				}
1685
			}
1686
 
1687
			fnode = fnode->next();
1688
		}
1689
 
1690
	}
1691
 
1692
	if ( shuffle )
1693
	{
50 cycrow 1694
		CLog::log(CLog::Log_Install, 2, "Shuffling Fake patches");
1 cycrow 1695
		ShuffleFakePatches(errors);
50 cycrow 1696
		CLog::log(CLog::Log_Install, 2, "Shuffling Text Files");
1 cycrow 1697
		ShuffleTextFiles(errors);
1698
	}
1699
 
1700
	// now we need to link any child/parent packages
1701
	if ( package->GetType() == TYPE_SPK )
1702
	{
1703
		CSpkFile *spk = (CSpkFile *)package;
50 cycrow 1704
		if ( spk->IsAnotherMod() ) {
1 cycrow 1705
			spk->SetParent((CSpkFile *)FindSpkPackage(spk->GetOtherName(), spk->GetOtherAuthor()));
50 cycrow 1706
			CLog::logf(CLog::Log_Install, 2, "Linking to parent package: %s by %s (Version: %s)", spk->name().c_str(), spk->author().c_str(), spk->version().c_str());
1707
		}
1 cycrow 1708
	}
1709
 
1710
	// store enabled mod
50 cycrow 1711
	if ( package->IsMod() && !disabled ) {
1 cycrow 1712
		m_pEnabledMod = package;
50 cycrow 1713
		CLog::log(CLog::Log_Install, 1, "Setting package as primary mod");
1714
	}
1 cycrow 1715
 
88 cycrow 1716
	package->updateTextDB();
1717
 
1 cycrow 1718
	m_bRemoveDir = true;
1719
 
50 cycrow 1720
	CLog::log(CLog::Log_Install, 1, "Saving data to file");
1 cycrow 1721
	this->WriteData();
1722
 
50 cycrow 1723
	CLog::log(CLog::Log_Install, 1, "Installation Finished");
1 cycrow 1724
	return true;
1725
}
1726
 
1727
bool CPackages::UninstallPreparedPackages(CyStringList *errors, CProgressInfo *progress, CLinkList<CBaseFile> *uninstalledPackages, CLinkList<CBaseFile> *disabledPackages)
1728
{
1729
	if ( m_lInstallList.empty() ) return false;
1730
 
1731
	// update the used status, excluding all packages we are about to remove
1732
	UpdateUsedFiles(&m_lInstallList);
1733
 
1734
	CyStringList removeDirs;
1735
	CLinkList<C_File> uninstallFiles;
1736
	CLinkList<C_File> fileList;
1737
	bool readme = false, original = false, shuffle = false;
1738
 
1739
	// find all files that need to be removed
1740
	int maxFiles = 0;
1741
	for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
1742
	{
1743
		CBaseFile *p = node->Data();
1744
		maxFiles += this->GetAllPackageFiles(p, &fileList, true);
1745
 
1746
		// disable any dependants
1747
		if ( p->GetType() == TYPE_SPK && ((CSpkFile *)p)->IsLibrary() )
1748
		{
1749
			CLinkList<CBaseFile> depList;
1750
			if ( this->GetDependacyList(p, &depList) )
1751
			{
1752
				for ( CBaseFile *depP = depList.First(); depP; depP = depList.Next() )
1753
				{
1754
					if ( depP->IsEnabled() )
1755
						this->PrepareDisablePackage(depP);
1756
				}
1757
 
1758
				if ( m_lDisableList.size() )
1759
					this->DisablePreparedPackages(errors, progress, disabledPackages);
1760
			}
1761
		}
1762
	}
1763
 
1764
	// interate through all the files in the package
1765
	int fileCount = 0;
1766
	for ( CListNode<C_File> *node = fileList.Front(); node; node = node->next() )
1767
	{
1768
		C_File *f = node->Data();
1769
 
1770
		// display progress if needed
1771
		if ( progress )
1772
		{
1773
			progress->UpdateProgress(fileCount++, maxFiles);
1774
			progress->UpdateFile(f);
1775
		}
1776
 
1777
		// skip uninstall files
1778
		if ( f->GetFileType() == FILETYPE_UNINSTALL )
1779
		{
1780
			uninstallFiles.push_back(f);
1781
			continue;
1782
		}
1783
 
1784
		// only delete files that are not used
1785
		// if its a shared file, we skip it
1786
		if ( f->GetUsed() || f->IsShared() )
1787
			continue;
1788
 
1789
		if ( f->GetFileType() == FILETYPE_README )
1790
			readme = true;
1791
		else if ( f->GetFileType() == FILETYPE_UNINSTALL || f->GetFileType() == FILETYPE_MAP || f->GetFileType() == FILETYPE_SOUND || f->GetFileType() == FILETYPE_EXTRA || f->GetFileType() == FILETYPE_SHIPSCENE || f->GetFileType() == FILETYPE_COCKPITSCENE || f->GetFileType() == FILETYPE_SHIPOTHER || f->GetFileType() == FILETYPE_SHIPMODEL || f->GetFileType() == FILETYPE_ADVERT )
1792
		{
1793
			CyString dir = f->GetDirectory(NULL);
1794
			removeDirs.PushBack(dir, true);
1795
			dir = dir.FindReplace("\\", "/");
1796
			if ( dir.IsIn("/") )
1797
			{
1798
				for ( int i = dir.NumToken("/"); i; i-- )
1799
				{
1800
					CyString remDir = dir.GetToken("/", 1, i);
1801
					removeDirs.PushBack(remDir, true);
1802
				}
1803
			}
1804
		}
1805
 
1806
		if ( f->GetFileType() == FILETYPE_EXTRA && f->GetDir().Left(6).lower() == "extras" )
1807
			removeDirs.PushBack("Extras", true);
1808
 
1809
		if ( RemoveFile(f, errors) )
1810
		{
93 cycrow 1811
			original = _pOriginalFiles->restoreFile(f, errors);
1 cycrow 1812
		}
1813
		else // problem removeing (try when the program closes)
1814
			m_lNonRemovedFiles.PushBack(f->GetFilePointer());
1815
 
1816
		// check for fake patchs
1817
		if ( f->IsFakePatch() )
1818
			shuffle = true;
1819
		else if ( f->IsAutoTextFile() )
1820
			shuffle = true;
1821
 
1822
		// remove the file from the main list as swell
1823
		m_lFiles.remove(f, false);
1824
		delete f;
1825
	}
1826
 
1827
	// remove all the packages from memory
1828
	for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
1829
	{
1830
		CBaseFile *p = node->Data();
1831
		p->GetFileList()->clear();
1832
		m_lPackages.remove(p);
1833
 
1834
		if ( p == m_pEnabledMod )
1835
			m_pEnabledMod = NULL;
1836
 
1837
		if ( uninstalledPackages )
1838
			uninstalledPackages->push_back(p);
1839
		else
1840
			delete p;
1841
	}
1842
 
1843
	m_lInstallList.clear();
1844
 
1845
	// check unistall files
1846
	if ( !uninstallFiles.empty() )
1847
	{
1848
		removeDirs.PushBack(CyString("PluginManager/Uninstall"));
1849
 
1850
		// make sure the scripts directory is created, even thou it should always be there anyways
1851
		CDirIO scriptDir(m_sCurrentDir);
1852
		if ( !scriptDir.Exists("scripts") )
1853
		{
1854
			if ( scriptDir.Create("Scripts") )
1855
				this->AddLogEntry(SPKINSTALL_CREATEDIRECTORY, "Scripts", errors);
1856
			else
1857
				this->AddLogEntry(SPKINSTALL_CREATEDIRECTORY_FAIL, "Scripts", errors);
1858
		}
1859
 
1860
		for ( C_File *uf = uninstallFiles.First(); uf; uf = uninstallFiles.Next() )
1861
		{
1862
			C_File *newFile = new C_File();
1863
			newFile->SetFileType(FILETYPE_SCRIPT);
1864
			newFile->SetFilename(uf->GetFilename());
1865
			newFile->SetCreationTime(uf->GetCreationTime());
1866
 
1867
			// other installed packages use this file as well, copy it
1868
			CyString newFilename = m_sCurrentDir + "/" + newFile->GetNameDirectory(NULL);
1869
			CFileIO file(uf->GetFilePointer());
1870
 
1871
			if ( uf->GetUsed() )
1872
			{
52 cycrow 1873
				if ( file.copy(newFilename.ToString()) )
1 cycrow 1874
					this->AddLogEntry(SPKINSTALL_UNINSTALL_COPY, newFile->GetNameDirectory(NULL), errors);
1875
				else
1876
				{
1877
					this->AddLogEntry(SPKINSTALL_UNINSTALL_COPY_FAIL, newFile->GetNameDirectory(NULL), errors);
1878
					delete newFile;
1879
					newFile = NULL;
1880
				}
1881
			}
1882
			// otherwise just move it
1883
			else
1884
			{
1885
				if ( file.Rename(newFilename) )
1886
					this->AddLogEntry(SPKINSTALL_UNINSTALL_MOVE, newFile->GetNameDirectory(NULL), errors);
1887
				else
1888
				{
1889
					this->AddLogEntry(SPKINSTALL_UNINSTALL_MOVE_FAIL, newFile->GetNameDirectory(NULL), errors);
1890
					delete newFile;
1891
					newFile = NULL;
1892
				}
1893
 
1894
				m_lFiles.remove(uf, false);
1895
				delete uf;
1896
			}
1897
 
1898
			// add to the list
1899
			if ( newFile )
1900
			{
1901
				// first check if theres a matching one
1902
				bool found = false;
1903
				for ( CListNode<C_File> *node = m_lUninstallFiles.Front(); node; node = node->next() )
1904
				{
1905
					C_File *checkFile = node->Data();
1906
					if ( checkFile->GetFilename().Compare(newFile->GetFilename()) )
1907
					{
1908
						found = true;
1909
						break;
1910
					}
1911
				}
1912
 
1913
				// not found, so add it
1914
				if ( !found )
1915
					m_lUninstallFiles.push_back(newFile);
1916
				else
1917
					delete newFile;
1918
			}
1919
		}
1920
	}
1921
	uninstallFiles.clear();
1922
 
1923
	// remove all directies that we're not using
1924
	if ( readme )
1925
	{
1926
		removeDirs.PushBack(CyString("PluginManager/Readme"));
1927
		removeDirs.PushBack(CyString("Readme"));
1928
	}
105 cycrow 1929
	if ( original ) {
1930
		removeDirs.PushBack(CyString("PluginManager/Original/Replacements"));
1 cycrow 1931
		removeDirs.PushBack(CyString("PluginManager/Original"));
105 cycrow 1932
	}
1 cycrow 1933
	removeDirs.PushBack(CyString("PluginManager/Disabled"));
1934
	RemoveUnusedDirectories(removeDirs, errors);
1935
 
1936
	// finally lets shuffle any fake patchs to fill in gaps
1937
	if ( shuffle )
1938
	{
1939
		ShuffleFakePatches(errors);
1940
		ShuffleTextFiles(errors);
1941
	}
1942
 
1943
	this->WriteData();
1944
 
1945
	return true;
1946
}
1947
 
1948
/**
1949
 * Prepares a package to be uninstalled
1950
 *
1951
 * Adds the package, and all its children onto the uninstall list to be used by UninstallPreparePackages
1952
 */
1953
void CPackages::PrepareUninstallPackage(CBaseFile *package)
1954
{
1955
	// add package to list
1956
	if ( !m_lInstallList.FindData(package) )
1957
		m_lInstallList.push_back(package);
1958
 
1959
	// add all children
1960
	CLinkList<CBaseFile> children;
1961
	if ( this->GetChildPackages(package, &children, true) )
1962
	{
1963
		for ( CBaseFile *p = children.First(); p; p = children.Next() )
1964
		{
1965
			if ( !m_lInstallList.FindData(p) )
1966
				m_lInstallList.push_back(p);
1967
		}
1968
	}
1969
}
1970
 
1971
bool CPackages::PrepareEnablePackage(CBaseFile *package)
1972
{
1973
	ClearError();
1974
 
1975
	if ( package->GetParent() && !package->GetParent()->IsEnabled() )
1976
	{
1977
		m_iError = PKERR_NOPARENT;
1978
		return false;
1979
	}
1980
 
1981
	if ( m_bVanilla && !package->IsSigned() )
1982
	{
1983
		m_iError = PKERR_MODIFIED;
1984
		return false;
1985
	}
1986
 
1987
	// check if it needs depancies
1988
	if ( package->AnyDependacies() )
1989
	{
1990
		if ( this->GetMissingDependacies(package, NULL, true) )
1991
		{
1992
			m_iError = PKERR_MISSINGDEP;
1993
			return false;
1994
		}
1995
	}
1996
 
1997
	if ( !m_lEnableList.FindData(package) )
1998
	{
1999
		if ( !package->IsEnabled() )
2000
			m_lEnableList.push_back(package);
2001
 
2002
		// do all the children as well
2003
		if ( m_bAutoEnableChild )
2004
		{
2005
			CLinkList<CBaseFile> childList;
2006
			this->GetChildPackages(package, &childList, true);
2007
 
2008
			// add all disabled packages to list
2009
			for ( CBaseFile *p = childList.First(); p; p = childList.Next() )
2010
			{
2011
				if ( !p->IsEnabled() )
2012
					m_lEnableList.push_back(p);
2013
			}
2014
		}
2015
	}
2016
 
2017
	m_bRemoveDir = true;
2018
 
2019
	return true;
2020
}
2021
 
2022
bool CPackages::PrepareDisableForVanilla()
2023
{
2024
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
2025
	{
2026
		CBaseFile *p = node->Data();
2027
		if ( !p->IsSigned() && p->IsEnabled() )
2028
		{
2029
			this->PrepareDisablePackage(p);
2030
			m_bDisableVanilla = true;
2031
		}
2032
	}
2033
 
2034
	return true;
2035
}
2036
 
2037
bool CPackages::PrepareEnableLibrarys()
2038
{
2039
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
2040
	{
2041
		CBaseFile *p = node->Data();
2042
		if ( p->GetType() != TYPE_SPK )
2043
			continue;
2044
 
2045
		if ( !p->IsEnabled() && ((CSpkFile *)p)->IsLibrary() )
2046
			this->PrepareEnablePackage(p);
2047
	}
2048
 
2049
	return true;
2050
}
2051
 
2052
bool CPackages::PrepareEnableFromVanilla()
2053
{
2054
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
2055
	{
2056
		CBaseFile *p = node->Data();
2057
		if ( !p->IsEnabled() && p->IsModifiedEnabled() ) {
2058
			this->PrepareEnablePackage(p);
2059
		}
2060
	}
2061
 
2062
	return true;
2063
}
2064
 
2065
int CPackages::GetDependacyList(CBaseFile *package, CLinkList<CBaseFile> *list)
2066
{
2067
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
2068
	{
2069
		CBaseFile *p = node->Data();
50 cycrow 2070
		if ( p->IsPackageNeeded(package->name(), package->author()) )
1 cycrow 2071
			list->push_back(p);
2072
	}
2073
 
2074
	return list->size();
2075
}
2076
 
2077
bool CPackages::PrepareDisablePackage(CBaseFile *package)
2078
{
2079
	if ( !m_lDisableList.FindData(package) )
2080
	{
2081
		if ( package->IsEnabled() )
2082
			m_lDisableList.push_back(package);
2083
 
2084
		CLinkList<CBaseFile> childList;
2085
		this->GetChildPackages(package, &childList, true);
2086
 
2087
		// add all disabled packages to list
2088
		for ( CBaseFile *p = childList.First(); p; p = childList.Next() )
2089
		{
2090
			if ( p->IsEnabled() && !m_lDisableList.FindData(p) )
2091
				m_lDisableList.push_back(p);
2092
		}
2093
 
2094
		// if its a library, check for any dependacies
2095
		if ( package->GetType() == TYPE_SPK && ((CSpkFile *)package)->IsLibrary() )
2096
		{
2097
			CLinkList<CBaseFile> depList;
2098
			if ( this->GetDependacyList(package, &depList) )
2099
			{
2100
				for ( CBaseFile *p = depList.First(); p; p = depList.Next() )
2101
				{
2102
					if ( !m_lDisableList.FindData(p) )
2103
						this->PrepareDisablePackage(p);
2104
				}
2105
			}
2106
		}
2107
	}
2108
	return true;
2109
}
2110
 
2111
/**
2112
 * Prepares a package to be installed
2113
 */
2114
int CPackages::PrepareInstallPackage(CBaseFile *package, bool disabled, bool force, int check)
2115
{
2116
	// add package to list
2117
	if ( !m_lInstallList.FindData(package) )
2118
	{
2119
		int error = this->CheckInstallPackage(package, check);
2120
		if ( error == INSTALLCHECK_OK || force )
2121
		{
2122
			if ( disabled )
2123
				package->SetEnabled(false);
2124
 
2125
			bool added = false;
2126
			if ( package->GetType() == TYPE_SPK )
2127
			{
2128
				// find other mods in the currently added list
2129
				CSpkFile *spk = (CSpkFile *)package;
2130
				if ( spk->IsAnotherMod() )
2131
				{
2132
					for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
2133
					{
2134
						CBaseFile *p = node->Data();
50 cycrow 2135
						if ( spk->GetOtherName().Compare(p->name()) && spk->GetOtherAuthor().Compare(p->author()) )
1 cycrow 2136
						{
2137
							m_lInstallList.insert(m_lInstallList.FindPos(p) + 2, package);
2138
							added = true;
2139
							break;
2140
						}
2141
					}
2142
				}
2143
			}
2144
 
2145
			if ( !added )
2146
			{
2147
				// check if we are a parent
2148
				for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
2149
				{
2150
					if ( node->Data()->GetType() != TYPE_SPK )
2151
						continue;
2152
 
2153
					CSpkFile *spk = (CSpkFile *)node->Data();
2154
					if ( !spk->IsAnotherMod() )
2155
						continue;
2156
 
50 cycrow 2157
					if ( spk->GetOtherName().Compare(package->name()) && spk->GetOtherAuthor().Compare(package->author()) )
1 cycrow 2158
					{
2159
						added = true;
2160
						m_lInstallList.insert(node->Data(), package);
2161
						break;
2162
					}
2163
				}
2164
 
2165
				if ( !added )
2166
					m_lInstallList.push_back(package);
2167
			}
2168
 
2169
			return INSTALLCHECK_OK;
2170
		}
2171
 
2172
		package->SetLoadError(error);
2173
		return error;
2174
	}
2175
 
2176
	return INSTALLCHECK_ALREADYQUEUED;
2177
}
2178
 
2179
void CPackages::RemovePreparedInstall(CBaseFile *package)
2180
{
2181
	if ( !package )
2182
	{
2183
		m_lInstallList.MemoryClear();
2184
	}
2185
	else
2186
	{
2187
		if ( m_lInstallList.FindData(package) )
2188
		{
2189
			m_lInstallList.remove(package, true);
2190
		}
2191
	}
2192
}
2193
 
2194
char CPackages::ConvertWareTypeBack(int w)
2195
{
2196
	switch ( w )
2197
	{
2198
		case WARES_BIO:
2199
			return 'b';
2200
		case WARES_ENERGY:
2201
			return 'e';
2202
		case WARES_FOOD:
2203
			return 'f';
2204
		case WARES_MINERAL:
2205
			return 'm';
2206
		case WARES_TECH:
2207
			return 't';
2208
		case WARES_NATURAL:
2209
			return 'n';
2210
	}
2211
	return 't';
2212
}
2213
int CPackages::ConvertWareType(char w)
2214
{
2215
	switch ( LOWER(w) )
2216
	{
2217
		case 'b':
2218
			return WARES_BIO;
2219
		case 'e':
2220
			return WARES_ENERGY;
2221
		case 'f':
2222
			return WARES_FOOD;
2223
		case 'm':
2224
			return WARES_MINERAL;
2225
		case 't':
2226
			return WARES_TECH;
2227
		case 'n':
2228
			return WARES_NATURAL;
2229
	}
2230
	return WARES_TECH;
2231
}
2232
 
2233
void CPackages::SetupShips()
2234
{
2235
	for ( CListNode<SGameShip> *wNode = m_lGameShips.Front(); wNode; wNode = wNode->next() )
2236
	{
2237
		if ( wNode->Data()->iType != WARETYPE_NONE )
2238
			wNode->Data()->iType = WARETYPE_DELETED;
2239
	}
2240
 
2241
	// find any new ships to add to the list
2242
	for ( CListNode<CBaseFile> *pNode = m_lPackages.Front(); pNode; pNode = pNode->next() )
2243
	{
2244
		if ( pNode->Data()->GetType() != TYPE_XSP )
2245
			continue;
2246
		CXspFile *p = (CXspFile *)pNode->Data();
2247
 
2248
		bool found = false;
2249
		for ( CListNode<SGameShip> *wNode = m_lGameShips.Front(); wNode; wNode = wNode->next() )
2250
		{
14 cycrow 2251
			if ( wNode->Data()->sShipID.Compare(p->GetShipID().c_str()) )
1 cycrow 2252
			{
2253
				if ( !p->IsEnabled() )
2254
					wNode->Data()->iType = WARETYPE_DISABLED;
2255
				else
2256
					wNode->Data()->iType = WARETYPE_ADDED;
2257
				found = true;
2258
				wNode->Data()->pPackage = p;
2259
				wNode->Data()->sShipClass = p->GetShipClass();
2260
				break;
2261
			}
2262
		}
2263
 
2264
		if ( found || !p->IsEnabled() )
2265
			continue;
2266
 
2267
		// first find any free
2268
		SGameShip *gw = NULL;
2269
		for ( CListNode<SGameShip> *wNode = m_lGameShips.Front(); wNode; wNode = wNode->next() )
2270
		{
2271
			if ( (!gw) && (wNode->Data()->iType == WARETYPE_NONE) )
2272
				gw = wNode->Data();
2273
			// find an old entry for the ware and add it to the same place
14 cycrow 2274
			if ( wNode->Data()->sShipID.Compare(p->GetShipID().c_str()) )
1 cycrow 2275
			{
2276
				gw = wNode->Data();
2277
				break;
2278
			}
2279
		}
2280
 
2281
		// none found, create one
2282
		if ( !gw )
2283
		{
2284
			gw = new SGameShip;
2285
			gw->sShipID = p->GetShipID();
2286
			gw->sShipClass = p->GetShipClass();
2287
			gw->pPackage = p;
2288
			m_lGameShips.push_back(gw);
2289
		}
2290
		gw->iType = WARETYPE_ADDED;
2291
	}
2292
}
2293
 
2294
void CPackages::SetupWares()
2295
{
2296
	for ( int i = 0; i < WAREBUFFERS; i++ )
2297
	{
2298
		for ( CListNode<SGameWare> *wNode = m_lGameWares[i].Front(); wNode; wNode = wNode->next() )
2299
		{
2300
			if ( wNode->Data()->iType != WARETYPE_NONE )
2301
				wNode->Data()->iType = WARETYPE_DELETED;
2302
		}
2303
	}
2304
 
2305
	// find any new wares to add to the list
2306
	for ( CListNode<CBaseFile> *pNode = m_lPackages.Front(); pNode; pNode = pNode->next() )
2307
	{
2308
		if ( pNode->Data()->GetType() != TYPE_SPK )
2309
			continue;
2310
		CSpkFile *p = (CSpkFile *)pNode->Data();
2311
 
2312
		for ( CListNode<SWares> *node = p->GetWaresList()->Front(); node; node = node->next() )
2313
		{
2314
			SWares *w = node->Data();
2315
			int wareType = CPackages::ConvertWareType(w->cType);
2316
 
2317
			// check if its on the list
2318
			bool found = false;
2319
			for ( CListNode<SGameWare> *wNode = m_lGameWares[wareType].Front(); wNode; wNode = wNode->next() )
2320
			{
2321
				if ( wNode->Data()->sWareName == w->sID )
2322
				{
2323
					if ( !p->IsEnabled() )
2324
						wNode->Data()->iType = WARETYPE_DISABLED;
2325
					else
2326
						wNode->Data()->iType = WARETYPE_ADDED;
2327
					wNode->Data()->pWare = w;
2328
					found = true;
2329
					break;
2330
				}
2331
			}
2332
 
2333
			if ( found || !p->IsEnabled() )
2334
				continue;
2335
 
2336
			// first find any free
2337
			SGameWare *gw = NULL;
2338
			for ( CListNode<SGameWare> *wNode = m_lGameWares[wareType].Front(); wNode; wNode = wNode->next() )
2339
			{
2340
				if ( (!gw) && (wNode->Data()->iType == WARETYPE_NONE) )
2341
					gw = wNode->Data();
2342
				// find an old entry for the ware and add it to the same place
2343
				if ( wNode->Data()->sWareName == w->sID )
2344
				{
2345
					gw = wNode->Data();
2346
					break;
2347
				}
2348
			}
2349
 
2350
			// none found, create one
2351
			if ( !gw )
2352
			{
2353
				gw = new SGameWare;
2354
				gw->sWareName = w->sID;
2355
				gw->iPos = m_lGameWares[wareType].size();
2356
				gw->pWare = w;
2357
				gw->cType = w->cType;
2358
				m_lGameWares[wareType].push_back(gw);
2359
			}
2360
			gw->iType = WARETYPE_ADDED;
2361
		}
2362
	}
2363
}
2364
 
2365
/**
2366
 * Closing the current directory
2367
 *
2368
 * When existing, program needs to close the directory
2369
 */
2370
bool CPackages::CloseDir ( CyStringList *errors, CProgressInfo *progress, bool removedir )
2371
{
2372
	if ( m_sCurrentDir.Empty() )
2373
		return true;
2374
	if ( !m_bLoaded )
2375
		return true;
2376
 
84 cycrow 2377
	CLog::log(CLog::Log_Directory, 1, "closing directory: " + m_sCurrentDir.ToString());
1 cycrow 2378
	m_sActiveDir = m_sCurrentDir;
2379
 
84 cycrow 2380
	if ( m_bRenameText ) {
2381
		CLog::log(CLog::Log_Directory, 2, "Creating other language files for game");
1 cycrow 2382
		CreateLanguageTextFiles(errors);
84 cycrow 2383
	}
1 cycrow 2384
 
84 cycrow 2385
	CLog::log(CLog::Log_Directory, 2, "Backing up save game files");
1 cycrow 2386
	this->BackupSaves();
2387
 
84 cycrow 2388
	if ( CFileIO(m_sCurrentDir + "/mods/PluginManager.dat").ExistsOld() ) {
2389
		CLog::log(CLog::Log_IO, 3, "Removing old PluginManager.dat file");
52 cycrow 2390
		CFileIO::Remove(m_sCurrentDir.ToString() + "/mods/PluginManager.dat");
84 cycrow 2391
	}
2392
	if ( CFileIO(m_sCurrentDir + "/mods/PluginManager.cat").ExistsOld() ) {
2393
		CLog::log(CLog::Log_IO, 3, "Removing old PluginManager.cat file");
52 cycrow 2394
		CFileIO::Remove(m_sCurrentDir.ToString() + "/mods/PluginManager.cat");
84 cycrow 2395
	}
1 cycrow 2396
 
2397
	if ( !m_bVanilla )
2398
	{
2399
		// base mode for Reunion
2400
		if ( m_iGame == GAME_X3 && m_pEnabledMod )
2401
		{
2402
			C_File *fDat = m_pEnabledMod->GetFirstFile(FILETYPE_MOD);
2403
			while ( fDat && !fDat->IsFakePatch() && !fDat->CheckFileExt("dat") )
2404
				fDat = m_pEnabledMod->GetNextFile(fDat);
2405
 
2406
			if ( fDat )
2407
			{
2408
				C_File *fCat = m_pEnabledMod->GetFirstFile(FILETYPE_MOD);
2409
				while ( fCat && !fCat->IsFakePatch() && !fCat->CheckFileExt("cat") && !fCat->GetBaseName().Compare(fDat->GetBaseName()) )
2410
					fCat = m_pEnabledMod->GetNextFile(fCat);
2411
 
2412
				if ( fCat )
2413
				{
52 cycrow 2414
					CFileIO(fDat->GetFilePointer()).copy(m_sCurrentDir.ToString() + "/mods/PluginManager.dat");
2415
					CFileIO(fCat->GetFilePointer()).copy(m_sCurrentDir.ToString() + "/mods/PluginManager.cat");
1 cycrow 2416
				}
2417
			}
2418
		}
52 cycrow 2419
		else if ( m_iGame == GAME_X3 && !m_sSetMod.Empty() && CFileIO(m_sCurrentDir + "/mods/" + m_sSetMod + ".cat").ExistsOld() && CFileIO(m_sCurrentDir + "/mods/" + m_sSetMod + ".dat").ExistsOld() )
1 cycrow 2420
		{
84 cycrow 2421
			CLog::log(CLog::Log_Directory, 2, "Copying mod file: " + m_sSetMod.ToString() + ", to PluginManager.cat");
52 cycrow 2422
			CFileIO(m_sCurrentDir + "/mods/" + m_sSetMod + ".dat").copy(m_sCurrentDir.ToString() + "/mods/PluginManager.dat");
2423
			CFileIO(m_sCurrentDir + "/mods/" + m_sSetMod + ".cat").copy(m_sCurrentDir.ToString() + "/mods/PluginManager.cat");
1 cycrow 2424
		}
2425
 
2426
		if ( !CDirIO(m_sCurrentDir).Exists("mods") )
2427
			CDirIO(m_sCurrentDir).Create("mods");
2428
 
2429
		SetupWares();
2430
		SetupShips();
2431
		CreateEMPFile();
2432
		CreateWareFiles();
2433
		CreateDummies();
2434
		CreateComponants();
2435
		CreateTShips();
2436
		CreateCutData();
2437
		CreateBodies();
2438
		CreateAnimations();
2439
		CreateCustomStarts();
2440
		CreateGlobals();
2441
		CreatePluginManagerText();
2442
		RestoreFakePatch();
2443
	}
2444
 
2445
	RemoveFailedFiles();
2446
 
2447
	WriteData();
2448
	if ( removedir && m_bRemoveDir )
2449
	{
2450
		m_bRemoveDir = false;
2451
		CyStringList removeDirs;
2452
		removeDirs.PushBack(".");
2453
		RemoveUnusedDirectories(removeDirs, errors);
2454
	}
2455
 
2456
	m_bLoaded = false;
2457
	return true;
2458
}
2459
 
2460
CyString CPackages::GetModKey()
2461
{
2462
	return m_gameExe.GetModKey(m_iGame - 1);
2463
}
2464
CyString CPackages::GetSelectedModName()
2465
{
2466
	if ( !m_pEnabledMod )
2467
	{
2468
		if ( m_sSetMod.Empty() && m_iGame == GAME_X3 )
2469
			return "PluginManager";
2470
		return m_sSetMod;
2471
	}
2472
 
2473
	if ( !m_pEnabledMod->IsEnabled() )
2474
		return m_sSetMod;
2475
 
2476
	C_File *f = m_pEnabledMod->GetFirstFile(FILETYPE_MOD);
2477
	if ( !f )
2478
		return m_sSetMod;
2479
 
2480
	CyString name = f->GetFilename();
2481
	name = name.Left(-4);
2482
	return name;
2483
 
2484
}
2485
 
2486
bool CPackages::RestoreFakePatch()
2487
{
84 cycrow 2488
	CLog::log(CLog::Log_Directory, 1, "Restoring PluginManager fake patch into game");
2489
 	m_iFakePatch = -1;
1 cycrow 2490
 
2491
	CFileIO catFile(m_sCurrentDir + "/PluginManager/PlugMan_Fake.cat");
2492
	CFileIO datFile(m_sCurrentDir + "/PluginManager/PlugMan_Fake.dat");
2493
 
2494
	// if only 1 exists, remove it
52 cycrow 2495
	if ( catFile.exists() && !datFile.exists() ) {
84 cycrow 2496
		CLog::log(CLog::Log_Directory, 1, "WARNING: cat/dat file mismatch, dat file seems to be missing, removing cat file");
52 cycrow 2497
		if ( !catFile.remove() ) return false;
1 cycrow 2498
	}
52 cycrow 2499
	else if ( !catFile.exists() && datFile.exists() ) {
84 cycrow 2500
		CLog::log(CLog::Log_Directory, 1, "WARNING: cat/dat file mismatch, cat file seems to be missing, removing dat file");
52 cycrow 2501
		if ( !datFile.remove() ) return false;
1 cycrow 2502
	}
2503
 
2504
	// if both exists, lets rename them
52 cycrow 2505
	if ( catFile.exists() && datFile.exists() )
1 cycrow 2506
	{
84 cycrow 2507
		CLog::log(CLog::Log_Directory, 3, "Creating pluginmanagerfake.txt file to add to Fake Patch");
1 cycrow 2508
		// we need to add the plugin manager file in
2509
		CyString file = m_sTempDir;
2510
		if ( !file.Empty() )
2511
			file += "/";
2512
		file += "pluginmanagerfake.txt";
2513
		file = file.FindReplace("\\", "/");
2514
		CFileIO fakeFile(file);
2515
		std::vector<CyString> lines;
2516
		lines.push_back("//pluginmanager fake patch");
84 cycrow 2517
		CLog::log(CLog::Log_Directory, 3, "Writing pluginmanagerfake.txt file to add to Fake Patch");
2518
		if ( !fakeFile.WriteFile(&lines) ) {
2519
			CLog::log(CLog::Log_Directory, 3, "Writing pluginmanagerfake.txt failed!!");
2520
		}
2521
		else {
85 cycrow 2522
/*
84 cycrow 2523
			CLog::log(CLog::Log_Directory, 2, "Adding TFake.pck file into FakePatch");
2524
			CCatFile fakePatch;
2525
			if ( fakePatch.Open(m_sCurrentDir + "/PluginManager/PlugMan_Fake.cat", this->GetAddonDir(), CATREAD_DAT, false) == CATERR_NONE )
1 cycrow 2526
			{
84 cycrow 2527
				if ( fakePatch.AppendFile(file.ToString(), "PlugMan\\TFake.pck") )
2528
					fakePatch.WriteCatFile();
85 cycrow 2529
			}	*/		
84 cycrow 2530
		}
1 cycrow 2531
 
85 cycrow 2532
		// backup existing mod files incase something happens to them
2533
		if ( !datFile.exists() || !catFile.exists() ) {
2534
			CLog::log(CLog::Log_Directory, 2, Utils::String("ERROR: ") + (!catFile.exists() ? "cat" : "dat") + " file appears to be missing");
2535
		}
2536
		else {
2537
			catFile.GetDirIO().Create("Backup");
2538
			catFile.copy(catFile.dir() + "/Backup/" + catFile.filename());
2539
			datFile.copy(datFile.dir() + "/Backup/" + datFile.filename());
2540
		}
2541
 
2542
 
84 cycrow 2543
		// find next available fake patch
2544
		m_iFakePatch = this->FindNextFakePatch();
2545
		CLog::log(CLog::Log_Directory, 2, "Finding next available fake patch number: " + (long)m_iFakePatch);
1 cycrow 2546
 
84 cycrow 2547
		Utils::String filename = Utils::String::PadNumber(m_iFakePatch, 2);
2548
		CLog::log(CLog::Log_Directory, 2, "Renaming cat file to: " + filename + ".cat");
2549
		if ( catFile.Rename(m_sCurrentDir + "/" + filename + ".cat") )
2550
		{
2551
			CLog::log(CLog::Log_Directory, 2, "Renaming dat file to: " + filename + ".dat");
2552
			if ( datFile.Rename(m_sCurrentDir + "/" + filename + ".dat") ){
2553
				CLog::log(CLog::Log_Directory, 3, "Deleting pluginmanagerfake.txt temporary file");
2554
				fakeFile.remove();
2555
				return true;
1 cycrow 2556
			}
84 cycrow 2557
			else {
2558
				CLog::log(CLog::Log_Directory, 2, "ERROR: failed to rename dat file");
2559
			}
2560
 
2561
			// TODO: restore cat file
1 cycrow 2562
		}
84 cycrow 2563
		else {
2564
			CLog::log(CLog::Log_Directory, 2, "ERROR: failed to rename cat file");
2565
		}
1 cycrow 2566
 
84 cycrow 2567
		CLog::log(CLog::Log_Directory, 3, "Deleting pluginmanagerfake.txt temporary file");
52 cycrow 2568
		fakeFile.remove();
1 cycrow 2569
		return false;
2570
	}
2571
 
2572
	return true;
2573
}
2574
 
2575
 
2576
/**
2577
 * Save package detail to date file
2578
 *
2579
 * Writes the current package list data into pluginmanager.dat file
2580
 */
2581
void CPackages::WriteData()
2582
{
2583
	if ( m_sCurrentDir.Empty() )
2584
		return;
2585
 
84 cycrow 2586
	CLog::log(CLog::Log_Directory, 1, "Writing data file for current directory: " + m_sCurrentDir.ToString());
2587
 
1 cycrow 2588
	CyStringList lines;
2589
	CyString version;
2590
	version.FromFloat(GetLibraryVersion(), 2);
2591
	version.Prepend("SpkInstaller: ");
2592
	lines.PushBack(version);
2593
 
2594
	lines.PushBack(CyString("UpdateTime: ") + (long)m_iLastUpdated);
2595
	if ( m_iFakePatch != -1 )
2596
		lines.PushBack(CyString("FakePatch: ") + (long)m_iFakePatch);
2597
	if ( m_iSaveGame != -1 )
2598
		lines.PushBack(CyString("SaveGame: ") + (long)m_iSaveGame);
2599
	lines.PushBack(CyString("SaveGameManager: ") + (long)m_iSaveGameManager);
2600
	if ( !m_bVanilla )
2601
		lines.PushBack("Modified");
2602
	if ( m_bUsedWare )
2603
		lines.PushBack("UsedWare");
2604
	if ( m_bSurpressProtectedWarning )
2605
		lines.PushBack("SurpressProtectedWarning");
2606
	if ( !m_sSetMod.Empty() )
2607
		lines.PushBack(CyString("SetMod: ") + m_sSetMod);
2608
	lines.PushBack(CyString("ShipBuffer: ") + (long)m_iShipBuffer);
2609
	CyString wareBuffer = "WareBuffers:";
2610
	for ( int i = 0; i < WAREBUFFERS; i++ )
2611
		wareBuffer += CyString(" ") + (long)m_iWareBuffer[i];
2612
	lines.PushBack(wareBuffer);
2613
	for ( int i = 0; i < WAREBUFFERS; i++ )
2614
	{
2615
		if ( !m_lGameWares[i].size() )
2616
			continue;
2617
		lines.PushBack(CyString("Wares: ") + (long)i + " " + (long)m_lGameWares[i].size());
2618
 
2619
		for ( CListNode<SGameWare> *node = m_lGameWares[i].Front(); node; node = node->next() )
2620
		{
2621
			SGameWare *gm = node->Data();
2622
			lines.PushBack(CyString((long)gm->iPos) + " " + (long)gm->iType + " " + CyString((char)gm->cType) + " " + gm->sWareName);
2623
		}
2624
	}
2625
 
2626
	for ( SStringList *str = m_lNonRemovedFiles.Head(); str; str = str->next )
2627
		lines.PushBack(CyString("NonRemovedFile: ") + str->str);
2628
 
2629
	if ( m_lGameShips.size() )
2630
	{
2631
		lines.PushBack(CyString("Ships: ") + (long)m_lGameShips.size());
2632
 
2633
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
2634
		{
2635
			SGameShip *gm = node->Data();
2636
			lines.PushBack(CyString((long)gm->iType) + " $#C:" + gm->sShipClass + " " + gm->sShipID);
2637
		}
2638
	}
2639
 
2640
	// write created Files
2641
	if ( !m_lCreatedFiles.Empty() )
2642
	{
2643
		for ( SStringList *node = m_lCreatedFiles.Head(); node; node = node->next )
2644
			lines.PushBack(CyString("CreatedFile: ") + node->str.Remove(m_sCurrentDir));
2645
	}
2646
 
2647
	// write uninstall files
2648
	if ( !m_lUninstallFiles.empty() )
2649
	{
2650
		for ( CListNode<C_File> *node = m_lUninstallFiles.Front(); node; node = node->next() )
2651
		{
2652
			C_File *uf = node->Data();
2653
			CyString uString = "Uninstall: ";
2654
			uString += CyString::Number((long)uf->GetCreationTime()) + " ";
2655
			uString += uf->GetFilename();
2656
			lines.PushBack(uString);
2657
		}
2658
	}
2659
 
2660
	// write the original file data
93 cycrow 2661
	_pOriginalFiles->writeData(&lines);
1 cycrow 2662
 
2663
	// write the global changes
2664
	if ( !m_lGlobals.Empty() )
2665
	{
2666
		for ( SStringList *str = m_lGlobals.Head(); str; str = str->next )
2667
			lines.PushBack(CyString("GlobalSetting: ") + str->str + ":" + str->data.Remove(";"));
2668
	}
2669
 
2670
	// write the fake patch ordering
2671
	if ( !m_lFakePatchOrder.Empty() )
2672
	{
2673
		for ( SStringList *str = m_lFakePatchOrder.Head(); str; str = str->next )
2674
			lines.PushBack(CyString("FakePatchOrder: ") + str->str + ":" + str->data);
2675
	}
2676
 
88 cycrow 2677
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
2678
		SWarePriceOverride *ware = node->Data();
2679
		switch(ware->type) {
2680
			case Ware_EMP:
2681
				lines.PushBack(CyString(Utils::String("EMPPriceOverride:") + (long)ware->pos + " " + (long)ware->relval));
2682
				if ( ware->bNotority )
2683
					lines.PushBack(CyString(Utils::String("EMPNotoOverride:") + (long)ware->pos + " " + (long)ware->notority));
2684
				break;
2685
			case Ware_Custom:
2686
				lines.PushBack(CyString(Utils::String("CustomWarePriceOverride:") + ware->id + ";" + (long)ware->relval));
2687
				if ( ware->bNotority )
2688
					lines.PushBack(CyString(Utils::String("CustomWareNotoOverride:") + ware->id + ";" + (long)ware->notority));
2689
				break;
2690
			case Ware_BuiltIn:
2691
				lines.PushBack(CyString(Utils::String("BuiltInWarePriceOverride:") + (long)ware->pos + " " + (long)ware->relval));
2692
				if ( ware->bNotority )
2693
					lines.PushBack(CyString(Utils::String("BuiltInWareNotoOverride:") + (long)ware->pos + " " + (long)ware->notority));
2694
				break;
2695
		}
2696
	}
2697
 
1 cycrow 2698
	// write the global file list
2699
	lines.PushBack("GlobalFiles:");
2700
	int num = 0;
2701
	for ( CListNode<C_File> *fn = m_lFiles.Front(); fn; fn = fn->next() )
2702
	{
2703
		C_File *f = fn->Data();
2704
		f->SetPos(num++);
2705
 
2706
		CyString line = CyString::Number(f->GetFileType()) + ":" + CyString::Number((long)f->GetCreationTime()) + ":" + f->GetDir() + ":";
2707
		if ( f->IsShared() && !f->IsFakePatch() )
2708
			line += "1:";
2709
		else
2710
			line += "0:";
2711
 
2712
		CyString filename = f->GetFilePointer();
2713
		filename.Remove(m_sCurrentDir);
2714
 
2715
		if ( f->IsDisabled() )
2716
			line += "D#";
2717
 
2718
		line += "G#";
2719
		line += (long)f->GetGame();
2720
		line += "#";
2721
 
2722
		line += filename;
2723
 
2724
		if ( !f->GetOriginalName().Empty() )
2725
		{
2726
			line += "O#";
2727
			line += f->GetOriginalName();
2728
		}
2729
 
2730
		lines.PushBack(line);
2731
	}
2732
 
2733
	// write the package list
2734
	for ( CListNode<CBaseFile> *pn = m_lPackages.Front(); pn; pn = pn->next() )
2735
	{
2736
		CBaseFile *package = pn->Data();
2737
 
2738
		if ( package->GetType() == TYPE_SPK )
2739
			lines.PushBack("<script>");
2740
		else if ( package->GetType() == TYPE_XSP )
2741
			lines.PushBack("<ship>");
2742
		else if ( package->GetType() == TYPE_ARCHIVE )
2743
			lines.PushBack("<archive>");
2744
		else if ( package->GetType() == TYPE_BASE )
2745
			lines.PushBack("<base>");
2746
		else
2747
			continue;
2748
 
50 cycrow 2749
		if ( !package->filename().empty() )
2750
			lines.PushBack(CyString("Installspk: ") + package->filename());
1 cycrow 2751
 
2752
		CyString valuesline = package->CreateValuesLine();
2753
		if ( valuesline.Right(1) == '\n' )
2754
			valuesline.Truncate((int)valuesline.Length() - 1);
2755
		lines.PushBack(valuesline);
2756
 
2757
		if ( !package->IsEnabled() )
2758
			lines.PushBack("Disabled");
2759
		if ( !package->IsModifiedEnabled() )
2760
			lines.PushBack("ModifiedDisabled");
2761
 
2762
		if ( package->GetIcon() )
2763
			lines.PushBack(CyString("Icon: ") + package->GetIconExt() + " " + package->GetIcon()->GetFilePointer() );
2764
 
2765
		CyString fileline("Files:");
2766
		for ( CListNode<C_File> *fn = package->GetFileList()->Front(); fn; fn = fn->next() )
2767
		{
2768
			C_File *f = fn->Data();
2769
			fileline += " ";
2770
			fileline += CyString::Number(f->GetPos());
2771
		}
2772
		lines.PushBack(fileline);
2773
	}
2774
 
2775
	lines.PushBack("</scripts>");
2776
 
84 cycrow 2777
	CFileIO datFile(m_sCurrentDir + "/PluginManager/PluginManager.new");
1 cycrow 2778
 
2779
	CDirIO Dir(m_sCurrentDir);
84 cycrow 2780
	if ( !Dir.Exists("PluginManager") ) {
2781
		CLog::log(CLog::Log_IO, 2, "Creating PluginManager directory");
2782
 		Dir.Create("PluginManager");
2783
	}
1 cycrow 2784
 
84 cycrow 2785
	CLog::log(CLog::Log_IO, 2, "Writing data file: " + m_sCurrentDir.ToString() + "/PluginManager/PluginManager.new");
1 cycrow 2786
	if ( !datFile.WriteFile(&lines) )
2787
	{
84 cycrow 2788
		CLog::log(CLog::Log_IO, 1, "ERROR: Failed to write data file");
1 cycrow 2789
	}
84 cycrow 2790
	else {
2791
		CLog::log(CLog::Log_IO, 2, "Removing old data file: " + m_sCurrentDir.ToString() + "/PluginManager/PluginManager.dat");
2792
		if ( !CFileIO::Exists(m_sCurrentDir.ToString() + "/PluginManager/PluginManager.dat") || CFileIO::Remove(m_sCurrentDir.ToString() + "/PluginManager/PluginManager.dat") ) {
2793
			CLog::log(CLog::Log_IO, 2, "Renaming data file: PluginManager.new => PluginManager.dat");
2794
			datFile.Rename(m_sCurrentDir + "/PluginManager/PluginManager.dat");
2795
		}
2796
	}
1 cycrow 2797
}
2798
 
2799
 
2800
/**
2801
 * Get All Files
2802
 *
2803
 * Gets a list of all files, includes any child package files
2804
 */
2805
int CPackages::GetAllPackageFiles(CBaseFile *package, CLinkList<C_File> *fileList, bool includeChild)
2806
{
2807
	for ( CListNode<C_File> *node = package->GetFileList()->Front(); node; node = node->next() )
2808
	{
2809
		C_File *f = node->Data();
2810
		if ( !fileList->FindData(f) )
2811
			fileList->push_back(f);
2812
	}
2813
 
2814
	if ( includeChild )
2815
	{
2816
		CLinkList<CBaseFile> childList;
2817
		if ( this->GetChildPackages(package, &childList) )
2818
		{
2819
			for ( CBaseFile *child = childList.First(); child; child = childList.Next() )
2820
				this->GetAllPackageFiles(child, fileList, includeChild);
2821
		}
2822
	}
2823
 
2824
	// disablign for vanilla, make sure we add all files
2825
	if ( m_bDisableVanilla )
2826
	{
2827
		for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
2828
		{
2829
			C_File *f = node->Data();
2830
			if ( !fileList->FindData(f) )
2831
				fileList->push_back(f);
2832
		}
2833
	}
2834
 
2835
	return fileList->size();
2836
}
2837
 
2838
int CPackages::GetAllPackageFiles(CLinkList<CBaseFile> *list, CLinkList<C_File> *fileList, bool includeChild)
2839
{
2840
	for ( CListNode<CBaseFile> *node = list->Front(); node; node = node->next() )
2841
		this->GetAllPackageFiles(node->Data(), fileList, includeChild);
2842
	return fileList->size();
2843
}
2844
 
2845
/**
2846
 * Add Log
2847
 *
2848
 * Adds a log entry to displayed at end
2849
 */
2850
void CPackages::AddLogEntry(int type, CyString args, CyStringList *errors)
2851
{
2852
	if ( !errors )
2853
		return;
2854
 
2855
	errors->PushBack(args, ERRORLOG(type));
2856
}
2857
 
2858
/**
2859
 * Enable a package
2860
 *
2861
 * Enables all files in the package, unless they are already enabled, ie, used by other packages
2862
 * Backs up any original files before attempting to enable the file
2863
 *
2864
 * Fake patches are renamed to the next available slot
2865
 *
2866
 * Clears up the "PluginManager/Disabled" directory
2867
 *
2868
 * param: package		- The package class to be removed
2869
 * param: errors		- The string list for all the status for debugging, ie has an entry for whats happened to every file
2870
 * param: progress		- The progress class, updates a progress screen of the derived class
2871
 *
2872
 * return: boolen - Returns true if the package enabling was successful
2873
 */
2874
bool CPackages::EnablePackage ( CBaseFile *package, CyStringList *errors, CProgressInfo *progress )
2875
{
2876
	ClearError();
2877
 
2878
	// if already enabled, just skip
2879
	if ( package->IsEnabled() )
2880
		return true;
2881
 
2882
	// check if parent is enabled
2883
	if ( package->GetParent() && !package->GetParent()->IsEnabled() )
2884
	{
2885
		m_iError = PKERR_NOPARENT;
2886
		return false;
2887
	}
2888
 
2889
	// check for modified
2890
	if ( m_bVanilla && !package->IsSigned() )
2891
	{
2892
		m_iError = PKERR_MODIFIED;
2893
		return false;
2894
	}
2895
 
2896
	if ( this->PrepareEnablePackage(package) )
2897
		return this->EnablePreparedPackages(errors, progress);
2898
 
2899
	return false;
2900
}
2901
bool CPackages::EnablePreparedPackages ( CyStringList *errors, CProgressInfo *progress, CLinkList<CBaseFile> *enabledPackages )
2902
{
2903
	ClearError();
2904
 
2905
	// get all files, including children
2906
	CLinkList<C_File> fileList;
2907
	int maxFiles = this->GetAllPackageFiles(&m_lEnableList, &fileList, false);
2908
 
2909
	int fileCount = 0;
2910
	// we use this list to match cat and dat files
2911
	CyStringList fakePatches;
2912
	for ( CListNode<C_File> *node = fileList.Front(); node; node = node->next() )
2913
	{
2914
		C_File *f = node->Data();
2915
		if ( f->GetGame() && m_iGame ) {
2916
			if ( f->GetGame() != m_iGame )
2917
				continue;
2918
		}
2919
		CBaseFile *package = NULL;
2920
		for ( CListNode<CBaseFile> *node = m_lEnableList.Front(); node; node = node->next() )
2921
		{
2922
			CBaseFile *p = node->Data();
2923
			if ( p->IsFileAdded(f) )
2924
			{
2925
				package = p;
2926
				break;
2927
			}
2928
		}
2929
 
2930
		if ( progress )
2931
		{
2932
			progress->UpdateProgress(fileCount++, maxFiles);
2933
			progress->UpdateFile(f);
2934
		}
2935
 
2936
		// only move fiels that are disabled
2937
		if ( !f->IsDisabled() )
2938
			continue;
2939
 
2940
		// make the directory if it dont exist
2941
		CDirIO Dir(m_sCurrentDir);
2942
 
2943
		// fake patches are in the root, no need for directory
2944
		if ( !f->IsFakePatch() )
2945
		{
2946
			if ( !Dir.Exists(f->GetDirectory(package)) )
2947
			{
2948
				if ( !Dir.Create(f->GetDirectory(package)) )
2949
				{
2950
					this->AddLogEntry(SPKINSTALL_CREATEDIRECTORY_FAIL, f->GetDirectory(package), errors);
2951
					continue;
2952
				}
2953
				this->AddLogEntry(SPKINSTALL_CREATEDIRECTORY, f->GetDirectory(package), errors);
2954
			}
2955
		}
2956
 
2957
		// check if theres an original file to backup
93 cycrow 2958
		_pOriginalFiles->doBackup(f, errors);
1 cycrow 2959
 
2960
		CyString newFilename = f->GetNameDirectory(package);
2961
 
2962
		// fake patches need to be renamed
2963
		if ( f->IsFakePatch() )
2964
		{
2965
			// first check if the matching file has been done already
2966
			SStringList *foundStr = fakePatches.FindString(f->GetBaseName());
2967
 
2968
			// already done one, simply change this to match
2969
			if ( foundStr )
2970
				newFilename = foundStr->data + "." + f->GetFileExt();
2971
 
2972
			// we need to find the next available number instead
2973
			else
2974
			{
2975
				CyString newPos = CyString::Number(FindNextFakePatch()).PadNumber(2);
2976
				newFilename = newPos + "." + f->GetFileExt();
2977
				// and wee need to push this onto the string list so we can adjust the matchign pair
2978
				fakePatches.PushBack(f->GetBaseName(), newPos);
2979
			}
2980
		}
2981
 
2982
		// lets actually move the file back now
2983
		// !!error checking!!
2984
		CFileIO currentFile(f->GetFilePointer());
2985
		CFileIO newFile(m_sCurrentDir + "/" + newFilename);
52 cycrow 2986
		if ( !currentFile.exists() )
1 cycrow 2987
		{
2988
			// missing file ??
52 cycrow 2989
			if ( !newFile.exists() )
1 cycrow 2990
			{
2991
				this->AddLogEntry(SPKINSTALL_MISSINGFILE, newFilename, errors);
2992
				continue;
2993
			}
2994
		}
2995
		// remove existing file
2996
		// file exists, so lets try to move it
2997
		else
2998
		{
52 cycrow 2999
			if ( newFile.exists() )
3000
				newFile.remove();
1 cycrow 3001
 
102 cycrow 3002
			if ( !currentFile.Rename(newFile.fullFilename()) )
1 cycrow 3003
			{
3004
				this->AddLogEntry(SPKINSTALL_ENABLEFILE_FAIL, newFilename, errors);
3005
				continue;
3006
			}
3007
		}
3008
 
3009
		this->AddLogEntry(SPKINSTALL_ENABLEFILE, newFilename, errors);
3010
 
3011
		// adjust the internal name to match the new filename
3012
		f->SetFilename(m_sCurrentDir + "/" + newFilename);
3013
		// no longer disabled, we need to remove the flag
3014
		f->SetDisabled(false);
3015
	}
3016
 
3017
	// recursive, auto enable all children
3018
	CBaseFile *oldMod = m_pEnabledMod;
3019
	CBaseFile *pMod = NULL;
3020
 
3021
	for ( CListNode<CBaseFile> *node = m_lEnableList.Front(); node; node = node->next() )
3022
	{
3023
		CBaseFile *p = node->Data();
3024
		p->SetEnabled(true);
3025
		if ( p->IsMod() && !pMod )
3026
			pMod = p;
3027
 
3028
		if ( enabledPackages )
3029
			enabledPackages->push_back(p);
105 cycrow 3030
 
3031
		_pOriginalFiles->installed(p);
1 cycrow 3032
	}
3033
 
105 cycrow 3034
 
1 cycrow 3035
	if ( pMod )
3036
		m_pEnabledMod = pMod;
3037
 
3038
	// disabled the mod
3039
	if ( oldMod && oldMod != m_pEnabledMod && !m_bForceModInstall )
3040
		this->DisablePackage(oldMod, errors, progress);
3041
 
3042
	// lets remove all the directories we might have left empty
3043
	CyStringList removeDirs;
3044
	removeDirs.PushBack(CyString("PluginManager/Disabled"));
3045
	RemoveUnusedDirectories(removeDirs, errors);
3046
 
3047
	m_lEnableList.clear();
3048
 
3049
	this->WriteData();
3050
 
3051
	return true;
3052
}
3053
 
3054
 
3055
bool CPackages::DisablePreparedPackages ( CyStringList *errors, CProgressInfo *progress, CLinkList<CBaseFile> *disabledPackages )
3056
{
3057
	if ( progress )
3058
		progress->UpdateStatus(PROGRESS_DISABLEFILE);
3059
 
3060
	UpdateUsedFiles(&m_lDisableList, false);
3061
 
3062
	// checks if there are any original files to restore and if any fake patches were disabled to reshuffle
3063
	bool original = false, shuffle = false;
3064
 
3065
	// holds our list of directories that we might need to remove, only empty ones from this list will actually be removed
3066
	CyStringList removeDirs;
3067
 
3068
	// get all files, including children
3069
	CLinkList<C_File> fileList;
3070
	int maxFiles = this->GetAllPackageFiles(&m_lDisableList, &fileList, true);
3071
 
3072
	// interate through all the files in the package
3073
	int fileCount = 0;
3074
	for ( CListNode<C_File> *node = fileList.Front(); node; node = node->next() )
3075
	{
3076
		C_File *f = node->Data();
3077
		CBaseFile *checkPackage = NULL;
3078
		for ( CListNode<CBaseFile> *node = m_lDisableList.Front(); node; node = node->next() )
3079
		{
3080
			CBaseFile *p = node->Data();
3081
			if ( p->IsFileAdded(f) )
3082
			{
3083
				checkPackage = p;
3084
				break;
3085
			}
3086
		}
3087
 
3088
		// update the progress count for the current file
3089
		if ( progress )
3090
		{
3091
			progress->UpdateProgress(++fileCount, maxFiles);
3092
			progress->UpdateFile(f);
3093
		}
3094
 
3095
		// only delete files that are not used by any other enabled packages, counter from UpdateUsedFiles()
3096
		if ( f->GetUsed() || (f->IsShared() && !m_bDisableVanilla) )
3097
			continue;
3098
 
3099
		// file is already disabled, no need to disable again
3100
		if ( f->IsDisabled() )
3101
			continue;
3102
 
3103
		// readmes, uninstall and extra files dont need to be disabled
3104
		// Extra files not in the "Extras" directory could be anywhere, so these should be disabled incase they are game changing files, ie in "types"
3105
		if ( f->GetFileType() == FILETYPE_README || f->GetFileType() == FILETYPE_UNINSTALL || (f->GetFileType() == FILETYPE_EXTRA && f->GetDir().Left(5).lower() == "Extra") )
3106
			continue;
3107
 
3108
		// check if there is a matching uninstall file, ie there the script file is also an uninstall script file for a previously uninstalled package that has yet to be removed
3109
		if ( f->GetFileType() == FILETYPE_SCRIPT )
3110
		{
3111
			bool found = false;
3112
			for ( CListNode<C_File> *uNode = m_lUninstallFiles.Front(); uNode; uNode = uNode->next() )
3113
			{
3114
				C_File *uFile = uNode->Data();
3115
				if ( uFile->GetFilename().Compare(f->GetFilename()) )
3116
				{
3117
					found = true;
3118
					break;
3119
				}
3120
			}
3121
 
3122
			if ( found )
3123
				continue;
3124
		}
3125
 
3126
		if ( f->GetFileType() == FILETYPE_MOD && !f->IsFakePatch() && f->CheckFileExt("cat") )
3127
		{
3128
			if ( f->GetBaseName().Compare(m_sSetMod) )
3129
				m_sSetMod = NullString;
3130
		}
3131
 
3132
		// file is not being used by any enabled package
3133
		// set disabled and move to disabled directory
3134
		CDirIO Dir(m_sCurrentDir);
3135
		CyString newFilename = "PluginManager/Disabled/";
3136
 
3137
		// fake patches have thier own special directory
3138
		if ( f->IsFakePatch() )
3139
			newFilename += "FakePatches";
3140
		// otherwise we put them in thier usual directory structure inside the disabled dir
3141
		else
3142
			newFilename += f->GetDirectory(NULL);
3143
 
3144
		// make sure the directory exists so we can move the file
3145
		if ( !Dir.Exists(newFilename) )
3146
		{
3147
			// we couldn't create the directory for some reason, this is not good
3148
			if ( !Dir.Create(newFilename) )
3149
			{
3150
				this->AddLogEntry(SPKINSTALL_CREATEDIRECTORY_FAIL, newFilename, errors);
3151
				continue;
3152
			}
3153
			this->AddLogEntry(SPKINSTALL_CREATEDIRECTORY, newFilename, errors);
3154
		}
3155
 
3156
		// fake patches need a special directory and filename so they dont overright each other as thier filenames are always changes
3157
		// if a package with a fake patch is installed while another one is disabled, it will fill the gap left by the disabled one
3158
		// they will then end up with the same filename, if it gets disabled they would overright each other, so we change the filename to prevent that from happening
3159
		if ( f->IsFakePatch() )
3160
		{
3161
			// find package the fake patch belongs to
3162
			if ( checkPackage )
3163
			{
50 cycrow 3164
				newFilename = m_sCurrentDir + "/PluginManager/Disabled/FakePatches/FakePatch_" + checkPackage->GetNameValidFile() + "_" + checkPackage->author() + "_" + f->GetName();
1 cycrow 3165
				shuffle = true;
3166
			}
3167
		}
3168
		else if ( f->IsAutoTextFile() )
3169
		{
3170
			if ( checkPackage )
3171
			{
50 cycrow 3172
				newFilename = m_sCurrentDir + "/PluginManager/Disabled/TextFiles/Text_" + checkPackage->GetNameValidFile() + "_" + checkPackage->author() + "_" + f->GetName();
1 cycrow 3173
				shuffle = true;
3174
			}
3175
		}
3176
		// otherwise we can just use the standard filename
3177
		else
3178
			newFilename = m_sCurrentDir + "/PluginManager/Disabled/" + f->GetNameDirectory(checkPackage);
3179
 
3180
		// now to move the file by renameing it to its new location
3181
		// !!error checking!!
3182
		// check the file, if it doesn't exist, and exists as disabled, we should just adjust the setting instead of an error
3183
		CFileIO currentFile(f->GetFilePointer());
52 cycrow 3184
		if ( !currentFile.exists() )
1 cycrow 3185
		{
52 cycrow 3186
			if ( !CFileIO(newFilename).exists() )
1 cycrow 3187
			{
3188
				this->AddLogEntry(SPKINSTALL_MISSINGFILE, f->GetNameDirectory(checkPackage), errors);
3189
				continue;
3190
			}
3191
		}
3192
		// otherwise the file must exists, so lets move it
3193
		else if ( !currentFile.Rename(newFilename) )
3194
		{
3195
			this->AddLogEntry(SPKINSTALL_DISABLEFILE_FAIL, f->GetNameDirectory(checkPackage), errors);
3196
			continue;
3197
		}
3198
 
3199
		// must have been fine
3200
		this->AddLogEntry(SPKINSTALL_DISABLEFILE, f->GetNameDirectory(checkPackage), errors);
3201
 
93 cycrow 3202
		original = _pOriginalFiles->restoreFile(f, errors);
1 cycrow 3203
 
3204
		// extra file thats not in the extras directory
3205
		if ( f->GetFileType() == FILETYPE_EXTRA || f->GetFileType() == FILETYPE_MAP || f->GetFileType() == FILETYPE_SOUND )
3206
			removeDirs.PushBack(f->GetDirectory(checkPackage), NullString, true);
3207
 
3208
		// change the filename
3209
		f->SetFilename(newFilename);
3210
 
3211
		// finally mark the file as disabled so we know not to try to move it again
3212
		f->SetDisabled(true);
3213
	}
3214
 
3215
	// a fake patch has been disabled, we need to reshuffle the rest to fill in any gaps
3216
	if ( shuffle )
3217
	{
3218
		if ( progress )
3219
			progress->UpdateStatus(PROGRESS_SHUFFLEFAKE);
3220
		ShuffleFakePatches(errors);
3221
		ShuffleTextFiles(errors);
3222
	}
3223
 
3224
	// original files were restored, check to remove the original file directory if its now empty
3225
	if ( original )
3226
		removeDirs.PushBack(CyString("PluginManager/Original"));
3227
 
3228
	// remove any empty directories that we might have left
3229
	if ( !removeDirs.Empty() )
3230
		RemoveUnusedDirectories(removeDirs, errors);
3231
 
3232
	// finally mark the whole package as disabled
3233
	// recursive, we need to disable all children
3234
	for ( CBaseFile *child = m_lDisableList.First(); child; child = m_lDisableList.Next() )
3235
	{
3236
		if ( m_pEnabledMod == child )
3237
			m_pEnabledMod = NULL;
3238
		child->SetEnabled(false);
3239
 
3240
		if ( disabledPackages )
3241
			disabledPackages->push_back(child);
3242
	}
3243
 
3244
	// disabling has completed successfully, we hope
3245
	m_bDisableVanilla = false;
3246
	m_lDisableList.clear();
3247
 
3248
	this->WriteData();
3249
 
3250
	return true;
3251
}
3252
 
3253
/**
3254
 * Disables the selected package
3255
 *
3256
 * Disables all enabled files that are not being used by any other enabled package
3257
 * Any files that are being used by other enabled packages are skipped and left enabled
3258
 *
3259
 * Original Files are restored when file is disabled
3260
 *
3261
 * Fake patches are shuffled to fill in any gaps caused by disabling fake patches
3262
 *
3263
 * All files go into the Plugin/Disabled directory into thier respective directories.
3264
 *
3265
 * Any directories left empty when disabling files are then removed
3266
 *
3267
 * param: package	- Package file to be disabled
3268
 * param: errors	- A string list used to add the status as it progresses, used in debugging output
3269
 * param: progress	- The progress class, updates the progress of the current disabling.  Needs a divered class to report the progress somewhere
3270
 *
3271
 * return: boolean, true if there was no errors, otherwise false
3272
 */
3273
bool CPackages::DisablePackage ( CBaseFile *package, CyStringList *errors, CProgressInfo *progress )
3274
{
3275
	// if already disabled, just skip
3276
	if ( !package->IsEnabled() )
3277
		return true;
3278
 
3279
	m_lDisableList.clear();
3280
	if ( this->PrepareDisablePackage(package) )
3281
		return this->DisablePreparedPackages(errors, progress);
3282
 
3283
	return false;
3284
}
3285
 
3286
 
3287
/**
3288
 * Find a Package
3289
 *
3290
 * Finds a matching package so we can find if one is already installed
3291
 *
3292
 * Uses seperate functions for each package type, ie for SPK and XSP packages
3293
 */
3294
CBaseFile *CPackages::FindPackage(CBaseFile *package)
3295
{
3296
	// no point checking if we've been sent a null pointer
3297
	if ( !package )
3298
		return 0;
3299
 
3300
	// we are checking against a SPK package, so we match the name and author
3301
	if ( package->GetType() == TYPE_SPK )
50 cycrow 3302
		return FindSpkPackage(package->name(), package->author());
1 cycrow 3303
	else if ( package->GetType() == TYPE_XSP )
3304
		return FindXspPackage(((CXspFile *)package)->GetShipID());
3305
	else if ( package->GetType() == TYPE_ARCHIVE )
50 cycrow 3306
		return FindArchivePackage(package->name());
1 cycrow 3307
 
3308
	// nothing found obviously
3309
	return 0;
3310
}
3311
 
3312
CBaseFile *CPackages::FindFirstPackageWithFile(C_File *f)
3313
{
3314
	return FindNextPackageWithFile(NULL, f);
3315
}
3316
 
3317
CBaseFile *CPackages::FindNextPackageWithFile(CBaseFile *p, C_File *f)
3318
{
3319
	bool startCheck = (p) ? false : true;
3320
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
3321
	{
3322
		if ( startCheck )
3323
		{
3324
			if ( node->Data()->IsFileAdded(f) )
3325
				return node->Data();
3326
		}
3327
		else if ( p == node->Data() )
3328
			startCheck = true;
3329
	}
3330
 
3331
	return NULL;
3332
}
3333
 
3334
 
3335
/**
3336
 * Find a File
3337
 *
3338
 * Searches for a file matching the filetype and filename
3339
 * Optional dir is used for extras files
3340
 */
3341
C_File *CPackages::FindFile(int filetype, CyString filename, CyString dir)
3342
{
3343
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
3344
	{
3345
		C_File *f = node->Data();
3346
		if ( f->GetFileType() != filetype )
3347
			continue;
3348
 
3349
		if ( !f->GetFilename().Compare(filename) )
3350
			continue;
3351
 
3352
		if ( !dir.Empty() && f->GetDir().Compare(dir) )
3353
			continue;
3354
 
3355
		return f;
3356
	}
3357
 
3358
	return NULL;
3359
}
3360
 
3361
CArchiveFile *CPackages::FindArchivePackage(CyString name)
3362
{
3363
	// interate through all packages
3364
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
3365
	{
3366
		CBaseFile *file = node->Data();
3367
 
3368
		// only look for archive packages
3369
		if ( file->GetType() != TYPE_ARCHIVE )
3370
			continue;
3371
 
3372
		// now compare the name and author, "Compare" is a non case senseative check, opposed to ==.
50 cycrow 3373
		if ( file->name().Compare(name.ToString()) )
1 cycrow 3374
			return (CArchiveFile *)file;
3375
	}
3376
 
3377
	// nothing found
3378
	return 0;
3379
}
3380
 
3381
/**
3382
 * Find a SPK Package
3383
 *
3384
 * This searching all installed packages for a SPK Package matching the name and author
3385
 */
3386
CBaseFile *CPackages::FindSpkPackage(CyString name, CyString author)
3387
{
3388
	// interate through all packages
3389
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
3390
	{
3391
		CBaseFile *file = node->Data();
3392
 
3393
		// only look for spk packages
3394
		if ( file->GetType() != TYPE_SPK )
3395
			continue;
3396
 
3397
		// now compare the name and author, "Compare" is a non case senseative check, opposed to ==.
50 cycrow 3398
		if ( file->name().Compare(name.ToString()) && file->author().Compare(author.ToString()) )
1 cycrow 3399
			return file;
3400
	}
3401
 
3402
	// nothing found
3403
	return 0;
3404
}
3405
 
3406
CBaseFile *CPackages::FindPackage(CyString name, CyString author)
3407
{
3408
	// interate through all packages
3409
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
3410
	{
3411
		CBaseFile *file = node->Data();
3412
 
3413
		// now compare the name and author, "Compare" is a non case senseative check, opposed to ==.
50 cycrow 3414
		if ( file->name().Compare(name.ToString()) && file->author().Compare(author.ToString()) )
1 cycrow 3415
			return file;
3416
	}
3417
 
3418
	// nothing found
3419
	return 0;
3420
}
3421
 
3422
/**
3423
 * Find a XSP Package
3424
 *
3425
 * This searching all installed packages for a XSP Package matching the object id
3426
 */
3427
CBaseFile *CPackages::FindXspPackage(CyString id)
3428
{
3429
	// interate through all packages
3430
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
3431
	{
3432
		CBaseFile *file = node->Data();
3433
 
3434
		// only look for spk packages
3435
		if ( file->GetType() != TYPE_XSP )
3436
			continue;
3437
 
3438
		// now compare the id, "Compare" is a non case senseative check, opposed to ==.
14 cycrow 3439
		if ( ((CXspFile *)file)->GetShipID().Compare(id.ToString()) )
1 cycrow 3440
			return file;
3441
	}
3442
 
3443
	// nothing found
3444
	return 0;
3445
}
3446
 
3447
/**
3448
 * Update the used files count
3449
 *
3450
 * counts how many packages are currently using the file
3451
 */
3452
void CPackages::UpdateUsedFiles(CLinkList<CBaseFile> *ignoreList, bool includedisabled)
3453
{
3454
	// clear amounts for all files
3455
	CListNode<C_File> *fnode = m_lFiles.Front();
3456
	while ( fnode )
3457
	{
3458
		fnode->Data()->ClearUsed();
3459
		fnode = fnode->next();
3460
	}
3461
 
3462
	// update for all packages
3463
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node= node->next() )
3464
	{
3465
		CBaseFile *file = node->Data();
3466
		if ( (ignoreList) && (ignoreList->FindData(file)) )
3467
			continue;
3468
		if ( !includedisabled && !file->IsEnabled() )
3469
			continue;
3470
		// now mark all files
3471
		CListNode<C_File> *fnode = file->GetFileList()->Front();
3472
		while ( fnode )
3473
		{
3474
			fnode->Data()->IncUsed();
3475
			fnode = fnode->next();
3476
		}
3477
	}
3478
}
3479
 
3480
/**
3481
 * Removes all empty directories that might have been created
3482
 */
3483
void CPackages::RemoveUnusedDirectories(CyStringList &dirs, CyStringList *errors)
3484
{
3485
	CDirIO Dir(m_sCurrentDir);
3486
	for ( SStringList *str = dirs.Head(); str; str = str->next )
3487
	{
3488
		CyString dir = str->str;
3489
 
3490
		CyStringList removedDir;
3491
		if ( Dir.RemoveDir(dir, false, true, &removedDir) || !removedDir.Empty() )
3492
		{
3493
			for ( SStringList *node = removedDir.Head(); node; node = node->next )
3494
			{
3495
				CyString displayName = node->str;
3496
				displayName = displayName.Remove(m_sCurrentDir);
3497
				this->AddLogEntry(SPKINSTALL_REMOVEDIR, displayName, errors);
3498
			}
3499
		}
3500
	}
3501
}
3502
 
3503
/**
3504
 * Update signed status
3505
 *
3506
 * Updates the signed status of all packages
3507
 */
3508
void CPackages::UpdateSigned()
3509
{
3510
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
3511
	{
3512
		CBaseFile *p = node->Data();
3513
 
3514
		if ( p->GetType() != TYPE_SPK )
3515
			continue;
3516
 
3517
		((CSpkFile *)p)->UpdateSigned(false);
3518
	}
3519
}
3520
 
3521
/**
3522
 * Check validity of package file
3523
 *
3524
 * Checks if there is a newer version of the package installed
3525
 */
3526
int CPackages::CheckInstallPackage(CBaseFile *package, int check)
3527
{
3528
	if ( package->GetType() == TYPE_XSP && m_iGame == GAME_X2 )
3529
		return INSTALLCHECK_NOSHIP;
3530
 
3531
	// search for an old version
3532
	CBaseFile *oldPackage = FindPackage(package);
3533
 
3534
	// check versions are newer
3535
	if (oldPackage && (check & IC_OLDVERSION))
3536
	{
50 cycrow 3537
		if ( oldPackage->version().compareVersion(package->version()) == COMPARE_OLDER )
1 cycrow 3538
			return INSTALLCHECK_OLDVERSION;
3539
	}
3540
 
3541
	// now check for game version
3542
	if ((check & IC_WRONGGAME) || (check & IC_WRONGVERSION))
3543
	{
3544
		if ( package->AnyGameCompatability() )
3545
		{
3546
			if ( (check & IC_WRONGGAME) && (!package->CheckGameCompatability(m_iGame)) )
3547
				return INSTALLCHECK_WRONGGAME;
3548
			else if ( (check & IC_WRONGVERSION) && (!package->CheckGameVersionCompatability(m_iGame, m_sGameVersion, m_iGameVersion)) )
3549
				return INSTALLCHECK_WRONGVERSION;
3550
		}
3551
	}
3552
 
3553
	// check for modified
3554
	if (m_bVanilla && (check & IC_MODIFIED))
3555
	{
3556
		if ( !package->IsSigned() )
3557
			return INSTALLCHECK_MODIFIED;
3558
	}
3559
 
3560
	return INSTALLCHECK_OK;
3561
}
3562
 
3563
bool CPackages::CheckOtherPackage(CBaseFile *package)
3564
{
3565
	// check the need for another mod
3566
	if ( package->GetType() == TYPE_SPK )
3567
	{
3568
		CSpkFile *spk = (CSpkFile *)package;
3569
		if ( spk->IsAnotherMod() )
3570
		{
3571
			if ( !FindSpkPackage(spk->GetOtherName(), spk->GetOtherAuthor()) )
3572
			{
3573
				// check the install list
3574
				if ( m_lInstallList.empty() )
3575
					return false;
3576
 
3577
				bool found = false;
3578
				for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
3579
				{
50 cycrow 3580
					if ( spk->GetOtherName().Compare(node->Data()->name()) && spk->GetOtherAuthor().Compare(node->Data()->author()) )
1 cycrow 3581
					{
3582
						found = true;
3583
						break;
3584
					}
3585
				}
3586
 
3587
				if ( !found )
3588
					return false;
3589
			}
3590
		}
3591
	}
3592
 
3593
	return true;
3594
}
3595
 
3596
bool CPackages::CheckEnabledDependacy(CBaseFile *p)
3597
{
3598
	// check the for another mod
3599
	if ( p->GetType() == TYPE_SPK )
3600
	{
3601
		if ( ((CSpkFile *)p)->IsAnotherMod() )
3602
		{
3603
			CBaseFile *parent = this->FindSpkPackage(((CSpkFile *)p)->GetOtherName(), ((CSpkFile *)p)->GetOtherAuthor());
3604
			if ( parent )
3605
			{
3606
				if ( !parent->IsEnabled() )
3607
					return false;
3608
			}
3609
			else
3610
				return false;
3611
		}
3612
	}
3613
 
3614
	// check any dependacies
3615
	if ( p->AnyDependacies() )
3616
	{
3617
		for ( CListNode<SNeededLibrary> *dNode = p->GetNeededLibraries()->Front(); dNode; dNode = dNode->next() )
3618
		{
3619
			if ( dNode->Data()->sName.Compare("<package>") )
3620
				continue;
3621
			if ( !this->CheckInstalledDependacy(dNode->Data()->sName, dNode->Data()->sAuthor, dNode->Data()->sMinVersion, true, true) )
3622
				return false;
3623
		}
3624
	}
3625
 
3626
	return true;
3627
}
3628
 
3629
bool CPackages::CheckInstalledDependacy(CyString name, CyString author, CyString version, bool onlyEnabled, bool includePrepared)
3630
{
3631
	CBaseFile *p = this->FindSpkPackage(name, author);
3632
	if ( p )
3633
	{
3634
		// now check version
50 cycrow 3635
		if ( version.CompareVersion(p->version()) == COMPARE_OLDER )
1 cycrow 3636
			return false;
3637
 
3638
		if ( onlyEnabled && !p->IsEnabled() )
3639
			return false;
3640
 
3641
		return true;
3642
	}
3643
 
3644
	// now check the prepared list
3645
	if ( includePrepared )
3646
	{
3647
		for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
3648
		{
3649
			p = node->Data();
3650
			if ( !p )
3651
				continue;
3652
 
50 cycrow 3653
			if ( p->name().Compare(name.ToString()) && p->author().Compare(author.ToString()) )
1 cycrow 3654
			{
50 cycrow 3655
				if ( version.CompareVersion(p->version()) == COMPARE_OLDER )
1 cycrow 3656
					continue;
3657
 
3658
				if ( onlyEnabled && !p->IsEnabled() )
3659
					continue;
3660
 
3661
				return true;
3662
			}
3663
		}
3664
 
3665
		m_lInstallList.RemoveEmpty();
3666
	}
3667
 
3668
	return false;
3669
}
3670
 
3671
int CPackages::GetMissingDependacies(CBaseFile *p, CyStringList *list, bool onlyEnabled, bool includePrepared)
3672
{
3673
	int count = 0;
3674
	CLinkList<SNeededLibrary> *neededList = p->GetNeededLibraries();
3675
	if ( neededList )
3676
	{
3677
		for ( CListNode<SNeededLibrary> *node = neededList->Front(); node; node = node->next() )
3678
		{
3679
			SNeededLibrary *nl = node->Data();
50 cycrow 3680
			if ( !CheckInstalledDependacy((nl->sName.Compare("<package>")) ? p->name() : nl->sName, (nl->sAuthor.Compare("<author>")) ? p->author() : nl->sAuthor, nl->sMinVersion, (nl->sName.Compare("<package>")) ? false : onlyEnabled, (nl->sName.Compare("<package>")) ? false : includePrepared) )
1 cycrow 3681
			{
3682
				if ( list )
50 cycrow 3683
					list->PushBack(((nl->sName.Compare("<package>")) ? CyString(p->name()) : nl->sName) + "|" + nl->sMinVersion, (nl->sAuthor.Compare("<author>")) ? CyString(p->author()) : nl->sAuthor);
1 cycrow 3684
				++count;
3685
			}
3686
		}
3687
	}
3688
 
3689
	if ( p->GetType() == TYPE_SPK )
3690
	{
3691
		CSpkFile *spk = (CSpkFile *)p;
3692
		if ( spk->IsAnotherMod() )
3693
		{
3694
			bool found = true;
3695
			if ( !this->FindSpkPackage(spk->GetOtherName(), spk->GetOtherAuthor()) )
3696
			{
3697
				if ( includePrepared )
3698
				{
3699
					found = false;
3700
					for ( CListNode<CBaseFile> *pNode = m_lInstallList.Front(); pNode; pNode = pNode->next() )
3701
					{
3702
						CBaseFile *checkP = pNode->Data();
50 cycrow 3703
						if ( p->author().Compare(checkP->author()) && p->name().Compare(checkP->name()) )
1 cycrow 3704
						{
3705
							found = true;
3706
							break;
3707
						}
3708
					}
3709
				}
3710
				else
3711
					found = false;
3712
			}
3713
 
3714
			if ( !found )
3715
			{
3716
				if ( list )
10 cycrow 3717
					list->PushBack(CyString(spk->GetOtherName()), CyString(spk->GetOtherAuthor()));
1 cycrow 3718
				++count;
3719
			}
3720
		}
3721
	}
3722
 
3723
	return count;
3724
}
3725
 
3726
int CPackages::CheckPreparedInstallRequired(CLinkList<CBaseFile> *list)
3727
{
3728
	// loop through all packages
3729
	int count = 0;
3730
	for ( CListNode<CBaseFile> *node = m_lInstallList.Front(); node; node = node->next() )
3731
	{
3732
		CBaseFile *p = node->Data();
3733
 
3734
		// no requirements found, remove from list
3735
		bool missingDep = false;
3736
		if ( !this->CheckOtherPackage(p) )
3737
			missingDep = true;
3738
		else if ( this->GetMissingDependacies(p, NULL, false, true) )
3739
			missingDep = true;
3740
 
3741
		if ( missingDep )
3742
		{
3743
			if ( list )
3744
			{
3745
				node->ChangeData(NULL);
3746
				list->push_back(p);
3747
			}
3748
			else
3749
				node->DeleteData();
3750
			++count;
3751
		}
3752
	}
3753
 
3754
	m_lInstallList.RemoveEmpty();
3755
 
3756
	return count;
3757
}
3758
 
3759
 
3760
/**
3761
 * Remove uninstall file
3762
 *
3763
 * Removes a single uninstall file
3764
 */
3765
bool CPackages::RemoveUninstallFile(C_File *file, CyStringList *errors)
3766
{
3767
	CFileIO fio(file->GetFilePointer());
52 cycrow 3768
	if ( fio.exists() )
1 cycrow 3769
	{
52 cycrow 3770
		if ( fio.remove() ) {
1 cycrow 3771
			this->AddLogEntry(SPKINSTALL_UNINSTALL_REMOVE, file->GetNameDirectory(NULL), errors);
3772
			return true;
3773
		}
3774
		else if ( errors )
3775
			this->AddLogEntry(SPKINSTALL_UNINSTALL_REMOVE_FAIL, file->GetNameDirectory(NULL), errors);
3776
	}
3777
 
3778
	return false;
3779
}
3780
 
3781
/**
3782
 * Remove uninstall scripts
3783
 *
3784
 * Removes any unused unisntall scripts
3785
 * Finds if any scripts are in the current package
3786
 */
3787
int CPackages::RemoveUninstallScripts(CyStringList *errors, CProgressInfo *progress)
3788
{
3789
	if ( m_lUninstallFiles.empty() )
3790
		return 0;
3791
 
3792
	UpdateUsedFiles();
3793
	int files = 0;
3794
 
3795
	for ( CListNode<C_File> *node = m_lUninstallFiles.Back(); node; node = node->prev() )
3796
	{
3797
		if ( progress )
3798
			progress->UpdateProgress(files, m_lUninstallFiles.size());
3799
		files++;
3800
 
3801
		C_File *file = node->Data();
3802
 
3803
		// first check if there is a matching file
3804
		bool found = false;
3805
		for ( CListNode<C_File> *fNode = m_lFiles.Front(); fNode; fNode = fNode->next() )
3806
		{
3807
			C_File *checkFile = fNode->Data();
3808
			if ( checkFile->GetFileType() != FILETYPE_SCRIPT )
3809
				continue;
3810
 
3811
			if ( checkFile->GetFilename().Compare(file->GetFilename()) )
3812
			{
3813
				found = true;
3814
				break;
3815
			}
3816
		}
3817
 
3818
		// not found a matching file, we can safetly remove it
3819
		if ( !found )
3820
		{
3821
			if ( RemoveUninstallFile(file) )
3822
				node->DeleteData();
3823
		}
3824
	}
3825
 
3826
	m_lUninstallFiles.RemoveEmpty();
3827
 
3828
	return files;
3829
}
3830
 
3831
 
3832
/**
3833
 * Remove unused shared file
3834
 *
3835
 * Removes a single file
3836
 */
3837
bool CPackages::RemoveSharedFile(C_File *file, CyStringList *errors)
3838
{
3839
	CFileIO fio(file->GetFilePointer());
52 cycrow 3840
	if ( fio.exists() )
1 cycrow 3841
	{
52 cycrow 3842
		if ( fio.remove() ) {
1 cycrow 3843
			this->AddLogEntry(SPKINSTALL_SHARED, file->GetNameDirectory(NULL), errors);
3844
			delete file;
3845
			return true;
3846
		}
3847
		else if ( errors )
3848
			this->AddLogEntry(SPKINSTALL_SHARED_FAIL, file->GetNameDirectory(NULL), errors);
3849
	}
3850
 
3851
	return false;
3852
}
3853
 
3854
/**
3855
 * Remove Unused Shared Files
3856
 *
3857
 * Files that have been marked as shared will not be removed or disabled when the last package is removed
3858
 * This function will remove any that are no longer connected with packages
3859
 *
3860
 * Marked shared fiels are mainly used for library scripts that arn't always added to packages
3861
 */
3862
int CPackages::RemoveUnusedSharedFiles(CyStringList *errors, CProgressInfo *progress)
3863
{
3864
	UpdateUsedFiles();
3865
	int files = 0;
3866
	int done = 0;
3867
 
3868
	for ( CListNode<C_File> *node = m_lFiles.Back(); node; node = node->prev() )
3869
	{
3870
		if ( progress )
3871
			progress->UpdateProgress(files, m_lFiles.size());
3872
		files++;
3873
 
3874
		C_File *file = node->Data();
3875
 
3876
		// only do marked shared files
3877
		if ( !file->IsShared() )
3878
			continue;
3879
 
3880
		// only do ones that are no longer needed
3881
		if ( file->GetUsed() )
3882
			continue;
3883
 
3884
		if ( RemoveSharedFile(file, errors) )
3885
			++done;
3886
		node->ChangeData(NULL);
3887
	}
3888
 
3889
	m_lFiles.RemoveEmpty();
3890
 
3891
	return done;
3892
}
3893
 
3894
/**
3895
 * Any Unused Shared
3896
 *
3897
 * Checks if theres any unused shared files available
3898
 *
3899
 * Any file thats marked as shared, and is no longer connected to any installed package
3900
 */
3901
bool CPackages::AnyUnusedShared()
3902
{
3903
	UpdateUsedFiles();
3904
 
3905
	for ( CListNode<C_File> *node = m_lFiles.Back(); node; node = node->prev() )
3906
	{
3907
		C_File *file = node->Data();
3908
 
3909
		// only do marked shared files
3910
		if ( !file->IsShared() )
3911
			continue;
3912
 
3913
		// only do ones that are no longer needed
3914
		if ( file->GetUsed() )
3915
			continue;
3916
 
3917
		return true;
3918
	}
3919
 
3920
	return false;
3921
 
3922
}
3923
 
3924
void CPackages::ShuffleTextFiles(CyStringList *errors)
3925
{
3926
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
3927
	{
3928
		C_File *f = node->Data();
3929
		// only do files that are enabled
3930
		if ( f->IsDisabled() )
3931
			continue;
3932
 
3933
		if ( f->GetFileType() != FILETYPE_TEXT )
3934
			continue;
3935
 
3936
		// check if the file is an auto text file
3937
		if ( !f->IsAutoTextFile() )
3938
			continue;
3939
 
3940
		// we need to rename it
3941
		int current = FindNextTextFile();
3942
		if ( current < f->GetTextFileID() )
3943
		{
3944
			CFileIO moveFile(f->GetFilePointer());
3945
 
3946
			CyString newName = SPK::FormatTextName(current, m_iLanguage, (m_iGameFlags & EXEFLAG_TCTEXT)) + "." + moveFile.GetFileExtension();
3947
			if ( moveFile.Rename(m_sCurrentDir + "/t/" + newName) )
3948
			{
3949
				this->AddLogEntry(SPKINSTALL_AUTOTEXT, f->GetName() + "~" + newName, errors);
3950
				f->SetName(newName);
3951
			}
3952
			else
3953
				this->AddLogEntry(SPKINSTALL_AUTOTEXT_FAIL, f->GetName() + "~" + newName, errors);
3954
		}
3955
	}
3956
}
3957
 
3958
/**
3959
 * Shuffle Fake Patches
3960
 *
3961
 * Rename the fake patches so they are always in sequence to be loaded into the game
3962
 *
3963
 * IE, when one is removed, the rest need to be shuffled down so theres no gaps
3964
 */
3965
void CPackages::ShuffleFakePatches(CyStringList *errors)
3966
{
3967
	int check = FindNextFakePatch();
3968
 
3969
	// lets make sure our order is correct
3970
	// find Lowest Fake Patch Installed
3971
	CLinkList<C_File> doneList;
3972
	int lowest = FindLowestFakePatchInstalled();
3973
	if ( check < lowest ) lowest = check; // gap at the beginning, lets use that
3974
 
3975
	// lets define the order
3976
	CyStringList fakePatchOrder;
3977
	for ( SStringList *str = m_lFakePatchOrder.Head(); str; str = str->next )
3978
		fakePatchOrder.PushBack(str->str, str->data);
3979
 
3980
	// add any other packages that need to be ordered
3981
	// we need to work out the correct order
3982
	CLinkList<CBaseFile> packages;
3983
	for ( CListNode<CBaseFile> *pNode = m_lPackages.Front(); pNode; pNode = pNode->next() )
3984
	{
3985
		CBaseFile *p = pNode->Data();
3986
		// search for any fake patches in package
3987
		if ( !p->IsEnabled() ) continue;
3988
		if ( !p->AnyFileType(FILETYPE_MOD) ) continue;
3989
 
3990
		// must have an order define
3991
		if ( !p->AnyFakePatchOrder() ) continue;
3992
 
3993
		// check if theres any already ordered (manual)
3994
		bool added = false;
3995
		for ( SStringList *sCheck = fakePatchOrder.Head(); sCheck; sCheck = sCheck->next )
3996
		{
50 cycrow 3997
			if ( sCheck->str.Compare(CyString(p->name())) && sCheck->data.Compare(CyString(p->author())) )
1 cycrow 3998
			{
3999
				added = true;
4000
				break;
4001
			}
4002
		}
4003
 
4004
		if ( added ) continue;
4005
 
4006
		bool anyFound = false;
4007
		for ( C_File *file = p->GetFirstFile(FILETYPE_MOD); file; file = p->GetNextFile(file) )
4008
		{
4009
			if ( !file->IsFakePatch() ) continue;
4010
			if ( !file->CheckFileExt("cat") ) continue;
4011
			if ( doneList.FindData(file) ) 	continue;
4012
			anyFound = true;
4013
			break;
4014
		}
4015
 
4016
		// we have some fake patches that need to be shuffled
4017
		if ( anyFound )
4018
			packages.push_back(p);
4019
	}
4020
 
4021
	// lets adjust the order (only if theres more than 1
4022
	if ( packages.size() > 1 )
4023
	{
4024
		CLinkList<CBaseFile> sortedPackages;
4025
 
4026
		// first add all the packages that dont need to be installed after
4027
		for ( CListNode<CBaseFile> *pNode = packages.Front(); pNode; pNode = pNode->next() )
4028
		{
4029
			CBaseFile *p = pNode->Data();
4030
			// we have a before and not after
4031
			if ( !p->GetFakePatchBeforeOrder().Empty() && p->GetFakePatchAfterOrder().Empty() )
4032
			{
4033
				// if we have to install before, check if any on the list
4034
				int earliestPos = -1;
4035
				bool notAdded = true;
4036
				for ( SStringList *str = p->GetFakePatchBeforeOrder().Head(); str; str = str->next )
4037
				{
4038
					int pos = 0;
4039
					for ( CListNode<CBaseFile> *sNode = sortedPackages.Front(); sNode; sNode = sNode->next() )
4040
					{
50 cycrow 4041
						if ( str->str.Compare(CyString(sNode->Data()->name())) && str->data.Compare(CyString(sNode->Data()->author())) )
1 cycrow 4042
						{
4043
							if ( earliestPos == -1 || pos < earliestPos )
4044
								earliestPos = pos;
4045
							break;
4046
						}
4047
						++pos;
4048
					}					
4049
				}
4050
 
4051
				if ( earliestPos > -1 )
4052
					sortedPackages.insert(earliestPos, p);
4053
				// otherwise just add it at the back
4054
				else
4055
					sortedPackages.push_back(p);
4056
 
4057
				// remove from the list
4058
				pNode->ChangeData(NULL);
4059
			}
4060
		}
4061
 
4062
		// now do the packages that have both before and after
4063
		packages.RemoveEmpty();
4064
		for ( CListNode<CBaseFile> *pNode = packages.Front(); pNode; pNode = pNode->next() )
4065
		{
4066
			CBaseFile *p = pNode->Data();
4067
			if ( !p->GetFakePatchBeforeOrder().Empty() && !p->GetFakePatchAfterOrder().Empty() )
4068
			{
4069
			}
4070
		}
4071
 
4072
		// add them onto the list
4073
		for ( CListNode<CBaseFile> *pNode = sortedPackages.Front(); pNode; pNode = pNode->next() )
50 cycrow 4074
			fakePatchOrder.PushBack(CyString(pNode->Data()->name()), CyString(pNode->Data()->author()));
1 cycrow 4075
	}
4076
 
4077
	// now add to do list
4078
	for ( CListNode<CBaseFile> *pNode = packages.Front(); pNode; pNode = pNode->next() )
50 cycrow 4079
		fakePatchOrder.PushBack(CyString(pNode->Data()->name()), CyString(pNode->Data()->author()));
1 cycrow 4080
 
4081
	for ( SStringList *str = fakePatchOrder.Head(); str; str = str->next )
4082
	{
4083
		CBaseFile *package = FindPackage(str->str, str->data);
4084
		if ( package )
4085
		{
4086
			// might have more than 1 fake patch for the file, so we'll need the lowest
4087
			while ( true )
4088
			{
4089
				C_File *lowestFile = NULL;
4090
				for ( C_File *file = package->GetFirstFile(FILETYPE_MOD); file; file = package->GetNextFile(file) )
4091
				{
4092
					if ( !file->IsFakePatch() ) continue;
4093
					if ( !file->CheckFileExt("cat") ) continue; // only do the cat file, we can shuffle the dat file to match later
4094
					if ( doneList.FindData(file) ) continue; // already done?
4095
 
4096
					if ( !lowestFile )
4097
						lowestFile = file;
4098
					else
4099
					{
4100
						if ( file->GetBaseName().ToInt() < lowestFile->GetBaseName().ToInt() )
4101
							lowestFile = file;
4102
					}
4103
				}
4104
 
4105
				if ( !lowestFile ) // no more files ?
4106
					break;
4107
 
4108
				// check its filename, it might already be in the correct place
4109
				if ( lowestFile->GetBaseName().ToInt() != lowest )
4110
				{
4111
					// if the file already exists, we need to move it elsewhere
4112
					CyString nextName = CyString::Number(lowest).PadNumber(2);
52 cycrow 4113
					if ( CFileIO(m_sCurrentDir + "/" + nextName + ".cat").ExistsOld() )
1 cycrow 4114
					{
4115
						// find the file in our internal file list
4116
						C_File *moveFile = FindFile(FILETYPE_MOD, nextName + ".cat");
4117
						if ( !moveFile ) // must not have it in our list ? lets move to the next
4118
						{
4119
							lowest++;
4120
							continue;
4121
						}
4122
 
4123
						// now we can move the the cat/dat file elsewhere, lets shuffle it to the highest free number
4124
						ShufflePatchTo(moveFile, FindLastFakePatch(), errors);
4125
					}
4126
 
4127
					// space should be free, now lets shuffle it
4128
					ShufflePatchTo(lowestFile, lowest, errors);
4129
				}
4130
 
4131
				doneList.push_back(lowestFile); // we've done this file now
4132
				lowest++; // move up the lowest ready for the next patch
4133
			}
4134
		}
4135
	}
4136
 
4137
	// now lets shuffle the rest
4138
	// now find any packages with greater fake patchs and fill the gaps
4139
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
4140
	{
4141
		C_File *f = node->Data();
4142
		// already done?
4143
		if ( doneList.FindData(f) ) 
4144
			continue;
4145
 
4146
		// only do files that are enabled
4147
		if ( f->IsDisabled() )
4148
			continue;
4149
 
4150
		// check if the file is a fake patch
4151
		if ( !f->IsFakePatch() )
4152
			continue;
4153
 
4154
		// we only want cat and dat files, all fake patchs should be, but incase theres an error in the package somewhere we can check
4155
		if ( !f->CheckFileExt("cat") )
4156
			continue;
4157
 
4158
		// now lets check if its greater than our gap
4159
		int check = FindNextFakePatch();
4160
		int patchNum = f->GetFilename().GetToken(".", 1, 1).ToInt();
4161
		if ( patchNum <= check )
4162
			continue;
4163
 
4164
		ShufflePatchTo(f, check, errors);
4165
	}
4166
}
4167
 
4168
void CPackages::ShufflePatchTo(C_File *file, int to, CyStringList *errors)
4169
{
4170
	// it is, we need to shift this to fill the gap
4171
	CyString newName = CyString::Number(to).PadNumber(2) + "." + file->GetFileExt();
4172
 
4173
	// now rename the file
4174
	CFileIO moveFile(file->GetFilePointer());
4175
	if ( moveFile.Rename(m_sCurrentDir + "/" + newName) )
4176
	{
4177
		// display moveing
4178
		this->AddLogEntry(SPKINSTALL_FAKEPATCH, file->GetName() + "~" + newName, errors);
4179
 
4180
		// now find the matching pairing if it exists
4181
		for ( CListNode<C_File> *node2 = m_lFiles.Front(); node2; node2 = node2->next() )
4182
		{
4183
			C_File *f2 = node2->Data();
4184
 
4185
			if ( f2->IsDisabled() || !f2->IsFakePatch() || f2->CheckFileExt(file->GetFileExt()) )
4186
				continue;
4187
 
4188
			// needs to be the same file
4189
			if ( f2->GetBaseName() != file->GetBaseName() )
4190
				continue;
4191
 
4192
			CyString newName2 = CyString::Number(to).PadNumber(2) + "." + f2->GetFileExt();
4193
			CFileIO moveFile(f2->GetFilePointer());
4194
			if ( moveFile.Rename(m_sCurrentDir + "/" + newName2) )
4195
			{
4196
				this->AddLogEntry(SPKINSTALL_FAKEPATCH, f2->GetName() + "~" + newName2, errors);
4197
				f2->SetName(newName2);
4198
			}
4199
			else
4200
				this->AddLogEntry(SPKINSTALL_FAKEPATCH_FAIL, f2->GetName() + "~" + newName2, errors);
4201
		}
4202
 
4203
		// finally make sure the internal name matches the new one
4204
		file->SetName(newName);
4205
	}
4206
	else
4207
		this->AddLogEntry(SPKINSTALL_FAKEPATCH_FAIL, file->GetName() + "~" + newName, errors);
4208
}
4209
 
4210
int CPackages::FindLowestFakePatchInstalled()
4211
{
4212
	int lowest = 99;
4213
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
4214
	{
4215
		CBaseFile *p = node->Data();
4216
		if ( !p->IsEnabled() ) continue;
4217
		if ( !p->AnyFileType(FILETYPE_MOD) ) continue;
4218
 
4219
		// now get all fake patches
4220
		for ( C_File *file = p->GetFirstFile(FILETYPE_MOD); file; file = p->GetNextFile(file) )
4221
		{
4222
			if ( !file->IsFakePatch() ) continue;
4223
			if ( file->CheckFileExt("dat") ) continue;
4224
			int check = file->GetBaseName().ToInt();
4225
			if ( check < lowest )
4226
				lowest = check;
4227
		}
4228
	}
4229
 
4230
	return lowest;
4231
}
4232
 
4233
int CPackages::FindLastFakePatch(int start, CyString dir)
4234
{
4235
	CDirIO Dir((dir.Empty()) ? m_sCurrentDir : dir);
4236
 
4237
	int check = start;
4238
	while ( check > 0 )
4239
	{
4240
		CyString checkStr = CyString::Number(check).PadNumber(2);
4241
 
4242
		// check if a cat file exists
4243
		if ( !Dir.Exists(checkStr + ".cat") )
4244
		{
4245
			// it doen't, check if theres a dat file (incase of package error)
4246
			if ( !Dir.Exists(checkStr + ".dat") )
4247
				break;
4248
		}
4249
		--check;
4250
	}
4251
 
4252
	return check;
4253
}
4254
 
4255
/**
4256
 * Find next fake patch
4257
 *
4258
 * Searching for the next gap in patches, starting with 01.cat to 99.cat
4259
 */
4260
int CPackages::FindNextFakePatch(int start, CyString dir)
4261
{
4262
	CDirIO Dir((dir.Empty()) ? m_sCurrentDir : dir);
4263
 
4264
	int check = start;
4265
	while ( check < 99 )
4266
	{
4267
		++check;
4268
		CyString checkStr = CyString::Number(check).PadNumber(2);
4269
 
4270
		// check if a cat file exists
4271
		if ( !Dir.Exists(checkStr + ".cat") )
4272
		{
4273
			// it doen't, check if theres a dat file (incase of package error)
4274
			if ( !Dir.Exists(checkStr + ".dat") )
4275
				break;
4276
		}
4277
	}
4278
 
4279
	return check;
4280
}
4281
 
4282
/**
4283
 * Find next text file
4284
 *
4285
 * Searching for the next gap in automatic text files, start with 0003-LXXX or XX0003
4286
 */
4287
int CPackages::FindNextTextFile(int start, CyString dir)
4288
{
4289
	int check = start;
4290
	if ( check < 2 ) check = 2;
4291
	while ( check < 9999 )
4292
	{
4293
		++check;
43 cycrow 4294
		Utils::String newFilename = SPK::FormatTextName(check, m_iLanguage, (m_iGameFlags & EXEFLAG_TCTEXT)).ToString();
1 cycrow 4295
 
43 cycrow 4296
		// check the vfs
4297
		if ( m_pGameVFS.isFileAvailable("t/" + newFilename + ".pck") ) continue;
4298
		if ( m_pGameVFS.isFileAvailable("t/" + newFilename + ".xml") ) continue;
4299
 
4300
		break;
1 cycrow 4301
	}
4302
 
4303
	return check;
4304
}
4305
 
4306
int CPackages::FindLastTextFile(int start, CyString dir)
4307
{
4308
	CDirIO Dir((dir.Empty()) ? m_sCurrentDir : dir);
4309
	Dir.cd("t");
4310
 
4311
	int check = start;
4312
	while ( check < 9999 )
4313
	{
4314
		++check;
4315
		CyString newFilename = SPK::FormatTextName(check, m_iLanguage, (m_iGameFlags & EXEFLAG_TCTEXT));
4316
 
4317
		// check if a packed file exists
4318
		if ( !Dir.Exists(newFilename + ".pck") )
4319
		{
4320
			// it doen't, check if theres an unpacked file
4321
			if ( !Dir.Exists(newFilename + ".xml") )
4322
				break;
4323
		}
4324
	}
4325
 
4326
	return check;
4327
}
4328
 
4329
/**
4330
 * Read game language
4331
 *
4332
 * Reads the lang.dat file from the game directory for the language id
4333
 */
4334
void CPackages::ReadGameLanguage(bool force)
4335
{
4336
	// check if lauguage is already set
4337
	if ( !force && m_iLanguage )
4338
		return;
4339
 
4340
	CDirIO Dir(m_sCurrentDir);
4341
 
4342
	// check for lang.dat file
4343
	if ( Dir.Exists("lang.dat") )
4344
	{
4345
		CFileIO File(Dir.File("lang.dat"));
4346
 
4347
		size_t size;
4348
		char *data = File.ReadToData(&size);
4349
 
4350
		if ( data )
4351
		{
4352
			CyString str(data);
4353
			m_iLanguage = str.GetToken("\n", 1, 1).GetToken(" ", 1, 1).ToInt();
4354
		}
4355
	}
4356
}
4357
 
4358
/**
4359
 * Create Language Text File
4360
 *
4361
 * Creates text files for all packages into the correct language
4362
 */
4363
void CPackages::CreateLanguageTextFiles(CyStringList *errors)
4364
{
4365
	// no need to create them if theres no language to use
4366
	if ( !m_iLanguage )
4367
		return;
4368
 
4369
	// find all text files
4370
	CyStringList ids;
4371
 
4372
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
4373
	{
4374
		C_File *f = node->Data();
4375
		// only do text fiels
4376
		if ( f->GetFileType() != FILETYPE_TEXT )
4377
			continue;
4378
 
4379
		CyString id, lang;
4380
		if ( m_iGameFlags & EXEFLAG_TCTEXT )
4381
		{
4382
			id = f->GetBaseName().GetToken("-", 1, 1);
4383
			lang = f->GetBaseName().GetToken("-", 2, 2);
4384
			if ( lang.Empty() )
4385
				lang = "NULL";
4386
			else
4387
				lang = lang.Erase(0, 1);  // remove the "L"
4388
		}
4389
		else
4390
		{
4391
			lang = f->GetBaseName().Left((int)f->GetBaseName().Length() - 4).PadNumber(3);
4392
			id = f->GetBaseName().Mid(((int)f->GetBaseName().Length() - 4) + 1, 4);
4393
		}
4394
 
4395
		SStringList *strList = ids.FindString(id);
4396
 
4397
		// not added, add a new one
4398
		if ( !strList )
4399
			strList = ids.PushBack(id, lang);
4400
		else
4401
		{
4402
			if ( strList->data.Empty() )
4403
				strList->data = lang;
4404
			else
4405
			{
4406
				strList->data += ":";
4407
				strList->data += lang;
4408
			}
4409
		}
4410
	}
4411
 
4412
	// we should now have a list of all text files, we need to remove those that have a matching language
4413
	for ( SStringList *sNode = ids.Head(); sNode; sNode = sNode->next )
4414
	{
4415
		int size = 0;
4416
		CyString *data = sNode->data.SplitToken(':', &size);
4417
 
4418
		// huh ? we shouldn't have this
4419
		if ( !size )
4420
			continue;
4421
 
4422
		// lets search for a matching id
4423
		int useId = 0;
4424
		bool found = false;
4425
		for ( int i = 0; i < size; i++ )
4426
		{
4427
			if ( data[i] == "NULL" )
4428
				useId = -1;
4429
			else
4430
			{
4431
				int num = data[i].ToInt();
4432
				if ( num == m_iLanguage )
4433
				{
4434
					found = true;
4435
					useId = m_iLanguage;
4436
					break;
4437
				}
4438
				// prioities the text file to use, no language first, then 44, then 49, otherwise, we pick the first available
4439
				else if ( num == 44 && useId != -1)
4440
					useId = 44;
4441
				// if we have a german language, and its not yet found english or null
4442
				else if ( num == 49 && useId != 44 && useId != -1 )
4443
					useId = 49;
4444
				// if we have not found a valid language yet, we will use this one
4445
				else if ( !useId )
4446
					useId = num;
4447
			}
4448
		}
4449
 
4450
		if ( found )
4451
			continue;
4452
 
4453
		if ( !useId )
4454
			useId = data[0].ToInt();
4455
		if ( !useId )
4456
			useId = -1;
4457
 
4458
		CLEANSPLIT(data, size);
4459
 
4460
		RenameTextFile(sNode->str, useId, errors);
4461
	}
4462
}
4463
 
4464
/**
4465
 * Rename a text file
4466
 *
4467
 * Creates a new text file and copies an existing one
4468
 */
4469
bool CPackages::RenameTextFile(CyString textid, int languageid, CyStringList *errors)
4470
{
4471
	// lets check if the file already exists
4472
	CyString newFilename = SPK::FormatTextName(textid.ToInt(), m_iLanguage, (m_iGameFlags & EXEFLAG_TCTEXT));
4473
	C_File *addFile = FindFile(FILETYPE_TEXT, newFilename + ".xml");
4474
	if ( !addFile )
4475
		addFile = FindFile(FILETYPE_TEXT, newFilename + ".pck");
4476
 
4477
	// we have found the file, lets just add it to our scripts
4478
	if ( addFile )
4479
	{
4480
		AddTextFileToScripts(addFile, textid);
4481
		return true;
4482
	}
4483
 
4484
	// first we need to find our text file
4485
	CyString filename;
4486
	if ( languageid != -1 )
4487
		filename = SPK::FormatTextName(textid.ToInt(), languageid, (m_iGameFlags & EXEFLAG_TCTEXT));
4488
	else
4489
		filename = textid;
4490
 
4491
	C_File *textFile = FindFile(FILETYPE_TEXT, filename + ".xml");
4492
	if ( !textFile )
4493
	{
4494
		textFile = FindFile(FILETYPE_TEXT, filename + ".pck");
4495
		if ( !textFile )
4496
			return false;
4497
	}
4498
 
4499
	// now lets create out new text file
4500
	CFileIO readFile(textFile->GetFilePointer());
4501
	std::vector<CyString> *lines = readFile.ReadLines();
4502
 
4503
	// find the language id in the lines
4504
	std::vector<CyString> frontLines;
4505
	for(std::vector<CyString>::iterator it = lines->begin(); it != lines->end(); ++it)
4506
	{
4507
		CyString line = *it;
4508
		int pos = line.FindPos("<language id");
4509
		if ( pos != -1)
4510
		{
4511
			CyString newLine = "<language id=\"";
4512
			newLine += CyString::Number(m_iLanguage);
4513
			newLine += "\">";
4514
			newLine += line.GetToken(">", 2);
4515
 
4516
			frontLines.insert(frontLines.begin(), newLine);
4517
 
4518
			lines->erase(lines->begin(), ++it);
4519
			break;
4520
		}
4521
		frontLines.insert(frontLines.begin(), line);
4522
	}
4523
 
4524
	for(std::vector<CyString>::iterator it = frontLines.begin(); it != frontLines.end(); ++it)
4525
		lines->insert(lines->begin(), *it);
4526
 
4527
	addFile = new C_File(newFilename + ".xml");
4528
	addFile->SetFileType(FILETYPE_TEXT);
4529
 
4530
	CFileIO writeFile(m_sCurrentDir + "/" + addFile->GetNameDirectory(NULL));
4531
	if ( writeFile.WriteFile(lines) )
4532
	{
4533
		this->AddLogEntry(SPKINSTALL_WRITEFILE, addFile->GetNameDirectory(NULL), errors);
4534
 
4535
		addFile->SetFilename(m_sCurrentDir + "/" + addFile->GetNameDirectory(NULL));
4536
		// now we have the file wrriten, we need to add it to all scripts that need it
4537
		// first we add it to the global list
4538
		m_lFiles.push_back(addFile);
4539
 
4540
		// now add it to the scripts
4541
		AddTextFileToScripts(addFile, textid);
4542
	}
4543
	else
4544
	{
4545
		this->AddLogEntry(SPKINSTALL_WRITEFILE_FAIL, addFile->GetNameDirectory(NULL), errors);
4546
		if ( lines )
4547
			delete lines;
4548
		return false;
4549
	}
4550
 
4551
	if ( lines )
4552
		delete lines;
4553
 
4554
 
4555
	return true;
4556
}
4557
 
4558
/**
4559
 * Add file to scripts
4560
 *
4561
 * Adds a file to all scripts that need it
4562
 */
4563
void CPackages::AddTextFileToScripts(C_File *file, CyString textid)
4564
{
4565
	// now we need to find all scripts that have a matching file and add this to the list
4566
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
4567
	{
4568
		CBaseFile *package = node->Data();
4569
 
4570
		// first make sure it doesn't already exist
4571
		if ( package->GetFileList()->FindData(file) )
4572
			continue;
4573
 
4574
		bool found = false;
4575
		for ( CListNode<C_File> *fNode = package->GetFileList()->Front(); fNode; fNode = fNode->next() )
4576
		{
4577
			C_File *tFile = fNode->Data();
4578
			if ( tFile->GetFileType() != FILETYPE_TEXT )
4579
				continue;
4580
 
4581
			CyString id = tFile->GetBaseName().GetToken("-", 1, 1);
4582
			if ( id == textid )
4583
			{
4584
				found = true;
4585
				break;
4586
			}
4587
		}
4588
 
4589
		if ( found )
4590
			package->GetFileList()->push_back(file);
4591
	}
4592
}
4593
 
4594
bool CPackages::RemoveFile(C_File *file, CyStringList *errors)
4595
{
4596
	if ( !file )
4597
		return true;
4598
 
4599
	CyString remFileStr = file->GetFilePointer();
4600
	remFileStr.FindReplace(m_sCurrentDir, "");
4601
 
4602
	if ( file->GetFilePointer().IsIn("::") ) {
4603
		CFileIO CatFile(file->GetFilePointer().GetToken("::", 1, 1));
52 cycrow 4604
		if ( CatFile.exists() ) {
1 cycrow 4605
			CCatFile cat;
102 cycrow 4606
			if ( cat.Open(CatFile.fullFilename(), this->GetAddonDir(), CATREAD_DAT, false) == CATERR_NONE ) {
1 cycrow 4607
				CyString fileName = file->GetFilePointer().GetToken("::", 2, 2);
4608
				if ( cat.FindData(fileName) ) {
4609
					if ( cat.RemoveFile(fileName) ) {
4610
						this->AddLogEntry(SPKINSTALL_DELETEFILE, remFileStr, errors);
4611
					}
4612
					else {
4613
						this->AddLogEntry(SPKINSTALL_DELETEFILE_FAIL, remFileStr, errors);
4614
						return false;
4615
					}
4616
				}
4617
			}
4618
		}
4619
	}
4620
	else {
4621
		CFileIO f(file->GetFilePointer());
52 cycrow 4622
		if ( f.exists() )
1 cycrow 4623
		{
52 cycrow 4624
			if ( f.remove() ) this->AddLogEntry(SPKINSTALL_DELETEFILE, remFileStr, errors);
1 cycrow 4625
			else if ( errors )
4626
			{
4627
				this->AddLogEntry(SPKINSTALL_DELETEFILE_FAIL, remFileStr, errors);
4628
				return false;
4629
			}
4630
			else
4631
				return false;
4632
		}
4633
	}
4634
 
4635
	return true;
4636
}
4637
 
4638
int CPackages::RemoveAllPackages(CyStringList *errors, CProgressInfo *progress)
4639
{
4640
	int files = 0;
4641
 
4642
	// remove all files
93 cycrow 4643
	int max = m_lFiles.size() + _pOriginalFiles->count() + m_lUninstallFiles.size();
1 cycrow 4644
	for ( CListNode<C_File> *node = m_lFiles.Front(); node; node = node->next() )
4645
	{
4646
		// update the progress
4647
		if ( progress )
4648
			progress->UpdateProgress(files, max);
4649
		++files;
4650
 
4651
		RemoveFile(node->Data());
4652
		delete node->Data();
4653
	}
4654
	m_lFiles.clear();
4655
 
4656
	// restore any original files that are backed up
93 cycrow 4657
	//TODO: find a better way to do the progress
4658
	files = _pOriginalFiles->restoreAll(progress, files, max);
1 cycrow 4659
 
4660
	// remove any uninstall files that remain
4661
	for ( CListNode<C_File> *uNode = m_lUninstallFiles.Front(); uNode; uNode = uNode->next() )
4662
	{
4663
		// update the progress
4664
		if ( progress )
4665
			progress->UpdateProgress(files, max);
4666
		++files;
4667
 
4668
		RemoveFile(uNode->Data());
4669
		delete uNode->Data();
4670
	}
4671
	m_lUninstallFiles.clear();
4672
 
4673
	// delete all packages
4674
	for ( CListNode<CBaseFile> *pNode = m_lPackages.Front(); pNode; pNode = pNode->next() )
4675
	{
4676
		// clear file list as we have removed them already
4677
		pNode->Data()->GetFileList()->clear();
4678
		// delete the memory for the package
4679
		delete pNode->Data();
4680
	}
4681
	m_lPackages.clear();
4682
 
4683
	return files;
4684
}
4685
 
4686
/**
4687
 * Get Install Before Text
4688
 *
4689
 * Returns the install before text for the package in the correct language
4690
 */
4691
CyString CPackages::GetInstallBeforeText(CBaseFile *package)
4692
{
46 cycrow 4693
	return package->installText(m_iLanguage, true);
1 cycrow 4694
}
4695
CyString CPackages::GetInstallAfterText(CBaseFile *package)
4696
{
46 cycrow 4697
	return package->installText(m_iLanguage, false);
1 cycrow 4698
}
4699
CyString CPackages::GetUninstallBeforeText(CBaseFile *package)
4700
{
46 cycrow 4701
	return package->uninstallText(m_iLanguage, true);
1 cycrow 4702
}
4703
CyString CPackages::GetUninstallAfterText(CBaseFile *package)
4704
{
46 cycrow 4705
	return package->uninstallText(m_iLanguage, false);
1 cycrow 4706
}
4707
 
4708
int CPackages::GetChildPackages(CBaseFile *package, CLinkList<CBaseFile> *children, bool recursive)
4709
{
4710
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
4711
	{
4712
		CBaseFile *p = node->Data();
4713
		if ( p->GetParent() == package )
4714
		{
4715
			children->push_back(p);
4716
 
4717
			if ( recursive )
4718
				this->GetChildPackages(p, children, recursive);
4719
		}
4720
	}
4721
 
4722
	return children->size();
4723
}
4724
 
4725
void CPackages::AssignPackageNumbers()
4726
{
4727
	int num = 0;
4728
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
4729
		node->Data()->SetNum(num++);
4730
}
4731
 
4732
CyString CPackages::FindDataDir(CyString dir, CyString file)
4733
{
4734
	CDirIO Dir(dir);
4735
	// data files could be in 4 places depending on what program is used, check for all of these
4736
	if ( Dir.Exists(file) )
4737
		return Dir.File(file);
4738
	else if ( Dir.Exists(CyString("Data/") + file) )
4739
		return Dir.File(CyString("Data/") + file);
4740
	else if ( Dir.Exists(CyString("../") + file) )
4741
		return Dir.File(CyString("../") + file);
4742
	else if ( Dir.Exists(CyString("../Data/") + file) )
4743
		return Dir.File(CyString("../Data/") + file);
4744
 
4745
	return NullString;
4746
}
4747
 
4748
void CPackages::Startup(CyString dir, CyString tempDir, CyString myDoc, CyString mod)
4749
{
4750
	this->SetTempDirectory(tempDir);
4751
	this->SetMyDocuments(myDoc);
4752
 
4753
	m_sSetMod = mod;
4754
 
4755
	// need to read the game exe versions
4756
	m_gameExe.Reset();
4757
 
4758
	CyString exeFile = this->FindDataDir(dir, "exe");
4759
 
4760
	// if file exists, read it, otherwise, just add
52 cycrow 4761
	if ( !exeFile.Empty() && CFileIO(exeFile).ExistsOld() )
56 cycrow 4762
		m_gameExe.ReadFile(exeFile.ToString());
1 cycrow 4763
	else
4764
	{
56 cycrow 4765
		m_gameExe.ParseExe("x2.exe|0:5:NOSAVESUBDIR:HKCU/Software/EgoSoftware/X2/ModName:X2 The Threat:!GAMEDIR!:2:1604608!2150400:1.4 Artifical Life:1974272:1.5 Uplink");
4766
		m_gameExe.ParseExe("x3.exe|30:5:0:HKCU/Software/Egosoft/X3/ModName:X3 Reunion:Egosoft/X3:2:2347008:2.0 Bala Gi:2367488!2375680:2.5 Uplink");
4767
		m_gameExe.ParseExe("x3tc.exe|35:5:NO_XOR|TC_TEXT|MYDOCLOG:HKCU/Software/Egosoft/X3TC/ModName:X3 Terran Conflict:Egosoft/X3TC:3:1933464!1933520:2.0 Aldrin Expansion:-1:2.5 A New Home (Superbox):-1:3.0 Balance of Power");
76 cycrow 4768
		m_gameExe.ParseExe("x3ap.exe|38:2:NO_XOR|TC_TEXT|MYDOCLOG|ADDON:HKCU/Software/Egosoft/X3AP/ModName:X3 Albion Prelude:Egosoft/X3AP:addon!x3tc.exe:3:-1:2.0 The War Continues:-1:2.5 Operation Loose Ends:-1:3.0 Shady Business");
1 cycrow 4769
	}
4770
}
4771
 
4772
int CPackages::GetGameLanguage(CyString dir)
4773
{
4774
	if ( dir.Empty() )
4775
		dir = m_sCurrentDir;
4776
 
4777
	CDirIO Dir(dir);
4778
 
4779
	// check for lang.dat file
4780
	if ( Dir.Exists("lang.dat") )
4781
	{
4782
		CFileIO File(Dir.File("lang.dat"));
4783
 
4784
		size_t size;
4785
		char *data = File.ReadToData(&size);
4786
 
4787
		if ( data )
4788
		{
4789
			CyString str(data);
4790
			return str.GetToken("\n", 1, 1).GetToken(" ", 1, 1).ToInt();
4791
		}
4792
	}
4793
 
4794
	return 0;
4795
}
4796
CyString CPackages::GetGameRunExe(CyString dir)
4797
{
56 cycrow 4798
	return m_gameExe.GetGameRunExe((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString());
1 cycrow 4799
}
4800
 
4801
CyString CPackages::GetGameNameFromType(int game)
4802
{
4803
	return m_gameExe.GetGameNameFromType(game - 1);
4804
}
4805
CyString CPackages::GetGameName(CyString dir)
4806
{
56 cycrow 4807
	return m_gameExe.GetGameName((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString());
1 cycrow 4808
}
4809
CyString CPackages::GetProperDir(CyString dir)
4810
{
56 cycrow 4811
	return m_gameExe.GetProperDir((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString());
1 cycrow 4812
}
4813
CyString CPackages::GetAddonDir(CyString dir)
4814
{
56 cycrow 4815
	return m_gameExe.GetAddonDir((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString());
1 cycrow 4816
}
4817
int CPackages::GetGameAddons(CyStringList &exes, CyString dir)
4818
{
56 cycrow 4819
	return m_gameExe.GetGameAddons((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString(), exes);
1 cycrow 4820
}
4821
 
4822
CyString CPackages::GetGameTypesString(CBaseFile *package, bool includeVersion)
4823
{
4824
	if ( !package->AnyGameCompatability() )
4825
		return NullString;
4826
 
98 cycrow 4827
	Utils::String sGames;
1 cycrow 4828
	for ( CListNode<SGameCompat> *gNode = package->GetGameCompatabilityList()->Front(); gNode; gNode = gNode->next() ) {
98 cycrow 4829
		if ( !sGames.empty() )
1 cycrow 4830
			sGames += ", ";
4831
		sGames += m_gameExe.GetGameNameFromType(gNode->Data()->iGame - 1);
4832
		if ( includeVersion ) {
98 cycrow 4833
			Utils::String version = m_gameExe.GetGameVersionFromType(gNode->Data()->iGame - 1, gNode->Data()->iVersion - 1, gNode->Data()->sVersion);
4834
			if ( !version.empty() ) {
4835
				sGames += " (";
4836
				sGames += version;
4837
				sGames += ")";
4838
			}
1 cycrow 4839
		}
4840
	}
4841
	return sGames;
4842
}
4843
 
4844
CyString CPackages::GetGameVersionString(CBaseFile *package)
4845
{
4846
	for ( CListNode<SGameCompat> *gNode = package->GetGameCompatabilityList()->Front(); gNode; gNode = gNode->next() ) {
4847
		if ( gNode->Data()->iGame == m_iGame ) {
4848
			return m_gameExe.GetGameVersionFromType(m_iGame - 1, gNode->Data()->iVersion - 1, gNode->Data()->sVersion);
4849
		}
4850
	}
4851
 
4852
	return NullString;
4853
}
4854
 
4855
CyString CPackages::GetGameVersionFromType(int game, int version, CyString sVersion)
4856
{
56 cycrow 4857
	return m_gameExe.GetGameVersionFromType(game - 1, version - 1, sVersion.ToString());
1 cycrow 4858
}
4859
 
4860
int CPackages::CountBuiltInPackages(bool onlyEnabled)
4861
{
4862
	int count = 0;
4863
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
4864
	{
4865
		if ( !node->Data()->CheckGameCompatability(m_iGame) )
4866
			continue;
4867
		if ( onlyEnabled && !node->Data()->IsEnabled() )
4868
			continue;
50 cycrow 4869
		if ( node->Data()->author().Compare("PluginManager") )
1 cycrow 4870
			++count;
4871
	}
4872
 
4873
	return count;
4874
}
4875
 
4876
int CPackages::CountPackages(int type, bool onlyEnabled)
4877
{
4878
	int count = 0;
4879
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
4880
	{
4881
		CBaseFile *p = node->Data();
4882
 
4883
		if ( (type != TYPE_BASE) && (p->GetType() != type) )
4884
			continue;
4885
 
4886
		if ( (onlyEnabled) && (!p->IsEnabled()) )
4887
			continue;
4888
 
4889
		++count;
4890
	}
4891
 
4892
	return count;
4893
}
4894
 
4895
int CPackages::ExtractGameFile(CyString aFilename, CyString aTo, CyString dir, CyString addon)
4896
{
4897
	// first check the enabled mod
4898
	if ( dir.Empty() )
4899
		dir = m_sCurrentDir;
4900
 
4901
	CyString addonDir = addon;
4902
	if ( addonDir.Empty() ) addonDir = this->GetAddonDir(dir);
4903
 
4904
	if ( m_pEnabledMod && m_pEnabledMod->AnyFileType(FILETYPE_MOD) )
4905
	{
4906
		for ( C_File *file = m_pEnabledMod->GetFirstFile(FILETYPE_MOD); file; file = m_pEnabledMod->GetNextFile(file) )
4907
		{
4908
			if ( !file->CheckFileExt("cat") )
4909
				continue;
4910
 
4911
			CCatFile catFile;
4912
			if ( catFile.Open(file->GetFilePointer(), addonDir, CATREAD_CATDECRYPT, false) == CATERR_NONE )
4913
			{
4914
				if ( catFile.ExtractFile(aFilename, aTo) )
4915
					return 1;
4916
				if ( catFile.Error() == CATERR_INVALIDDEST || catFile.Error() == CATERR_CANTCREATEDIR )
4917
				{
4918
					if ( catFile.ExtractFile(aFilename) )
4919
						return -1;
4920
				}
4921
 
4922
			}
4923
		}
4924
	}
4925
	else if ( !m_sSetMod.Empty() )
4926
	{
52 cycrow 4927
		if ( CFileIO(m_sCurrentDir + "/mods/" + m_sSetMod + ".cat").ExistsOld() )
1 cycrow 4928
		{
4929
			CCatFile catFile;
4930
			if ( catFile.Open(m_sCurrentDir + "/mods/" + m_sSetMod + ".cat", addonDir, CATREAD_CATDECRYPT, false) == CATERR_NONE )
4931
			{
4932
				if ( catFile.ExtractFile(aFilename, aTo) )
4933
					return 1;
4934
				if ( catFile.Error() == CATERR_INVALIDDEST || catFile.Error() == CATERR_CANTCREATEDIR )
4935
				{
4936
					if ( catFile.ExtractFile(aFilename) )
4937
						return -1;
4938
				}
4939
			}
4940
		}
4941
	}
4942
 
4943
	// find the highest cat number
4944
	int catNumber = 1;
52 cycrow 4945
	while ( CFileIO(dir + "/" + CyString::Number(catNumber).PadNumber(2) + ".cat").ExistsOld() && catNumber < 99 )
1 cycrow 4946
		++catNumber;
4947
 
4948
	// get the last one, not the next free one
4949
	--catNumber;
4950
 
4951
	// work backwards until we find the file
4952
	for ( ; catNumber; catNumber-- )
4953
	{
4954
		CCatFile catFile;
4955
		if ( catFile.Open(dir + "/" + CyString::Number(catNumber).PadNumber(2) + ".cat", addonDir, CATREAD_CATDECRYPT, false) == CATERR_NONE )
4956
		{
4957
			// check for the file
4958
			if ( catFile.ExtractFile(aFilename, aTo) )
4959
				return 1;
4960
			if ( catFile.Error() == CATERR_INVALIDDEST || catFile.Error() == CATERR_CANTCREATEDIR )
4961
			{
4962
				if ( catFile.ExtractFile(aFilename) )
4963
					return -1;
4964
			}
4965
		}
4966
	}
4967
 
4968
	return 0;
4969
}
4970
 
4971
void CPackages::CreateWareFiles()
4972
{
4973
	// do each ware
4974
	int wareTextID = WARETEXTSTART;
4975
	for ( int i = 0; i < WAREBUFFERS; i++ )
4976
	{
4977
		// its empty, no need to create ware files
4978
		if ( !m_lGameWares[i].size() )
4979
			continue;
4980
 
4981
		// lets extract the ware file
4982
		char wareType = CPackages::ConvertWareTypeBack(i);
4983
		CyString wareFile = "TWare";
4984
		wareFile += (char)UPPER(wareType);
4985
 
4986
		CyString openFile;
4987
 
4988
		int e;
52 cycrow 4989
		if ( i == WARES_TECH && CFileIO(m_sTempDir + "/TWareT.txt").ExistsOld() )
1 cycrow 4990
			openFile = m_sTempDir + "/TWareT.txt";
4991
		else {
4992
			e = ExtractGameFile(CyString("types/") + wareFile + ".pck", m_sTempDir + "/" + wareFile + ".txt");
4993
			if ( e == 1 )
4994
				openFile = m_sTempDir + "/" + wareFile + ".txt";
4995
			else if ( e == -2 )
4996
				openFile = wareFile + ".txt";
4997
		}
4998
 
4999
		if ( !openFile.Empty() )
5000
		{
5001
			// read the file into memory
5002
			CyStringList wareLines;
5003
			int oldSize = -1;
5004
			int version = -1;
5005
 
5006
			// read first number
5007
			CFileIO readFile(m_sTempDir + "/" + wareFile + ".txt");
5008
			CyStringList *lines = readFile.ReadLinesStr();
5009
			if ( lines )
5010
			{
5011
				for ( SStringList *str = lines->Head(); str; str = str->next )
5012
				{
5013
					CyString line(str->str);
5014
					line.RemoveFirstSpace();
5015
					line.RemoveChar(9);
5016
					line.RemoveChar('\r');
5017
					if ( line.Empty() )
5018
						continue;
5019
					if ( line[0] == '/' )
5020
						continue;
5021
 
5022
					if ( oldSize == -1 )
5023
					{
5024
						version = line.GetToken(";", 1, 1).ToInt();
5025
						oldSize = line.GetToken(";", 2, 2).ToInt();
5026
					}
5027
					else
5028
					{
5029
						line.RemoveEndSpace();
5030
						if ( line.Right(1) != ';' )
5031
							line += ";";
5032
						wareLines.PushBack(line);
5033
						if ( wareLines.Count() >= oldSize )
5034
							break;
5035
					}
5036
				}
5037
 
5038
				delete lines;
5039
 
5040
				// apply the buffer
5041
				if ( m_iWareBuffer[i] <= 0 )
5042
					m_iWareBuffer[i] = wareLines.Count() + 10;
5043
				// last resort, readjust the buffer
5044
				else if ( wareLines.Count() > m_iWareBuffer[i] )
5045
					m_iWareBuffer[i] = wareLines.Count();
5046
 
5047
				// add the buffers
5048
				while ( wareLines.Count() < m_iWareBuffer[i] )
5049
					wareLines.PushBack("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;SS_WARE_FILLER;");
5050
 
5051
				// add the ware lines
5052
				bool create = false;
5053
				for ( CListNode<SGameWare> *node = m_lGameWares[i].Front(); node; node = node->next() )
5054
				{
5055
					SGameWare *w = node->Data();
5056
 
5057
					if ( w->iType == WARETYPE_NONE )
5058
						continue;
5059
					else if ( w->iType == WARETYPE_DISABLED )
5060
					{
5061
						create = true;
5062
						wareLines.PushBack(CyString("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;") + w->sWareName + "_DISABLED;");
5063
					}
5064
					else if ( w->iType == WARETYPE_DELETED || !w->pWare )
5065
					{
5066
						create = true;
5067
						wareLines.PushBack("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;SS_WARE_DELETED;");
5068
					}
5069
					else if ( w->iType == WARETYPE_ADDED )
5070
					{
5071
						create = true;
5072
						w->pWare->iDescID = wareTextID;
5073
						w->iText = wareTextID;
5074
						wareTextID += 10;
5075
						w->iPos = wareLines.Count();
88 cycrow 5076
						long price = this->customWareOveridePrice(w->pWare->sID);
5077
						int notority = w->pWare->iNotority;
5078
						if ( !this->customWareOverideNoto(w->pWare->sID, &notority) ) notority = w->pWare->iNotority;
5079
						if ( !price ) price = w->pWare->iPrice;
5080
 
5081
						wareLines.PushBack(CyString("28;0;0;0;0;") + (long)wareLines.Count() + ";" + (long)(w->iText + 3) + ";" + (long)w->pWare->iVolumn + ";" + price + ";1;1;" + (long)w->pWare->iSize + ";" + price + ";" + (long)notority + ";0;0;" + w->sWareName.ToUpper() + ";");
1 cycrow 5082
					}
5083
				}
5084
 
5085
				if ( create )
5086
				{
5087
					wareLines.PushFront(CyString::Number(version) + ";" + CyString::Number(wareLines.Count()) + ";", NullString);
5088
					CyString strV;
5089
					strV.FromFloat(GetLibraryVersion(), 2);
5090
					wareLines.PushFront(CyString("// Created by SPKInstaller Libraries V") + strV, NullString);
5091
					if ( readFile.WriteFile(&wareLines) )
5092
						this->PackFile(&readFile, CyString("types\\") + wareFile + ".pck");
5093
				}
5094
			}
52 cycrow 5095
			readFile.remove();
1 cycrow 5096
		}
5097
	}
5098
}
5099
 
88 cycrow 5100
Utils::String CPackages::empWaresForGame(int *maxsize)
1 cycrow 5101
{
88 cycrow 5102
	if ( maxsize ) (*maxsize) = 0;
1 cycrow 5103
 
5104
	if ( m_iGame == GAME_X3TC )
5105
	{
88 cycrow 5106
		if ( maxsize ) (*maxsize) = EMP_X3TC;
5107
		return GetX3TCEmp();
1 cycrow 5108
	}
5109
	else if ( m_iGame == GAME_X3AP )
5110
	{
88 cycrow 5111
		if ( maxsize ) (*maxsize) = EMP_X3AP;
5112
		return GetX3TCEmp();
1 cycrow 5113
	}
5114
	else if ( m_iGame == GAME_X3 )
5115
	{
88 cycrow 5116
		if ( maxsize ) (*maxsize) = EMP_X3;
5117
		return GetX3Emp();
1 cycrow 5118
	}
5119
 
88 cycrow 5120
	return Utils::String::Null();
5121
}
5122
 
5123
void CPackages::_addWareOverride(enum WareTypes type, int pos, const Utils::String &id, int value, bool noto)
5124
{
5125
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
5126
		SWarePriceOverride *wp = node->Data();
5127
		if ( wp->type == type ) {
5128
			if ( wp->type == Ware_Custom && !wp->id.Compare(id) ) continue;
5129
			else if ( wp->type != Ware_Custom && wp->pos != pos ) continue;
5130
			if ( noto ) {
5131
				wp->notority  = value;
89 cycrow 5132
				wp->bNotority = true;
88 cycrow 5133
			}
5134
			else wp->relval = value;
5135
			return;
5136
		}
5137
	}
5138
 
5139
	SWarePriceOverride *ware = new SWarePriceOverride;
5140
	ware->bNotority = noto;
5141
	ware->notority = (noto) ? value : 0;
5142
	ware->relval = (noto) ? 0 : value;
5143
	ware->type = type;
5144
	ware->pos = pos;
5145
	ware->id = id;
5146
 
5147
	m_lWarePrices.push_back(ware);
5148
}
5149
 
5150
void CPackages::addEMPPriceOverride(int empId, int price)
5151
{
5152
	_addWareOverride(Ware_EMP, empId, Utils::String::Null(), price, false);
5153
}
5154
 
5155
void CPackages::addEMPNotoOverride(int empId, int noto)
5156
{
5157
	_addWareOverride(Ware_EMP, empId, Utils::String::Null(), noto, true);
5158
}
5159
 
5160
void CPackages::addBuiltInWarePriceOverride(int empId, int price)
5161
{
5162
	_addWareOverride(Ware_BuiltIn, empId, Utils::String::Null(), price, false);
5163
}
5164
 
5165
void CPackages::addBuiltInWareNotoOverride(int empId, int noto)
5166
{
5167
	_addWareOverride(Ware_BuiltIn, empId, Utils::String::Null(), noto, false);
5168
}
5169
 
5170
void CPackages::addCustomWarePriceOverride(const Utils::String &id, int price)
5171
{
5172
	_addWareOverride(Ware_Custom, 0, id, price, false);
5173
}
5174
 
5175
void CPackages::addCustomWareNotoOverride(const Utils::String &id, int noto)
5176
{
5177
	_addWareOverride(Ware_Custom, 0, id, noto, true);
5178
}
5179
 
5180
 
5181
void CPackages::CreateEMPFile(CyString progDir)
5182
{
5183
	// do emp wares
5184
	int maxsize = 0;
5185
	Utils::String empWares = empWaresForGame(&maxsize);
5186
 
1 cycrow 5187
	if ( maxsize )
5188
	{
5189
		int e = ExtractGameFile("types/TWareT.pck", m_sTempDir + "/TWareT.txt");
5190
		if ( e )
5191
		{
5192
			// read the file into memory
5193
			CyStringList wareLines;
5194
			int oldSize = -1;
5195
			int version = -1;
5196
 
5197
			// read first number
5198
			CFileIO readFile((e == -1) ? "TWareT.txt" : m_sTempDir + "/TWareT.txt");
88 cycrow 5199
			std::vector<Utils::String> *lines = readFile.readLines();
1 cycrow 5200
			if ( lines )
5201
			{
5202
				for ( int i = 0; i < (int)lines->size(); i++ )
5203
				{
88 cycrow 5204
					Utils::String line(lines->at(i));
5205
					line.removeFirstSpace();
5206
					line.removeChar('\r');
5207
					line.removeChar(9);
1 cycrow 5208
					if ( line[0] == '/' )
5209
						continue;
5210
 
5211
					if ( oldSize == -1 )
5212
					{
88 cycrow 5213
						version = line.token(";", 1).toLong();
5214
						oldSize = line.token(";", 2).toLong();
1 cycrow 5215
					}
5216
					else
5217
					{
88 cycrow 5218
						line.removeEndSpace();
5219
						if ( line.right(1) != ";" )
1 cycrow 5220
							line += ";";
88 cycrow 5221
 
5222
						// check for any override values for built in wares
5223
						if ( (i >= 62 && i <= 81) || (i >= 88 && i <= 93) ) {
5224
							int pos = i - ((i >= 88) ? 88 : 62);
5225
							int price = this->builtInWareOveridePrice(pos);
5226
							if ( price ) {
5227
								line = line.replaceToken(";", 9, Utils::String::Number(price));
5228
								line = line.replaceToken(";", 13, Utils::String::Number(price));
5229
							}
5230
 
5231
							int noto = 0;
5232
							if ( this->builtInWareOverideNoto(pos, &noto) ) {
5233
								line = line.replaceToken(";", 14, Utils::String::Number(noto));
5234
							}
5235
						}
5236
 
5237
						// check for any override values for EMP
5238
						if ( i >= 116 ) {
5239
							int price = this->empOveridePrice(i - 116);
5240
							if ( price ) {
5241
								line = line.replaceToken(";", 9, Utils::String::Number(price));
5242
								line = line.replaceToken(";", 13, Utils::String::Number(price));
5243
							}
5244
 
5245
							int noto = 0;
5246
							if ( this->empOverideNoto(i - 116, &noto) ) {
5247
								line = line.replaceToken(";", 14, Utils::String::Number(noto));
5248
							}
5249
						}
5250
 
5251
						wareLines.PushBack(CyString(line));
1 cycrow 5252
						if ( wareLines.Count() >= oldSize )
5253
							break;
5254
					}
5255
				}
5256
 
5257
				delete lines;
5258
			}
5259
 
5260
			// now we too add/remove entries to match
5261
			// need filler entries
5262
			while ( wareLines.Count() < maxsize )
5263
				wareLines.PushBack("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;SS_WARE_FILLER;");
5264
 
5265
			int empEntries = 0;
88 cycrow 5266
			Utils::String *empStr = empWares.tokenise("\n", &empEntries);
1 cycrow 5267
 
5268
			if ( empEntries && empStr )
5269
			{
88 cycrow 5270
				// apply any price overrides
5271
				for(int i = 0; i < empEntries; i++) {
5272
					int price = this->empOveridePrice(i);
5273
					if ( price ) {
5274
						empStr[i] = empStr[i].replaceToken(";", 9, Utils::String::Number(price));
5275
						empStr[i] = empStr[i].replaceToken(";", 13, Utils::String::Number(price));
5276
					}
5277
 
5278
					int noto = 0;
5279
					if ( this->empOverideNoto(i, &noto) ) {
5280
						empStr[i] = empStr[i].replaceToken(";", 14, Utils::String::Number(noto));
5281
					}
5282
				}
1 cycrow 5283
				// remove any empty end entries
88 cycrow 5284
				while ( empStr[empEntries - 1].empty() )
1 cycrow 5285
					--empEntries;
5286
 
5287
				CyStringList addAfter;
5288
				if ( wareLines.Count() > maxsize )
5289
				{
5290
					// force emp, remove entries to allow them to be added
5291
					if ( m_bForceEMP )
5292
					{
5293
						// more after emp
5294
						if ( wareLines.Count() > (maxsize + empEntries) )
5295
						{
5296
							SStringList *node = wareLines.GetAt(maxsize + empEntries);
5297
							while ( node )
5298
							{
5299
								addAfter.PushBack(node->str);
5300
								node = node->next;
5301
							}
5302
						}
5303
 
5304
						// no remove them all
5305
						wareLines.DeleteFrom(maxsize);
5306
					}
5307
					else if ( m_iGame == GAME_X3TC || m_iGame == GAME_X3AP ) // check if old emp is included, and convert it
5308
					{
5309
						if ( wareLines.Count() > 128 )
5310
						{
5311
							CyString test = wareLines.GetAt(128)->str;
5312
							if ( test.GetToken(";", -2).Compare("SS_WARE_SW_CUSTOM16_1;") )
5313
							{
5314
								// if theres any at the end, remove the last emp entry
5315
								if ( wareLines.Count() > (maxsize + empEntries - 1) )
5316
								{
5317
									SStringList *node = wareLines.GetAt(maxsize + empEntries - 2);
5318
									if ( node )
5319
										node->remove = true;
5320
								}
5321
								wareLines.Insert(128, "0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;128;");
5322
								wareLines.RemoveMarked();
5323
							}
5324
						}
5325
					}
5326
				}
5327
 
5328
				// too many entries, need to remove the first set of EMP wares
5329
				int i = 0;
5330
				if ( wareLines.Count() > maxsize )
5331
					i = wareLines.Count() - maxsize;
5332
 
5333
				for ( ; i < empEntries; i++ )
5334
				{
5335
					CyString str = empStr[i];
5336
					str.RemoveEndSpace();
5337
					str.RemoveChar(9);
5338
					str.RemoveChar('\r');
5339
					if ( str.Empty() )
5340
						continue;
5341
					if ( str.Right(1) != ";" )
5342
						str += ";";
5343
					wareLines.PushBack(str);
5344
				}
5345
 
5346
				for ( SStringList *afterNode = addAfter.Head(); afterNode; afterNode = afterNode->next )
5347
					wareLines.PushBack(afterNode->str);
5348
 
5349
				// finally we write the whole file
5350
				wareLines.PushFront(CyString::Number(version) + ";" + CyString::Number(wareLines.Count()) + ";", NullString);
5351
				CyString strV;
5352
				strV.FromFloat(GetLibraryVersion(), 2);
5353
				wareLines.PushFront(CyString("// Created by SPKInstaller Libraries V") + strV, NullString);
5354
				if ( readFile.WriteFile(&wareLines) )
5355
					this->PackFile(&readFile, "types\\TWareT.pck");
5356
			}
5357
			CLEANSPLIT(empStr, empEntries);
5358
		}
5359
	}
5360
}
5361
 
84 cycrow 5362
Utils::String parseXmlText(const Utils::String &str)
17 cycrow 5363
{
84 cycrow 5364
	Utils::String newStr(str);
17 cycrow 5365
	CyStringList changes;
5366
 
5367
	// find all XML commands, &<command>;
84 cycrow 5368
	Utils::String sStr = str;
5369
	Utils::String::size_type pos = sStr.find_first_of("&", 0);
5370
	while ( pos != Utils::String::npos ) {
17 cycrow 5371
		// find the next space and next ;.  If ; comes first, assume its acommand
84 cycrow 5372
		Utils::String::size_type spacePos = sStr.find_first_of(" ", pos);
5373
		Utils::String::size_type colonPos = sStr.find_first_of(";", pos);
5374
		if ( colonPos != Utils::String::npos && colonPos < spacePos ) {
17 cycrow 5375
			// replace with <::command::> so they the & doesn't get replaced
84 cycrow 5376
			Utils::String repStr = sStr.substr(pos, (colonPos + 1) - pos);
5377
			Utils::String repWithStr = "<::" + sStr.substr(pos + 1, colonPos - pos - 1) + "::>";
5378
			newStr = newStr.findReplace(repStr, repWithStr);
5379
			changes.PushBack(CyString(repStr), CyString(repWithStr));
17 cycrow 5380
		}
5381
 
5382
		// find the next command
5383
		pos = sStr.find_first_of("&", pos + 1);
5384
	}
5385
 
5386
	// replace the & now
84 cycrow 5387
	newStr = newStr.findReplace("&", "&amp;");
17 cycrow 5388
 
5389
	// restore the commands
5390
	for ( SStringList *strNode = changes.Head(); strNode; strNode = strNode->next ) {
84 cycrow 5391
		newStr = newStr.findReplace(strNode->data.ToString(), strNode->str.ToString());
17 cycrow 5392
	}
5393
 
5394
	return newStr;
5395
}
5396
 
84 cycrow 5397
Utils::String CPackages::ConvertTextString(const Utils::String &sText)
1 cycrow 5398
{
17 cycrow 5399
	//process any &
84 cycrow 5400
	Utils::String text = parseXmlText(sText);
17 cycrow 5401
 
5402
	// change special cases
84 cycrow 5403
	text = text.findReplace("(", "\\(");
5404
	text = text.findReplace(")", "\\)");
5405
	text = text.findReplace("[", "{");
5406
	text = text.findReplace("]", "}");
5407
	text = text.findReplace(">", "&gt;");
5408
	text = text.findReplace("<", "&lt;");
1 cycrow 5409
	return text;
5410
}
5411
 
56 cycrow 5412
int CPackages::_gameTextNumber() const
5413
{
5414
	int gameNumber = (m_pCurrentGameExe) ? m_pCurrentGameExe->iTextNum : -1;
5415
	if ( gameNumber != -1 ) return gameNumber;
5416
 
5417
	switch(m_iGame) {
5418
		case GAME_X3: return 30;
5419
		case GAME_X3TC: return 35;
5420
		case GAME_X3AP: return 38;
5421
		default: return 0;
5422
	}
5423
}
5424
 
87 cycrow 5425
void CPackages::createPluginManagerOpenText()
5426
{
5427
	int gameNumber = _gameTextNumber();
5428
 
5429
	int lang = m_iLanguage;
5430
	if ( !lang || lang < 0 )
5431
		lang = 44;
5432
 
5433
	CDirIO Dir(m_sCurrentDir);
5434
	if ( !Dir.Exists("t") )
5435
		Dir.Create("t");
5436
 
5437
	CyString filename = SPK::FormatTextName(PMTEXTFILE, lang, (m_iGameFlags & EXEFLAG_TCTEXT));
5438
	CFileIO textFile(m_sCurrentDir + "/t/" + filename + ".xml");
5439
 
5440
	std::vector<CyString> writeData;
5441
 
5442
	writeData.push_back(CyString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"));
5443
	writeData.push_back(CyString("<language id=\"") + CyString::Number(lang) + "\">");
5444
 
5445
	if ( !gameNumber )
5446
		writeData.push_back(CyString("	<page id=\"") + CyString::Number(PMTEXTFILE) + "\" title=\"Plugin Manager Text File\" descr=\"Contains text used for the plugin manager, packages, settings, wares, ship, etc\">");
5447
	else
5448
		writeData.push_back(CyString("	<page id=\"") + (long)gameNumber + CyString::Number(PMTEXTFILE).PadNumber(4) + "\" title=\"Plugin Manager Text File\" descr=\"Contains text used for the plugin manager, packages, settings, wares, ship, etc\">");
5449
 
5450
	writeData.push_back(CyString("		<t id=\"99998\">[author]Plugin Manager[/author]It appears the plugin manager hasn't been closed properly.  Make sure its closed before running the game otherwise things may not work correctly</t>"));
5451
	writeData.push_back(CyString("		<t id=\"99999\">2</t>"));
5452
 
5453
	writeData.push_back(CyString("	</page>"));
5454
 
5455
	writeData.push_back(CyString("</language>"));
5456
	textFile.WriteFileUTF(&writeData);
5457
 
5458
	size_t fileSize;
102 cycrow 5459
	char *fileData = CFileIO(textFile.fullFilename()).ReadToData(&fileSize);
87 cycrow 5460
 
5461
	if ( fileData && fileSize)
5462
	{
5463
		size_t newFileSize;
5464
		unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
5465
		if ( pckData )
5466
		{
5467
			CFileIO pckFile(m_sCurrentDir + "/t/" + filename + ".pck");
5468
			pckFile.WriteData((char *)pckData, newFileSize);
102 cycrow 5469
			this->AddCreatedFile(pckFile.fullFilename());
87 cycrow 5470
		}
5471
	}
5472
	textFile.remove();
5473
}
5474
 
1 cycrow 5475
void CPackages::CreatePluginManagerText()
5476
{
56 cycrow 5477
	int gameNumber = _gameTextNumber();
1 cycrow 5478
 
5479
	int lang = m_iLanguage;
5480
	if ( !lang || lang < 0 )
5481
		lang = 44;
5482
 
5483
	CDirIO Dir(m_sCurrentDir);
5484
	if ( !Dir.Exists("t") )
5485
		Dir.Create("t");
5486
 
5487
	m_iLastUpdated = (int)time(NULL);
5488
 
5489
	CyString filename = SPK::FormatTextName(PMTEXTFILE, lang, (m_iGameFlags & EXEFLAG_TCTEXT));
5490
	CFileIO textFile(m_sCurrentDir + "/t/" + filename + ".xml");
5491
 
5492
	std::vector<CyString> writeData;
5493
 
5494
	CLinkList<SGameWare> lWares;
5495
	CLinkList<SGameShip> lShips;
5496
	for ( int i = 0; i < WAREBUFFERS; i++ )
5497
	{
5498
		for ( CListNode<SGameWare> *node = m_lGameWares[i].Front(); node; node = node->next() )
5499
		{
5500
			SGameWare *w = node->Data();
5501
			if ( w->iType == WARETYPE_NONE )
5502
				continue;
5503
			lWares.push_back(w);
5504
		}
5505
	}
5506
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
5507
	{
5508
		if ( node->Data()->iType == WARETYPE_NONE )
5509
			continue;
5510
		lShips.push_back(node->Data());
5511
	}
5512
 
5513
	writeData.push_back(CyString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"));
5514
	writeData.push_back(CyString("<language id=\"") + CyString::Number(lang) + "\">");
5515
 
5516
	if ( !gameNumber )
5517
		writeData.push_back(CyString("	<page id=\"") + CyString::Number(PMTEXTFILE) + "\" title=\"Plugin Manager Text File\" descr=\"Contains text used for the plugin manager, packages, settings, wares, ship, etc\">");
5518
	else
5519
		writeData.push_back(CyString("	<page id=\"") + (long)gameNumber + CyString::Number(PMTEXTFILE).PadNumber(4) + "\" title=\"Plugin Manager Text File\" descr=\"Contains text used for the plugin manager, packages, settings, wares, ship, etc\">");
5520
 
5521
	// write the heading
5522
	int start = 10000;
5523
	writeData.push_back(CyString("		<t id=\"1\">") + CyString::Number(m_iLastUpdated) + "</t>");
5524
	writeData.push_back(CyString("		<t id=\"2\">") + CyString::Number(this->CountPackages(TYPE_SPK, true)) + "</t>");
5525
	writeData.push_back(CyString("		<t id=\"3\">") + CyString::Number(start) + "</t>");
5526
	writeData.push_back(CyString("		<t id=\"4\">") + CyString::Number(lWares.size()) + "</t>");
5527
	writeData.push_back(CyString("		<t id=\"6\">") + CyString::Number(lShips.size()) + "</t>");
5528
 
5529
	// write some generic texts
5530
	writeData.push_back(CyString("		<t id=\"110\">") + (long)m_iLanguage + "</t>");
5531
	writeData.push_back(CyString("		<t id=\"109\">Plugin Manager: \\033GPoll Gui Data\\033X</t>"));
5532
	writeData.push_back(CyString("		<t id=\"107\">Plugin Manager: \\033GExport Game Data\\033X </t>"));
5533
	writeData.push_back(CyString("		<t id=\"100\">\\n</t>"));
5534
	writeData.push_back(CyString("		<t id=\"101\">\\033B</t>"));
5535
	writeData.push_back(CyString("		<t id=\"102\">\\033G</t>"));
5536
	writeData.push_back(CyString("		<t id=\"103\">\\033B</t>"));
5537
	writeData.push_back(CyString("		<t id=\"104\">\\033X</t>"));
5538
	writeData.push_back(CyString("		<t id=\"105\">\\033Y</t>"));
5539
	writeData.push_back(CyString("		<t id=\"106\">\\033C</t>"));
5540
	writeData.push_back(CyString("		<t id=\"108\">\\033</t>"));
87 cycrow 5541
 
5542
	writeData.push_back(CyString("		<t id=\"99998\">[author]Plugin Manager[/author]It appears the plugin manager hasn't been closed properly.  Make sure its closed before running the game otherwise things may not work correctly</t>"));
5543
	writeData.push_back(CyString("		<t id=\"99999\">1</t>"));
1 cycrow 5544
	// now write each package
5545
	int settingStart = 100000;
5546
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
5547
	{
5548
		CBaseFile *p = node->Data();
5549
		if ( !p->IsEnabled() )
5550
			continue;
5551
 
5552
		if ( p->GetType() != TYPE_SPK )
5553
			continue;
5554
 
5555
		CSpkFile *spk = (CSpkFile *)p;
5556
 
5557
		// count text files
5558
		CyString textEntries;
5559
		int textCount = 0;
5560
		C_File *f = p->GetFirstFile(FILETYPE_TEXT);
5561
		while ( f )
5562
		{
5563
			CyString sLang;
5564
			CyString id;
5565
			if ( m_iGameFlags & EXEFLAG_TCTEXT )
5566
			{
5567
				id = f->GetBaseName().GetToken("-", 1, 1);
5568
				sLang = f->GetBaseName().GetToken("-", 2, 2);
5569
				if ( sLang.Empty() )
5570
					sLang = "NULL";
5571
				else
5572
					sLang = sLang.Erase(0, 1);  // remove the "L"
5573
			}
5574
			else
5575
			{
5576
				sLang = f->GetBaseName().Left((int)f->GetBaseName().Length() - 4).PadNumber(3);
5577
				id = f->GetBaseName().Mid(((int)f->GetBaseName().Length() - 4) + 1, 4);
5578
			}
5579
 
5580
			if ( sLang != "NULL" )
5581
			{
5582
				if ( sLang.ToInt() == lang )
5583
				{
5584
					++textCount;
5585
					if ( !textEntries.Empty() )
5586
						textEntries += " ";
5587
					textEntries += id;
5588
				}
5589
			}
5590
			f = p->GetNextFile(f);
5591
		}
5592
 
5593
		CyString sTextCount((long)textCount);
50 cycrow 5594
		writeData.push_back(CyString("		<t id=\"") + (long)start + "\">" + this->ConvertTextString(p->name()) + "</t>");
5595
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 1) + "\">" + this->ConvertTextString(p->author()) + "</t>");
5596
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 2) + "\">" + this->ConvertTextString(p->version()) + "</t>");
84 cycrow 5597
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 3) + "\">" + this->ConvertTextString(p->GetLanguageName(lang).ToString()) + "</t>");
1 cycrow 5598
 
14 cycrow 5599
		CLinkList<SSettingType> *settings = spk->GetSettingsList();
1 cycrow 5600
		if ( settings && settings->size() )
5601
		{
5602
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 4) + "\">" + (long)settings->size() + "</t>");
5603
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 5) + "\">" + (long)settingStart + "</t>");
5604
 
14 cycrow 5605
			for ( CListNode<SSettingType> *sNode = settings->Front(); sNode; sNode = sNode->next() )
1 cycrow 5606
			{
14 cycrow 5607
				SSettingType *st = sNode->Data();
1 cycrow 5608
				writeData.push_back(CyString("		<t id=\"") + (long)(settingStart++) + "\">" + st->sKey + "</t>");
5609
				writeData.push_back(CyString("		<t id=\"") + (long)(settingStart++) + "\">" + spk->GetSetting(st) + "</t>");
5610
			}
5611
		}
5612
		else
5613
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 4) + "\">0</t>");
5614
 
5615
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 6) + "\">" + sTextCount + "</t>");
5616
		if ( textCount )
5617
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 7) + "\">" + textEntries + "</t>");
5618
 
5619
		start += 10;
5620
	}
5621
 
5622
	// write ware names
5623
	if ( lWares.size() )
5624
	{
5625
		writeData.push_back(CyString("		<t id=\"5\">") + CyString::Number(start) + "</t>");
5626
		for ( CListNode<SGameWare> *node = lWares.Front(); node; node = node->next() )
5627
		{
5628
			SGameWare *w = node->Data();
5629
			if ( w->pWare && w->iType == WARETYPE_ADDED )
84 cycrow 5630
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">" + this->ConvertTextString(w->sWareName.ToString()) + "</t>");
1 cycrow 5631
			else
5632
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">-1</t>");
5633
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 1) + "\">" + CyString((char)w->cType) + "</t>");
5634
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 2) + "\">" + (long)w->iPos + "</t>");
5635
			start += 10;
5636
		}
5637
	}
5638
 
5639
	if ( lShips.size() )
5640
	{
5641
		writeData.push_back(CyString("		<t id=\"7\">") + CyString::Number(start) + "</t>");
5642
		for ( CListNode<SGameShip> *node = lShips.Front(); node; node = node->next() )
5643
		{
5644
			SGameShip *gs = node->Data();
5645
			if ( gs->iType == WARETYPE_NONE )
5646
				continue;
5647
			if ( gs->pPackage && gs->iType == WARETYPE_ADDED )
5648
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">" + gs->sShipID + "</t>");
5649
			else
5650
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">-1</t>");
5651
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 1) + "\">" + (long)gs->iPos + "</t>");
5652
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 2) + "\">Ship</t>");
5653
 
5654
			// write shipyard info
5655
			if ( gs->pPackage )
5656
			{
5657
				int doStart = start + 5;
5658
				for ( int i = SHIPYARD_ARGON; i <= SHIPYARD_MAX; i *= 2 )
5659
				{
5660
					writeData.push_back(CyString("		<t id=\"") + (long)(doStart) + "\">" + ((gs->pPackage->IsShipyard(i)) ? CyString::Number(1) : CyString::Number(0)) + "</t>");
5661
					++doStart;
5662
				}
5663
			}
5664
 
5665
			start += 20;
5666
		}
5667
	}
5668
 
5669
	writeData.push_back(CyString("	</page>"));
5670
 
5671
	// wares
5672
	if ( m_iGame == GAME_X3AP || m_iGame == GAME_X3TC || m_iGame == GAME_X3 || lWares.size() || lShips.size() )
5673
	{
5674
		if ( !gameNumber )
5675
			writeData.push_back(CyString("  <page id=\"17\" title=\"Plugin Manager Objects\">"));
5676
		else
5677
			writeData.push_back(CyString("  <page id=\"") + (long)gameNumber + "0017\" title=\"Plugin Manager Objects\">");
5678
 
5679
		writeData.push_back(CyString("		<t id=\"") + (long)(SHIPSTARTTEXT - 1) + "\">ZZ_BLANKSHIP</t>");
5680
		// do emp
5681
		if ( m_iGame == GAME_X3TC || m_iGame == GAME_X3 || m_iGame == GAME_X3AP )
5682
			writeData.push_back(GetEMPText());
5683
 
5684
		// object names
5685
		for ( CListNode<SGameWare> *node = lWares.Front(); node; node = node->next() )
5686
		{
5687
			SGameWare *w = node->Data();
5688
			if ( !w->pWare || w->iType != WARETYPE_ADDED )
5689
				continue;
5690
 
5691
			// find the correct text for the language
84 cycrow 5692
			Utils::String name = CSpkFile::GetWareText(w->pWare, m_iLanguage);
5693
			Utils::String desc = CSpkFile::GetWareDesc(w->pWare, m_iLanguage);
5694
			if ( !name.empty() )
17 cycrow 5695
				writeData.push_back(CyString("		<t id=\"") + (long)(w->iText + 3) + "\">" + this->ConvertTextString(name) + "</t>");
84 cycrow 5696
			if ( !desc.empty() )
17 cycrow 5697
				writeData.push_back(CyString("		<t id=\"") + (long)(w->iText + 4) + "\">" + this->ConvertTextString(desc) + "</t>");
1 cycrow 5698
		}
5699
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
5700
		{
5701
			SGameShip *s = node->Data();
5702
			if ( !s->pPackage || s->iType != WARETYPE_ADDED )
5703
				continue;
5704
			if ( s->pPackage->GetOriginalDescription() )
5705
				continue;
5706
 
84 cycrow 5707
			Utils::String name = s->pPackage->GetTextName(m_iLanguage);
5708
			Utils::String desc = s->pPackage->GetTextDescription(m_iLanguage);
5709
			if ( !name.empty() )
17 cycrow 5710
				writeData.push_back(CyString("		<t id=\"") + (long)s->iText + "\">" + this->ConvertTextString(name) + "</t>");
84 cycrow 5711
			if ( !desc.empty() )
17 cycrow 5712
				writeData.push_back(CyString("		<t id=\"") + (long)(s->iText + 1) + "\">" + this->ConvertTextString(desc) + "</t>");
1 cycrow 5713
		}
5714
		writeData.push_back(CyString("  </page>"));
5715
	}
5716
	writeData.push_back(CyString("</language>"));
5717
	textFile.WriteFileUTF(&writeData);
5718
 
5719
	size_t fileSize;
102 cycrow 5720
	char *fileData = CFileIO(textFile.fullFilename()).ReadToData(&fileSize);
1 cycrow 5721
 
5722
	if ( fileData && fileSize)
5723
	{
5724
		size_t newFileSize;
5725
		unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
5726
		if ( pckData )
5727
		{
5728
			CFileIO pckFile(m_sCurrentDir + "/t/" + filename + ".pck");
5729
			pckFile.WriteData((char *)pckData, newFileSize);
102 cycrow 5730
			this->AddCreatedFile(pckFile.fullFilename());
1 cycrow 5731
		}
5732
	}
52 cycrow 5733
	textFile.remove();
1 cycrow 5734
}
5735
 
5736
bool CPackages::IsCurrentDir(CyString dir)
5737
{
5738
	if ( dir.Compare(m_sCurrentDir) )
5739
		return true;
5740
 
5741
	CyString checkDir = m_sCurrentDir;
5742
	checkDir = checkDir.FindReplace("/", "\\");
5743
	if ( checkDir.Compare(dir) )
5744
		return true;
5745
 
5746
	checkDir = checkDir.FindReplace("\\", "/");
5747
	if ( checkDir.Compare(dir) )
5748
		return true;
5749
 
5750
	return false;
5751
}
5752
 
5753
void CPackages::BackupSaves(bool vanilla)
5754
{
5755
	// copy any saves into the vanilla directory
102 cycrow 5756
	Utils::String dir = (vanilla) ? "Vanilla" : "Modified";
1 cycrow 5757
 
5758
	// make sure the directory exists
102 cycrow 5759
	CDirIO saveDir(this->saveDirectory());
1 cycrow 5760
	CDirIO gameSaveDir(m_sCurrentDir);
5761
	if ( !gameSaveDir.Exists("PluginManager") )
5762
		gameSaveDir.Create("PluginManager");
5763
	gameSaveDir.cd("PluginManager");
5764
	if ( !gameSaveDir.Exists("Saves") )
5765
		gameSaveDir.Create("Saves");
5766
	gameSaveDir.cd("Saves");
5767
	if ( !gameSaveDir.Exists(dir) )
5768
		gameSaveDir.Create(dir);
5769
	gameSaveDir.cd(dir);
5770
 
5771
	// backup the saves
86 cycrow 5772
	CyStringList *files = saveDir.DirList();
5773
	if ( files )
1 cycrow 5774
	{
86 cycrow 5775
		for ( SStringList *node = files->Head(); node; node = node->next )
1 cycrow 5776
		{
5777
			CFileIO File(saveDir.File(node->str));
5778
			if ( !File.CheckFileExtension("sav") )
5779
				continue;
5780
			// remove the file if already exists
5781
			if ( gameSaveDir.Exists(node->str) )
52 cycrow 5782
				CFileIO::Remove(gameSaveDir.File(node->str).ToString());
1 cycrow 5783
 
5784
			// copy the file into the games save dir for backup
52 cycrow 5785
			File.copy(gameSaveDir.File(File.GetFilename()).ToString(), true);
1 cycrow 5786
		}
5787
 
86 cycrow 5788
		delete files;
1 cycrow 5789
	}
5790
 
5791
}
5792
 
5793
void CPackages::RestoreSaves(bool vanilla)
5794
{
5795
	// get dir to restore from
102 cycrow 5796
	Utils::String dir = (vanilla) ? "Vanilla" : "Modified";
1 cycrow 5797
	CDirIO restoreDir(m_sCurrentDir + "/PluginManager/Saves/" + dir);
102 cycrow 5798
	CDirIO toDir(this->saveDirectory());
1 cycrow 5799
 
86 cycrow 5800
	//if we are in vanilla mode, we should remove the saves (so we only have vanilla saves
5801
	if ( vanilla ) {
5802
		CyStringList *files = toDir.DirList();
5803
		if ( files ) {
5804
			for ( SStringList *node = files->Head(); node; node = node->next )
5805
			{
5806
				CFileIO saveFile(toDir.File(node->str));
5807
				if ( saveFile.extension().Compare("sav") ) {
5808
					saveFile.remove();
5809
				}
5810
			}
5811
			delete files;
5812
		}
5813
	}
5814
 
5815
	// now we copy of the backed up save games
1 cycrow 5816
	CyStringList *dirs = restoreDir.DirList();
5817
	if ( dirs )
5818
	{
5819
		for ( SStringList *node = dirs->Head(); node; node = node->next )
5820
		{
5821
			CFileIO File(restoreDir.File(node->str));
5822
			// remove the file if already exists
52 cycrow 5823
			if ( toDir.Exists(node->str) ) CFileIO::Remove(toDir.File(node->str).ToString());
1 cycrow 5824
 
5825
			// move file over
52 cycrow 5826
			File.copy(toDir.File(node->str).ToString(), true);
1 cycrow 5827
		}
5828
 
5829
		delete dirs;
5830
	}
5831
 
5832
}
5833
 
5834
bool CPackages::RemoveCurrentDirectory()
5835
{
5836
	if ( !m_bLoaded )
5837
		return false;
5838
 
5839
	// remove all package files
5840
	this->RemoveAllPackages();
5841
 
5842
	// remove all plugin manager files
5843
	this->RemoveCreatedFiles();
5844
 
5845
	// restore any vanilla saves
5846
	/*
5847
	if ( !m_bVanilla )
5848
	{
5849
		this->BackupSaves();
5850
		m_bVanilla = true;
5851
		this->RestoreSaves();
5852
	}*/
5853
 
5854
	this->Reset();
5855
	m_bLoaded = false;
5856
 
5857
	// clear the plugin manager directory
5858
	CDirIO Dir(m_sCurrentDir);
5859
	Dir.RemoveDir("PluginManager", true, true, 0);
5860
	Dir.RemoveDir("dds", false, true, 0);
5861
	Dir.RemoveDir("objects", false, true, 0);
5862
	Dir.RemoveDir("types", false, true, 0);
5863
	Dir.RemoveDir("textures", false, true, 0);
5864
 
5865
	// remove the plugin manager mod files
52 cycrow 5866
	if ( Dir.Exists("mods/PluginManager.cat") )	CFileIO::Remove(Dir.File("mods/PluginManager.cat").ToString());
5867
	if ( Dir.Exists("mods/PluginManager.dat") )	CFileIO::Remove(Dir.File("mods/PluginManager.dat").ToString());
1 cycrow 5868
 
5869
	return true;
5870
}
5871
 
5872
void CPackages::CreateDummies()
5873
{
5874
	// first check we have any ships
5875
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
5876
		return;
5877
 
5878
	CLinkList<SDummyEntry> dummyList;
5879
 
5880
	// now extract the existing dummies
5881
	int e = ExtractGameFile("types/Dummies.pck", m_sTempDir + "/Dummies.txt");
5882
	if ( e )
5883
	{
5884
		// read the dummies
5885
		CFileIO File;
5886
		if ( File.Open((e == -1) ? "Dummies.txt" : m_sTempDir + "/Dummies.txt") )
5887
		{
5888
			std::vector<CyString> *lines = File.ReadLines();
5889
			if ( lines )
5890
			{
5891
				int insection = 0;
5892
				SDummyEntry *currentSection = NULL;
5893
				for ( int j = 0; j < (int)lines->size(); j++ )
5894
				{
5895
					CyString line(lines->at(j));
5896
					line.RemoveChar(9);
5897
					line.RemoveChar('\r');
5898
					line.RemoveFirstSpace();
64 cycrow 5899
					line.RemoveEndSpace();
1 cycrow 5900
					if ( line.Empty() )
5901
						continue;
5902
					if ( line[0] == '/' )
5903
						continue;
5904
 
5905
					// read the section, first entry is section, second is size
5906
					while ( !line.Empty() )
5907
					{
5908
						if ( !insection )
5909
						{
5910
							CyString section = line.GetToken(";", 1, 1);
5911
							insection = line.GetToken(";", 2, 2).ToInt();
5912
 
5913
							// search for the sections
5914
							currentSection = NULL;
5915
							for ( CListNode<SDummyEntry> *node = dummyList.Front(); node; node = node->next() )
5916
							{
5917
								SDummyEntry *d = node->Data();
5918
								if ( d->sSection.Compare(section) )
5919
								{
5920
									currentSection = node->Data();
5921
									break;
5922
								}
5923
							}
5924
 
5925
							if ( !currentSection )
5926
							{
5927
								currentSection = new struct SDummyEntry;
5928
								currentSection->sSection = section;
5929
								dummyList.push_back(currentSection);
5930
							}
5931
 
5932
							// we have some more ?
5933
							line = line.DelToken(";", 1, 2);
5934
						}
5935
						else
5936
						{
5937
							--insection;
5938
							// check the last entry for number of states
5939
							if ( currentSection->sSection.Compare("SDTYPE_GUN") )
5940
							{
5941
								int states = line.GetToken(";", 3, 3).ToInt();
5942
								int parts = line.GetToken(";", 4 + (states * 2), 4 + (states * 2)).ToInt();
5943
								CyString data = line.GetToken(";", 1, 4 + (states * 2) + (parts * 2)) + ";";
5944
								currentSection->lEntries.PushBack(data);
5945
 
5946
								// remove done
5947
								line = line.DelToken(";", 1, 4 + (states * 2) + (parts * 2));
5948
							}
5949
							else
5950
							{
5951
								int states = line.GetToken(";", 3, 3).ToInt();
5952
								CyString data = line.GetToken(";", 1, 3 + (states * 2)) + ";";
5953
								currentSection->lEntries.PushBack(data);
5954
 
5955
								// remove done
5956
								line = line.DelToken(";", 1, 3 + (states * 2));
5957
							}
5958
						}
5959
					}
5960
				}
5961
 
5962
				delete lines;
5963
			}
5964
 
52 cycrow 5965
			File.remove();
1 cycrow 5966
		}
5967
 
5968
		// add the new entries for the ships
5969
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
5970
		{
5971
			SGameShip *s = node->Data();
5972
			if ( s->iType != WARETYPE_ADDED || !s->pPackage )
5973
				continue;
5974
 
5975
			// no dummies to add?
5976
			if ( !s->pPackage->AnyDummies() )
5977
				continue;
5978
 
5979
			// add each dummy to list
5980
			for ( CListNode<SDummy> *dNode = s->pPackage->GetDummies()->Front(); dNode; dNode = dNode->next() )
5981
			{
5982
				SDummy *dummy = dNode->Data();
5983
				SDummyEntry *found = NULL;
5984
				for ( CListNode<SDummyEntry> *eNode = dummyList.Front(); eNode; eNode = eNode->next() )
5985
				{
39 cycrow 5986
					if ( eNode->Data()->sSection.Compare(CyString(dummy->sSection)) )
1 cycrow 5987
					{
5988
						found = eNode->Data();
5989
						break;
5990
					}
5991
				}
5992
				if ( !found )
5993
				{
5994
					found = new SDummyEntry;
5995
					found->sSection = dummy->sSection;
5996
					dummyList.push_back(found);
5997
				}
5998
				// check if its already on the list
5999
				else
6000
				{
6001
					bool f = false;
6002
					for ( SStringList *strNode = found->lEntries.Head(); strNode; strNode = strNode->next )
6003
					{
39 cycrow 6004
						if ( strNode->str.GetToken(";", 1, 1).Compare(CyString(dummy->sData.token(";", 1))) )
1 cycrow 6005
						{
6006
							f = true;
6007
							break;
6008
						}
6009
					}
6010
 
6011
					if ( f )
6012
						continue;
6013
				}
6014
 
39 cycrow 6015
				found->lEntries.PushBack(CyString(dummy->sData));
1 cycrow 6016
			}
6017
		}
6018
 
6019
		// finally, write the file
6020
		std::vector<CyString> lines;
6021
		lines.push_back(CyString("// Dummies file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6022
		for ( SDummyEntry *dummy = dummyList.First(); dummy; dummy = dummyList.Next() )
6023
		{
6024
			lines.push_back("");
6025
			lines.push_back(CyString("// Section: ") + dummy->sSection + " Entries: " + (long)dummy->lEntries.Count());
6026
			lines.push_back(dummy->sSection + ";" + CyString::Number(dummy->lEntries.Count()) + ";");
6027
			for ( SStringList *str = dummy->lEntries.Head(); str; str = str->next )
6028
			{
6029
				CyString strLine = str->str;
6030
				strLine.RemoveChar(9);
6031
				strLine.RemoveChar('\r');
6032
				strLine.RemoveEndSpace();
6033
				strLine.RemoveFirstSpace();
6034
				strLine = strLine.FindReplace("<::PiPe::>", "|");
6035
				if ( strLine.Right(1) != ";" )
6036
					strLine += ";";
6037
				lines.push_back(strLine);
6038
			}
6039
		}
6040
		lines.push_back("");
6041
 
6042
		// write the file to disk
6043
		CFileIO WriteFile(m_sTempDir + "/dummies.txt");
6044
		if ( WriteFile.WriteFile(&lines) )
6045
		{
6046
			this->PackFile(&WriteFile, "types\\dummies.pck");
52 cycrow 6047
			WriteFile.remove();
1 cycrow 6048
		}
6049
	}
6050
}
6051
 
6052
void CPackages::CreateCutData()
6053
{
6054
	// first check we have any ships
6055
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6056
		return;
6057
 
6058
	bool found = false;
6059
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6060
	{
6061
		SGameShip *s = node->Data();
6062
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6063
			continue;
6064
 
6065
		// no dummies to add?
6066
		if ( !s->pPackage->AnyCutData() )
6067
			continue;
6068
		found = true;
6069
		break;
6070
	}
6071
 
6072
	if ( !found )
6073
		return;
6074
 
6075
	CyStringList cutList;
6076
	int e = ExtractGameFile("types/CutData.pck", m_sTempDir + "/CutData.txt");
6077
	if ( e )
6078
	{
6079
		CFileIO File;
6080
		if ( File.Open((e == -1) ? "CutData.txt" : m_sTempDir + "/CutData.txt") )
6081
		{
6082
			std::vector<CyString> *lines = File.ReadLines();
6083
			if ( lines )
6084
			{
6085
				int entries = -1;
6086
				for ( int j = 0; j < (int)lines->size(); j++ )
6087
				{
6088
					CyString line(lines->at(j));
6089
					line.RemoveChar(9);
6090
					line.RemoveChar('\r');
6091
					line.RemoveChar(' ');
6092
					if ( line.Empty() || line[0] == '/' )
6093
						continue;
6094
					if ( entries == -1 )
6095
						entries = line.GetToken(";", 1, 1).ToInt();
6096
					else
6097
					{
6098
						if ( line.Right(1) != ";" )
6099
							line += ";";
6100
						cutList.PushBack(line);
6101
						if ( cutList.Count() == entries )
6102
							break;
6103
					}
6104
				}
6105
 
6106
				delete lines;
6107
			}
6108
 
52 cycrow 6109
			File.remove();
1 cycrow 6110
		}
6111
	}
6112
 
6113
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6114
	{
6115
		SGameShip *s = node->Data();
6116
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6117
			continue;
6118
 
6119
		// no dummies to add?
6120
		if ( !s->pPackage->AnyCutData() )
6121
			continue;
6122
 
6123
		// add each dummy to list
6124
		for ( SStringList *strNode = s->pPackage->GetCutData()->Head(); strNode; strNode = strNode->next )
6125
		{
6126
			CyString str = strNode->str;
6127
			str.RemoveChar(' ');
6128
			if ( str.Right(1) != ";" )
6129
				str += ";";
6130
			cutList.PushBack(str, true);
6131
		}
6132
	}
6133
 
6134
	cutList.PushFront(CyString::Number(cutList.Count()) + ";");
6135
	cutList.PushFront("/cut id;filename (leave blank to use id)");
6136
	cutList.PushFront(CyString("// Cut Data file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6137
 
6138
	// write the file to disk
6139
	CFileIO WriteFile(m_sTempDir + "/CutData.txt");
6140
	if ( WriteFile.WriteFile(&cutList) )
6141
	{
6142
		this->PackFile(&WriteFile, "types\\CutData.pck");
52 cycrow 6143
		WriteFile.remove();
1 cycrow 6144
	}
6145
}
6146
 
6147
void CPackages::CreateAnimations()
6148
{
6149
	// first check we have any ships
6150
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6151
		return;
6152
 
6153
	bool found = false;
6154
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6155
	{
6156
		SGameShip *s = node->Data();
6157
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6158
			continue;
6159
 
6160
		// no dummies to add?
6161
		if ( !s->pPackage->AnyAnimations() )
6162
			continue;
6163
		found = true;
6164
		break;
6165
	}
6166
 
6167
	if ( !found )
6168
		return;
6169
 
6170
	CyStringList aniList;
6171
	int e = ExtractGameFile("types/Animations.pck", m_sTempDir + "/Animations.txt");
6172
	if ( e )
6173
	{
6174
		CFileIO File;
6175
		if ( File.Open((e == -1) ? "Animations.txt" : m_sTempDir + "/Animations.txt") )
6176
		{
6177
			std::vector<CyString> *lines = File.ReadLines();
6178
			if ( lines )
6179
			{
6180
				for ( int j = 0; j < (int)lines->size(); j++ )
6181
				{
6182
					CyString line(lines->at(j));
6183
					aniList.PushBack(line);
6184
				}
6185
 
6186
				delete lines;
6187
			}
6188
 
52 cycrow 6189
			File.remove();
1 cycrow 6190
		}
6191
	}
6192
 
6193
	CyStringList parsedAniList;
6194
	CXspFile::ReadAnimations(&aniList, &parsedAniList, 0);
6195
 
6196
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6197
	{
6198
		SGameShip *s = node->Data();
6199
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6200
			continue;
6201
 
6202
		// no dummies to add?
6203
		if ( !s->pPackage->AnyAnimations() )
6204
			continue;
6205
 
6206
		// add each dummy to list
6207
		for ( SStringList *strNode = s->pPackage->GetAnimations()->Head(); strNode; strNode = strNode->next )
6208
			parsedAniList.PushBack(strNode->str);
6209
	}
6210
 
6211
	// format the list with added spaces
6212
	CyStringList formatedAniList;
6213
	int lineCount = -1;
6214
	for ( SStringList *strNode = parsedAniList.Head(); strNode; strNode = strNode->next )
6215
	{
6216
		// format the comment to match the line number
6217
		lineCount++;
6218
		CyString oldComment = strNode->str.GetToken("//", 2);
6219
		CyString comment = CyString("//") + CyString::Number(lineCount);
6220
		if ( !oldComment.Empty() )
6221
		{
6222
			comment += " ";
6223
			oldComment.RemoveFirstSpace();
6224
			if ( oldComment.GetToken(" ", 1, 1).IsNumber() )
6225
				comment += oldComment.GetToken(" ", 2);
6226
			else
6227
				comment += oldComment;
6228
		}
6229
		CyString line = strNode->str.GetToken("//", 1, 1);
6230
 
6231
		// split into seperate lines
6232
		CyString first = line.GetToken(";", 1, 1);
6233
		if ( first.Compare("TAT_TAGSINGLESTEP") )
6234
		{
6235
			formatedAniList.PushBack(line.GetToken(";", 1, 5) + ";");
6236
			int max;
6237
			CyString *sLines = line.GetToken(";", 6).SplitToken(";", &max);
6238
			if ( max && sLines )
6239
			{
6240
				if ( sLines[max - 1].Empty() )
6241
					--max; // remove the last ";"
6242
 
6243
				for ( int i = 0; i < max; i++ )
6244
				{
6245
					CyString l = CyString("\t") + sLines[i] + ";";
6246
					if ( i == (max - 1) )
6247
						formatedAniList.PushBack(l + comment);
6248
					else
6249
						formatedAniList.PushBack(l);
6250
				}
6251
			}
6252
			CLEANSPLIT(sLines, max);
6253
		}
6254
		else if ( (first.Compare("TAT_TAGONESHOT") || first.Compare("TAT_TAGLOOP")) && (line.IsIn("TATF_COORDS")) )
6255
		{
6256
			formatedAniList.PushBack(line.GetToken(";", 1, 5) + ";");
6257
			int max;
6258
			CyString *sLines = line.GetToken(";", 6).SplitToken(";", &max);
6259
			if ( max && sLines )
6260
			{
6261
				if ( sLines[max - 1].Empty() )
6262
					--max; // remove the last ";"
6263
 
6264
				CyString prevLine;
6265
				for ( int i = 0; i < max; i++ )
6266
				{
6267
					CyString l = sLines[i] + ";";
6268
					if ( l.IsIn("TATF_COORDS") && !prevLine.Empty() )
6269
					{
6270
						formatedAniList.PushBack(CyString("\t") + prevLine);
6271
						prevLine = "";
6272
					}
6273
					prevLine += l;
6274
				}
6275
 
6276
				if ( !prevLine.Empty() )
6277
					formatedAniList.PushBack(CyString("\t") + prevLine + comment);
6278
 
6279
			}
6280
			CLEANSPLIT(sLines, max);
6281
		}
6282
		else
6283
			formatedAniList.PushBack(line + comment);
6284
	}
6285
 
6286
	formatedAniList.PushFront(CyString::Number(parsedAniList.Count()) + ";");
6287
	formatedAniList.PushFront(CyString("// Animations, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6288
 
6289
	// write the file to disk
6290
	CFileIO WriteFile(m_sTempDir + "/Animations.txt");
6291
	if ( WriteFile.WriteFile(&formatedAniList) )
6292
	{
6293
		this->PackFile(&WriteFile, "types\\Animations.pck");
52 cycrow 6294
		WriteFile.remove();
1 cycrow 6295
	}
6296
}
6297
 
6298
void CPackages::CreateBodies()
6299
{
6300
	// first check we have any ships
6301
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6302
		return;
6303
 
6304
	bool found = false;
6305
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6306
	{
6307
		SGameShip *s = node->Data();
6308
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6309
			continue;
6310
 
6311
		// no dummies to add?
6312
		if ( !s->pPackage->AnyBodies() )
6313
			continue;
6314
		found = true;
6315
		break;
6316
	}
6317
 
6318
	if ( !found )
6319
		return;
6320
 
6321
	// lets read our current bodies file
6322
	CLinkList<SBodies> bodiesList;
6323
	SBodies *currentSection = NULL;
6324
	int e = ExtractGameFile("types/Bodies.pck", m_sTempDir + "/Bodies.txt");
6325
	if ( e )
6326
	{
6327
		CFileIO File;
6328
		if ( File.Open((e == -1) ? "Bodies.txt" : m_sTempDir + "/Bodies.txt") )
6329
		{
6330
			std::vector<CyString> *lines = File.ReadLines();
6331
			if ( lines )
6332
			{
6333
				int entries = 0;
6334
				for ( int j = 0; j < (int)lines->size(); j++ )
6335
				{
6336
					CyString line(lines->at(j));
6337
					line.RemoveChar(' ');
6338
					line.RemoveChar(9);
6339
					if ( line.Empty() || line[0] == '/' )
6340
						continue;
6341
					if ( entries <= 0 )
6342
					{
6343
						entries = line.GetToken(";", 2, 2).ToInt();
6344
						currentSection = new SBodies;
6345
						currentSection->sSection = line.GetToken(";", 1, 1);
6346
						bodiesList.push_back(currentSection);
6347
					}
6348
					else if ( currentSection )
6349
					{
6350
						int num;
6351
						CyString *strs = line.SplitToken(";", &num);
6352
						if ( num && strs )
6353
						{
6354
							for ( int i = 0; i < num; i++ )
6355
							{
6356
								if ( strs[i].Empty() )
6357
									continue;
6358
								currentSection->lEntries.PushBack(strs[i] + ";", true);
6359
								--entries;
6360
							}
6361
						}
6362
						CLEANSPLIT(strs, num);
6363
					}
6364
				}
6365
 
6366
				delete lines;
6367
			}
52 cycrow 6368
			File.remove();
1 cycrow 6369
		}
6370
	}
6371
 
6372
	// lets now add any new entries
6373
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6374
	{
6375
		SGameShip *s = node->Data();
6376
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6377
			continue;
6378
 
6379
		// no dummies to add?
6380
		if ( !s->pPackage->AnyBodies() )
6381
			continue;
6382
 
6383
		// add each dummy to list
6384
		for ( SStringList *strNode = s->pPackage->GetBodies()->Head(); strNode; strNode = strNode->next )
6385
		{
6386
			CyString section = strNode->str.GetToken(";", 1, 1);
6387
			CyString body = strNode->str.GetToken(";", 2).Remove(' ');
6388
			if ( body.Right(1) != ";" )
6389
				body += ";";
6390
 
6391
			// find the section to add into
6392
			SBodies *foundSection = NULL;
6393
			for ( CListNode<SBodies> *checkBody = bodiesList.Front(); checkBody; checkBody = checkBody->next() )
6394
			{
6395
				if ( checkBody->Data()->sSection.Compare(section) )
6396
				{
6397
					foundSection = checkBody->Data();
6398
					break;
6399
				}
6400
			}
6401
 
6402
			if ( !foundSection )
6403
			{
6404
				foundSection = new SBodies;
6405
				foundSection->sSection = section;
6406
				bodiesList.push_back(foundSection);
6407
			}
6408
			foundSection->lEntries.PushBack(body, true);
6409
		}
6410
	}
6411
 
6412
	// now write the file
6413
	CyStringList writeList;
6414
	// the header first
6415
	writeList.PushBack(CyString("// Bodies file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6416
	writeList.PushBack("//body type;num bodies;");
6417
	writeList.PushBack("//[body id/name]");
6418
 
6419
	// now our sections
6420
	for ( SBodies *bSection = bodiesList.First(); bSection; bSection = bodiesList.Next() )
6421
	{
6422
		writeList.PushBack("");
6423
		writeList.PushBack(CyString("// Section: ") + bSection->sSection);
6424
		writeList.PushBack(bSection->sSection + ";" + CyString::Number(bSection->lEntries.Count()) + ";");
6425
		for ( SStringList *strNode = bSection->lEntries.Head(); strNode; strNode = strNode->next )
6426
		{
6427
			CyString str = strNode->str;
6428
			str.RemoveChar(9);
6429
			str.RemoveChar(' ');
6430
			if ( str.Right(1) != ";" )
6431
				str += ";";
6432
			writeList.PushBack(str);
6433
		}
6434
	}
6435
 
6436
	// write the file to disk
6437
	CFileIO WriteFile(m_sTempDir + "/Bodies.txt");
6438
	if ( WriteFile.WriteFile(&writeList) )
6439
	{
6440
		this->PackFile(&WriteFile, "types\\Bodies.pck");
52 cycrow 6441
		WriteFile.remove();
1 cycrow 6442
	}
6443
}
6444
 
6445
void CPackages::CreateCustomStarts()
6446
{
6447
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
6448
	{
6449
		// find all spk files (only ones that can be custom starts
6450
		if ( node->Data()->GetType() != TYPE_SPK )
6451
			continue;
6452
 
6453
		CSpkFile *p = (CSpkFile *)node->Data();
6454
 
6455
		// only use custom starts
6456
		if ( !p->IsCustomStart() )
6457
			continue;
6458
 
6459
		// get the name of the start to use
6460
		CyString name = p->GetCustomStartName();
6461
		if ( name.Empty() )
6462
			continue;
6463
 
6464
		// find if maps file exists
6465
		CyStringList createFiles;
6466
		createFiles.PushBack(name, "maps/x3_universe");
6467
		createFiles.PushBack(name, "types/Jobs");
6468
		createFiles.PushBack(name, "types/JobWings");
6469
 
6470
		for ( SStringList *str = createFiles.Head(); str; str = str->next )
6471
		{
102 cycrow 6472
			Utils::String dir = CFileIO(str->data).dir();
1 cycrow 6473
			int type = FILETYPE_EXTRA;
6474
			if ( dir.Compare("maps") )
6475
				type = FILETYPE_MAP;
6476
 
6477
			if ( !p->FindFile(str->str + ".xml", type) && !p->FindFile(str->str + ".pck", type) )
6478
			{
6479
				// create a maps files
6480
				int e = this->ExtractGameFile(str->data + ".pck", m_sTempDir + "/" + str->data + ".pck");
6481
				if ( e )
6482
				{
6483
					CFileIO File((e == -1) ? (str->data + ".pck") : (m_sTempDir + "/" + str->data + ".pck"));
52 cycrow 6484
					if ( File.exists() )
1 cycrow 6485
					{
6486
						File.Rename(m_sCurrentDir + "/" + dir + "/" + str->str + ".pck");
102 cycrow 6487
						this->AddCreatedFile(dir + "/" + str->str.ToString() + ".pck");
1 cycrow 6488
					}
6489
				}
6490
			}
6491
		}
6492
	}
6493
}
6494
 
6495
void CPackages::AddCreatedFile(CyString file)
6496
{
6497
	file = file.Remove(m_sCurrentDir);
6498
	while ( file[0] == '/' )
6499
		file.Erase(0, 1);
6500
	while ( file[0] == '\\' )
6501
		file.Erase(0, 1);
6502
 
6503
	m_lCreatedFiles.PushBack(file, true);
6504
}
6505
 
6506
void CPackages::CreateComponants()
6507
{
6508
	// first check we have any ships
6509
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6510
		return;
6511
 
6512
	CLinkList<SComponantEntry> dummyList;
6513
 
6514
	// now extract the existing dummies
6515
	int e = ExtractGameFile("types/Components.pck", m_sTempDir + "/Components.txt");
6516
	if ( e )
6517
	{
6518
		// read the dummies
6519
		CFileIO File;
6520
		if ( File.Open((e == -1) ? "Components.txt" : m_sTempDir + "/Components.txt") )
6521
		{
6522
			std::vector<CyString> *lines = File.ReadLines();
6523
			if ( lines )
6524
			{
6525
				int insection = 0;
6526
				int insubsection = 0;
6527
				SComponantEntry *currentSection = NULL;
6528
				SComponantEntry2 *currentSubSection = NULL;
6529
				for ( int j = 0; j < (int)lines->size(); j++ )
6530
				{
6531
					CyString line(lines->at(j));
6532
					if ( line[0] == '/' )
6533
						continue;
6534
					line.RemoveChar('\r');
6535
					line = line.RemoveFirstSpace();
6536
					line = line.RemoveEndSpace();
6537
					if ( line.Empty() )
6538
						continue;
6539
 
6540
 
6541
					// read the section, first entry is section, second is size
6542
					while ( !line.Empty() )
6543
					{
6544
						line = line.RemoveFirstSpace();
6545
						if ( line.Empty() )
6546
							break;
6547
 
6548
						if ( !insection && !insubsection )
6549
						{
6550
							CyString section = line.GetToken(";", 1, 1);
6551
							insection = line.GetToken(";", 2, 2).ToInt();
6552
 
6553
							// search for the sections
6554
							currentSection = NULL;
6555
							for ( CListNode<SComponantEntry> *node = dummyList.Front(); node; node = node->next() )
6556
							{
6557
								SComponantEntry *d = node->Data();
6558
								if ( d->sSection.Compare(section) )
6559
								{
6560
									currentSection = node->Data();
6561
									break;
6562
								}
6563
							}
6564
 
6565
							if ( !currentSection )
6566
							{
6567
								currentSection = new SComponantEntry;
6568
								currentSection->sSection = section;
6569
								dummyList.push_back(currentSection);
6570
							}
6571
 
6572
							// we have some more ?
6573
							line = line.DelToken(";", 1, 2);
6574
						}
6575
						else if ( !insubsection )
6576
						{
6577
							--insection;
6578
							CyString section = line.GetToken(";", 1, 1);
6579
							insubsection = line.GetToken(";", 2, 2).ToInt();
6580
 
6581
							currentSubSection = new SComponantEntry2;
6582
							currentSubSection->sSection = section;
6583
							currentSection->lEntries.push_back(currentSubSection);
6584
 
6585
							line = line.DelToken(";", 1, 2);
6586
						}
6587
						else
6588
						{
6589
							--insubsection;
6590
							currentSubSection->lEntries.PushBack(line.Remove(' '), true);
6591
							line = "";
6592
						}
6593
					}
6594
				}
6595
 
6596
				delete lines;
6597
			}
6598
 
52 cycrow 6599
			File.remove();
1 cycrow 6600
		}
6601
 
6602
		// add the new entries for the ships
6603
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6604
		{
6605
			SGameShip *s = node->Data();
6606
			if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6607
				continue;
6608
 
6609
			// no dummies to add?
6610
			if ( !s->pPackage->AnyComponents() )
6611
				continue;
6612
 
6613
			// add each dummy to list
6614
			for ( CListNode<SComponent> *dNode = s->pPackage->GetComponents()->Front(); dNode; dNode = dNode->next() )
6615
			{
6616
				SComponent *dummy = dNode->Data();
6617
				SComponantEntry *found = NULL;
6618
				SComponantEntry2 *found2 = NULL;
6619
				for ( CListNode<SComponantEntry> *eNode = dummyList.Front(); eNode; eNode = eNode->next() )
6620
				{
39 cycrow 6621
					if ( eNode->Data()->sSection.Compare(CyString(dummy->sSection)) )
1 cycrow 6622
					{
6623
						found = eNode->Data();
6624
						break;
6625
					}
6626
				}
6627
				if ( !found )
6628
				{
6629
					found = new SComponantEntry;
6630
					found->sSection = dummy->sSection;
6631
					dummyList.push_back(found);
6632
					found2 = new SComponantEntry2;
6633
					found2->sSection = dummy->sSection2;
6634
					found->lEntries.push_back(found2);
6635
				}
6636
				// else check for the 2nd section
6637
				else
6638
				{
6639
					for ( CListNode<SComponantEntry2> *cNode = found->lEntries.Front(); cNode; cNode = cNode->next() )
6640
					{
39 cycrow 6641
						if ( cNode->Data()->sSection.Compare(CyString(dummy->sSection2)) )
1 cycrow 6642
						{
6643
							found2 = cNode->Data();
6644
							break;
6645
						}
6646
					}
6647
 
6648
					if ( !found2 )
6649
					{
6650
						found2 = new SComponantEntry2;
6651
						found2->sSection = dummy->sSection2;
6652
						found->lEntries.push_back(found2);
6653
					}
6654
					else
6655
					{
6656
						bool f = false;
6657
						for ( SStringList *strNode = found2->lEntries.Head(); strNode; strNode = strNode->next )
6658
						{
39 cycrow 6659
							if ( dummy->sData.remove(' ').Compare(strNode->str.ToString()) )
1 cycrow 6660
							{
6661
								f = true;
6662
								break;
6663
							}
6664
						}
6665
 
6666
						if ( f )
6667
							continue;
6668
					}
6669
				}
6670
 
39 cycrow 6671
				found2->lEntries.PushBack(CyString(dummy->sData.remove(' ')));
1 cycrow 6672
			}
6673
		}
6674
 
6675
		// finally, write the file
6676
		std::vector<CyString> lines;
6677
		lines.push_back(CyString("// Components file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6678
		for ( SComponantEntry *dummy = dummyList.First(); dummy; dummy = dummyList.Next() )
6679
		{
6680
			lines.push_back("");
6681
			lines.push_back(CyString("// Section: ") + dummy->sSection + " Entries: " + (long)dummy->lEntries.size());
6682
			lines.push_back(dummy->sSection + ";" + CyString::Number(dummy->lEntries.size()) + ";");
6683
			for ( CListNode<SComponantEntry2> *comp = dummy->lEntries.Front(); comp; comp = comp->next() )
6684
			{
6685
				lines.push_back(comp->Data()->sSection + ";" + (long)comp->Data()->lEntries.Count() + ";");
6686
				for ( SStringList *str = comp->Data()->lEntries.Head(); str; str = str->next )
6687
				{
6688
					CyString cStr = str->str;
6689
					cStr.RemoveEndSpace();
6690
					cStr.RemoveChar(9);
6691
					cStr.RemoveChar('\r');
6692
					if ( cStr.Right(1) != ";" )
6693
						cStr += ";";
6694
					lines.push_back(cStr);
6695
				}
6696
			}
6697
		}
6698
 
6699
		// write the file to disk
6700
		CFileIO WriteFile(m_sTempDir + "/Components.txt");
6701
		if ( WriteFile.WriteFile(&lines) )
6702
		{
6703
			this->PackFile(&WriteFile, "types\\Components.pck");
52 cycrow 6704
			WriteFile.remove();
1 cycrow 6705
		}
6706
	}
6707
}
6708
 
89 cycrow 6709
bool CPackages::readWares(int iLang, CLinkList<SWareEntry> &list)
88 cycrow 6710
{
89 cycrow 6711
	if ( iLang == 0 ) iLang = m_iLanguage;
88 cycrow 6712
 
89 cycrow 6713
	Utils::String empWares = this->empWaresForGame();
6714
 
6715
	for(CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next()) {
91 cycrow 6716
		if ( !node->Data()->IsEnabled() ) continue;
89 cycrow 6717
		node->Data()->readWares(iLang, list, empWares);
88 cycrow 6718
	}
6719
 
89 cycrow 6720
	return true;
6721
}
88 cycrow 6722
 
89 cycrow 6723
bool CPackages::readCommands(int iLang, CLinkList<SCommandSlot> &list)
6724
{
6725
	if ( iLang == 0 ) iLang = m_iLanguage;
6726
 
6727
	for(CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next()) {
91 cycrow 6728
		if ( !node->Data()->IsEnabled() ) continue;
89 cycrow 6729
		node->Data()->readCommands(iLang, list);
88 cycrow 6730
	}
6731
 
89 cycrow 6732
	return true;
6733
}
88 cycrow 6734
 
89 cycrow 6735
bool CPackages::readWingCommands(int iLang, CLinkList<SCommandSlot> &list)
6736
{
6737
	if ( iLang == 0 ) iLang = m_iLanguage;
6738
 
6739
	for(CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next()) {
91 cycrow 6740
		if ( !node->Data()->IsEnabled() ) continue;
89 cycrow 6741
		node->Data()->readWingCommands(iLang, list);
6742
	}
6743
 
88 cycrow 6744
	return true;
6745
}
6746
 
6747
int CPackages::_warePriceOverride(enum WareTypes type, int pos, const Utils::String &id)
6748
{
6749
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
6750
		if ( node->Data()->type == type ) {
6751
			if ( node->Data()->type == Ware_Custom && id.Compare(node->Data()->id) ) return node->Data()->relval;
6752
			else if ( node->Data()->type != Ware_Custom && node->Data()->pos == pos ) return node->Data()->relval;
6753
		}
6754
	}
6755
	return 0;
6756
}
6757
 
6758
bool CPackages::_wareNotoOverride(enum WareTypes type, int pos, const Utils::String &id, int *noto)
6759
{
6760
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
6761
		if ( node->Data()->type == type && node->Data()->bNotority ) {
6762
			if ( node->Data()->type == Ware_Custom && !id.Compare(node->Data()->id) ) continue;
6763
			else if ( node->Data()->type != Ware_Custom && node->Data()->pos != pos ) continue;
6764
 
6765
			(*noto) = node->Data()->notority;
6766
			return true;
6767
		}
6768
	}
6769
	return false;
6770
}
6771
 
6772
void CPackages::_removeWareOverride(enum WareTypes type, int pos, const Utils::String &id)
6773
{
6774
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
6775
		if ( node->Data()->type == type ) {
6776
			if ( node->Data()->type == Ware_Custom && !id.Compare(node->Data()->id) ) continue;
6777
			else if ( node->Data()->type != Ware_Custom && node->Data()->pos != pos ) continue;
6778
			m_lWarePrices.remove(node);
6779
			break;
6780
		}
6781
	}
6782
}
6783
 
6784
int CPackages::empOveridePrice(int id)
6785
{
6786
	return _warePriceOverride(Ware_EMP, id, Utils::String::Null()); 
6787
}
6788
 
6789
bool CPackages::empOverideNoto(int id, int *noto)
6790
{
6791
	return _wareNotoOverride(Ware_EMP, id, Utils::String::Null(), noto);
6792
}
6793
 
6794
int CPackages::builtInWareOveridePrice(int id)
6795
{
6796
	return _warePriceOverride(Ware_BuiltIn, id, Utils::String::Null()); 
6797
}
6798
 
6799
bool CPackages::builtInWareOverideNoto(int id, int *noto)
6800
{
6801
	return _wareNotoOverride(Ware_BuiltIn, id, Utils::String::Null(), noto);
6802
}
6803
 
6804
int CPackages::customWareOveridePrice(const Utils::String &id)
6805
{
6806
	return _warePriceOverride(Ware_Custom, 0, id); 
6807
}
6808
 
6809
bool CPackages::customWareOverideNoto(const Utils::String &id, int *noto)
6810
{
6811
	return _wareNotoOverride(Ware_Custom, 0, id, noto);
6812
}
6813
 
6814
void CPackages::removeEmpOverride(int pos)
6815
{
6816
	_removeWareOverride(Ware_EMP, pos, Utils::String::Null());
6817
}
6818
 
6819
void CPackages::removeBuiltinWareOverride(int pos)
6820
{
6821
	_removeWareOverride(Ware_BuiltIn, pos, Utils::String::Null());
6822
}
6823
 
6824
void CPackages::removeCustomWareOverride(const Utils::String &id)
6825
{
6826
	_removeWareOverride(Ware_Custom, 0, id);
6827
}
6828
 
6829
 
1 cycrow 6830
bool CPackages::ReadGlobals(CyStringList &globals)
6831
{
6832
	int e = ExtractGameFile("types/Globals.pck", m_sTempDir);
6833
	if ( e )
6834
	{
6835
		CFileIO File(((e == -1) ? "." : m_sTempDir) + "/Globals.txt");
52 cycrow 6836
		if ( File.exists() )
1 cycrow 6837
		{
6838
			CyStringList *lines = File.ReadLinesStr();
6839
			if ( lines )
6840
			{
6841
				int entries = -1;
6842
				for ( SStringList *str = lines->Head(); str; str = str->next )
6843
				{
6844
					str->str.RemoveChar('\r');
6845
					str->str.RemoveChar(9);
6846
					str->str.RemoveFirstSpace();
6847
 
6848
					if ( str->str.Empty() )
6849
						continue;
6850
					if ( str->str[0] == '/' )
6851
						continue;
6852
 
6853
					// remove comments
6854
					CyString l = str->str;
6855
					if ( l.IsIn("/") ) 
6856
						l = l.GetToken("/", 1, 1);
6857
 
6858
					if ( entries == -1 )
6859
						entries = l.GetToken(";", 1, 1).ToInt();
6860
					else
6861
						globals.PushBack(l.GetToken(";", 1, 1), l.GetToken(";", 2, 2));
6862
				}
6863
 
6864
				delete lines;
6865
 
6866
				return true;
6867
			}
6868
		}
6869
	}
6870
 
6871
	return false;
6872
}
6873
 
6874
void CPackages::CreateGlobals()
6875
{
6876
	if ( m_lGlobals.Empty() )
6877
		return; // no global settings
6878
 
6879
	CyStringList globals;
6880
	if ( ReadGlobals(globals) )
6881
	{
6882
		// apply out settings
6883
		for ( SStringList *str = m_lGlobals.Head(); str; str = str->next )
6884
		{
6885
			SStringList *found = globals.FindString(str->str);
6886
			if ( found )
6887
				found->data = str->data;
6888
		}
6889
 
6890
		// now write it
6891
		CyStringList writeList;
6892
		for ( SStringList *str = globals.Head(); str; str = str->next )
6893
			writeList.PushBack(str->str + ";" + str->data + ";");
6894
 
6895
		// finally, write the file
6896
		writeList.PushFront(CyString::Number(writeList.Count()) + "; /globals amount", "");
6897
		writeList.PushFront(CyString("// Globals file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2), "");
6898
 
6899
		CFileIO WriteFile(m_sTempDir + "/Globals.txt");
6900
		if ( WriteFile.WriteFile(&writeList) )
6901
		{
6902
			this->PackFile(&WriteFile, "types/Globals.pck");
52 cycrow 6903
			WriteFile.remove();
1 cycrow 6904
		}
6905
	}
6906
}
6907
 
6908
void CPackages::CreateTShips()
6909
{
6910
	// no ships ?
6911
	if ( m_lGameShips.empty() )
6912
		return;
6913
 
6914
	// get the cockpit list to match with ships turrets
6915
	CyStringList Cockpits;
6916
	CyStringList *cockpitList = this->CreateCockpits();
6917
	if ( cockpitList )
6918
	{
6919
		for ( SStringList *str = cockpitList->Head(); str; str = str->next )
6920
		{
6921
			CyString id = str->str.GetToken(";", 19, 19);
6922
			Cockpits.PushBack(id);
6923
		}
6924
 
6925
		delete cockpitList;
6926
	}
6927
 
6928
	CLinkList<SGameShip> shipOverrides;
6929
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6930
	{
6931
		if ( node->Data()->iType != WARETYPE_ADDED || !node->Data()->pPackage )
6932
			continue;		
6933
		if ( !node->Data()->pPackage->IsExistingShip() )
6934
			continue;
6935
		shipOverrides.push_back(node->Data());
6936
	}
6937
 
6938
	// read the existing tships file
6939
	int e = ExtractGameFile("types/TShips.pck", m_sTempDir + "/TShips.txt");
6940
	if ( e )
6941
	{
6942
		int fileType = 51;
6943
		CyStringList tshipsList;
6944
 
6945
		// if we have no buffer, lets create one
6946
		CFileIO File;
6947
		if ( File.Open((e == -1) ? "TShips.txt" : m_sTempDir + "/TShips.txt") )
6948
		{
6949
			int shiptext = SHIPSTARTTEXT;
6950
 
6951
			std::vector<CyString> *lines = File.ReadLines();
6952
			if ( lines )
6953
			{
6954
				int count = -1;
6955
				for ( int j = 0; j < (int)lines->size(); j++ )
6956
				{
6957
					CyString line(lines->at(j));
6958
					if ( line[0] == '/' )
6959
						continue;
6960
					line.RemoveChar('\r');
6961
					line.RemoveChar(9);
6962
					line = line.RemoveFirstSpace();
6963
					line = line.RemoveEndSpace();
6964
					if ( line.Empty() )
6965
						continue;
6966
 
6967
					if ( count == -1 )
6968
					{
6969
						fileType = line.GetToken(";", 1, 1).ToInt();
6970
						count = line.GetToken(";", 2, 2).ToInt();
6971
					}
6972
					else
6973
					{
6974
						if ( line.Right(1) != ";" )
6975
							line += ";";
6976
 
6977
						// check for any ship overrides
6978
						bool added = false;
6979
						if ( !shipOverrides.empty() )
6980
						{
6981
							CShipData shipData;
6982
							if ( shipData.ReadShipData(line) )
6983
							{
6984
								for ( CListNode<SGameShip> *node = shipOverrides.Front(); node; node = node->next() )
6985
								{
6986
									SGameShip *s = node->Data();
14 cycrow 6987
									if ( !s->pPackage->GetShipID().Compare(shipData.sID.ToString()) )
1 cycrow 6988
										continue;
6989
									s->iText = shiptext;
6990
									if ( !s->pPackage->GetOriginalDescription() )
6991
										shiptext += 2;
6992
									s->iPos = tshipsList.Count();
6993
									added = true;
39 cycrow 6994
									tshipsList.PushBack(CyString(s->pPackage->FormatShipData(&Cockpits, &s->iText, m_iGame)));
1 cycrow 6995
									shipOverrides.remove(node);
6996
									break;
6997
								}
6998
							}
6999
						}
7000
 
7001
						if ( !added )
7002
							tshipsList.PushBack(line);
7003
						--count;
7004
						if ( count < 0 )
7005
							break;
7006
					}
7007
				}
7008
 
7009
				delete lines;
7010
 
7011
			}
7012
 
52 cycrow 7013
			File.remove();
1 cycrow 7014
 
7015
			// assign the ship buffer
7016
			if ( !m_iShipBuffer )
7017
				m_iShipBuffer = tshipsList.Count() + 15;
7018
			// there seems to be too many additional entries, we have no choise but to change the buffer
7019
			else if ( m_iShipBuffer <= tshipsList.Count() )
7020
				m_iShipBuffer = tshipsList.Count() + 15;
7021
 
7022
			CyString bufferStart;
7023
			if ( m_iGame == GAME_X3 )
7024
				bufferStart = "0;0;0;0;0;2;499999;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0.049988;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;4;1;0;0;0;0;0;0;2092;1;1;-1;0;0;1;1;0;1;1;1;0;0;0;;-1;0;0;0;0;0;0;0;0;0;";
7025
			else
7026
				bufferStart = "0;0;0;0;0;SG_SH_M5;499999;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0.049988;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;4;1;0;0;0;0;0;0;OBJ_BEACON;1;1;-1;0;0;1;1;0;1;1;1;0;0;0;;-1;0;0;0;0;0;0;0;0;0;";
7027
			// add the buffers now
7028
			for ( int i = tshipsList.Count(); i < m_iShipBuffer; i++ )
7029
				tshipsList.PushBack(bufferStart + "SHIP_BUFFER;");
7030
 
7031
			// now lets add our tships line
7032
			for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
7033
			{
7034
				SGameShip *s = node->Data();
7035
				if ( s->pPackage && s->pPackage->IsExistingShip() )
7036
					continue;
7037
				s->iPos = tshipsList.Count();
7038
				if ( s->iType == WARETYPE_ADDED && s->pPackage )
7039
				{
7040
					s->iText = shiptext;
7041
					if ( !s->pPackage->GetOriginalDescription() )
7042
						shiptext += 2;
7043
 
39 cycrow 7044
					tshipsList.PushBack(CyString(s->pPackage->FormatShipData(&Cockpits, &s->iText, m_iGame)));
1 cycrow 7045
				}
7046
				else if ( s->iType == WARETYPE_DELETED )
7047
					tshipsList.PushBack(bufferStart + "SHIP_DELETED;");
7048
				else if ( s->iType == WARETYPE_DISABLED )
7049
					tshipsList.PushBack(bufferStart + "SHIP_DISABLED;");
7050
				else
7051
					tshipsList.PushBack(bufferStart + "SHIP_SPACER;");
7052
			}
7053
 
7054
			// finally, write the file
7055
			tshipsList.PushFront(CyString::Number(fileType) + ";" + CyString::Number(tshipsList.Count()) + ";", "");
7056
			tshipsList.PushFront(CyString("// TShips file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2), "");
7057
 
7058
			CFileIO WriteFile(m_sTempDir + "/TShips.txt");
7059
			if ( WriteFile.WriteFile(&tshipsList) )
7060
			{
7061
				this->PackFile(&WriteFile, "types/TShips.pck");
52 cycrow 7062
				WriteFile.remove();
1 cycrow 7063
			}
7064
		}
7065
	}
7066
 
7067
}
7068
 
7069
bool CPackages::PackFile(CyString filename)
7070
{
7071
	// compress the file
7072
	CFileIO File(filename);
7073
	size_t fileSize;
7074
	char *fileData = File.ReadToData(&fileSize);
7075
 
7076
	if ( fileData && fileSize)
7077
	{
7078
		size_t newFileSize;
7079
		unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
7080
		if ( pckData )
7081
		{
7082
			CyString ext = "pck";
7083
			if ( File.CheckFileExtension("bob") )
7084
				ext = "pbb";
7085
			else if ( File.CheckFileExtension("bod") )
7086
				ext = "pbd";
7087
			CFileIO pckFile(File.ChangeFileExtension(ext));
102 cycrow 7088
			if ( !CDirIO(pckFile.dir()).Exists() )
7089
				CDirIO(pckFile.dir()).Create();
1 cycrow 7090
			pckFile.WriteData((char *)pckData, newFileSize);
7091
			return true;
7092
		}
7093
	}
7094
 
7095
	return false;
7096
}
7097
 
7098
bool CPackages::UnPackFile(CyString filename, bool checkxml)
7099
{
7100
	// compress the file
7101
	CFileIO File(filename);
7102
	size_t fileSize;
7103
	char *fileData = File.ReadToData(&fileSize);
7104
 
7105
	if ( fileData && fileSize)
7106
	{
7107
		size_t newFileSize;
96 cycrow 7108
		unsigned char *pckData = UnPCKData((unsigned char *)fileData, fileSize, &newFileSize, false);
7109
		if ( !pckData )
7110
			pckData = UnPCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
7111
 
1 cycrow 7112
		if ( pckData )
7113
		{
7114
			CyString ext = "txt";
7115
			if ( File.CheckFileExtension("pbb") )
7116
				ext = "bob";
7117
			else if ( File.CheckFileExtension("pbd") )
7118
				ext = "bod";
7119
			CFileIO pckFile(File.ChangeFileExtension(ext));
102 cycrow 7120
			if ( !CDirIO(pckFile.dir()).Exists() )
7121
				CDirIO(pckFile.dir()).Create();
1 cycrow 7122
			pckFile.WriteData((char *)pckData, newFileSize);
7123
 
7124
			// check for xml and rename
7125
			if ( checkxml )
7126
			{
7127
				int readmaxlines = 20;
7128
				bool isxml = false;
7129
				do {
52 cycrow 7130
					CyString line = pckFile.readEndOfLine();
1 cycrow 7131
					if ( line.IsIn("<language id=") )
7132
					{
7133
						isxml = true;
7134
						break;
7135
					}
7136
					else if ( line.IsIn("<page id=") )
7137
					{
7138
						isxml = true;
7139
						break;
7140
					}
7141
					else if ( line.IsIn("<?xml") || line.IsIn("<script>") )
7142
					{
7143
						isxml = true;
7144
						break;
7145
					}
7146
					--readmaxlines;
7147
					if ( readmaxlines <= 0 )
7148
						break;
52 cycrow 7149
				} while (pckFile.isOpened());
1 cycrow 7150
 
52 cycrow 7151
				if ( pckFile.isOpened() )
82 cycrow 7152
					pckFile.close();
1 cycrow 7153
 
7154
				if ( isxml )
7155
					pckFile.Rename(pckFile.ChangeFileExtension("xml"));
7156
			}
7157
 
7158
			return true;
7159
		}
7160
	}
7161
 
7162
	return false;
7163
}
7164
 
7165
bool CPackages::PackFile(CFileIO *File, CyString filename)
7166
{
7167
	filename = filename.FindReplace("\\", "/");
7168
	if ( m_iGame == GAME_X3 )
7169
	{
7170
		CCatFile catFile;
7171
		int error = catFile.Open(m_sCurrentDir + "/mods/PluginManager.cat", this->GetAddonDir(), CATREAD_CATDECRYPT, true);
7172
		if ( error == CATERR_NONE || error == CATERR_CREATED )
7173
		{
7174
			// it it wrote ok, remove the old ones
102 cycrow 7175
			if ( !catFile.AppendFile(File->fullFilename(), filename.ToString(), true, true) )
1 cycrow 7176
				return false;
7177
			return true;
7178
		}
7179
	}
7180
	else
7181
	{
7182
		// compress the file
7183
		size_t fileSize;
102 cycrow 7184
		char *fileData = CFileIO(File->fullFilename()).ReadToData(&fileSize);
1 cycrow 7185
 
7186
		if ( fileData && fileSize)
7187
		{
7188
			size_t newFileSize;
7189
			unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
7190
			if ( pckData )
7191
			{
7192
//				if ( !this->GetAddonDir().Empty() && CCatFile::IsAddonDir(filename) )
7193
//					filename = this->GetAddonDir() + "/" + filename;
7194
				CFileIO pckFile(m_sCurrentDir + "/" + filename);
102 cycrow 7195
				if ( !CDirIO(pckFile.dir()).Exists() )
7196
					CDirIO(pckFile.dir()).Create();
1 cycrow 7197
				pckFile.WriteData((char *)pckData, newFileSize);
102 cycrow 7198
				this->AddCreatedFile(pckFile.fullFilename());
1 cycrow 7199
				return true;
7200
			}
7201
		}
7202
	}
7203
 
7204
	return false;
7205
}
7206
 
7207
CyStringList *CPackages::CreateCockpits()
7208
{
7209
	// first check we have any ships
7210
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
7211
		return NULL;
7212
 
7213
	CyStringList *cockpitList = new CyStringList;
7214
 
7215
	// now extract the existing cockpits
7216
	int fileType = 51;
7217
	int e = ExtractGameFile("types/TCockpits.pck", m_sTempDir + "/TCockpits.txt");
7218
	if ( e )
7219
	{
7220
		// read the dummies
7221
		CFileIO File;
7222
		if ( File.Open((e == -1) ? "TCockpits.txt" : m_sTempDir + "/TCockpits.txt") )
7223
		{
7224
			CyStringList *lines = File.ReadLinesStr();
7225
			if ( lines )
7226
			{
7227
				int count = -1;
7228
				for ( SStringList *str = lines->Head(); str; str = str->next )
7229
				{
7230
					CyString line(str->str);
7231
					line.RemoveChar('\r');
7232
					line.RemoveChar(9);
7233
					line = line.RemoveFirstSpace();
7234
					line = line.RemoveEndSpace();
7235
					if ( line.Empty() )
7236
						continue;
7237
					if ( line[0] == '/' )
7238
						continue;
7239
 
7240
					if ( count == -1 )
7241
					{
7242
						fileType = line.GetToken(";", 1, 1).ToInt();
7243
						count = line.GetToken(";", 2, 2).ToInt();
7244
					}
7245
					else
7246
					{
7247
						while ( !line.Empty() )
7248
						{
7249
							CyString data = line.GetToken(";", 1, 19);
7250
							cockpitList->PushBack(data + ";");
7251
							line = line.DelToken(";", 1, 19);
7252
 
7253
							--count;
7254
							if ( count < 1 )
7255
								break;
7256
						}
7257
					}
7258
				}
7259
 
7260
				delete lines;
7261
			}
7262
 
52 cycrow 7263
			File.remove();
1 cycrow 7264
		}
7265
 
7266
		// now add the new ones
7267
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
7268
		{
7269
			SGameShip *s = node->Data();
7270
			if ( s->iType != WARETYPE_ADDED || !s->pPackage )
7271
				continue;
7272
 
7273
			if ( !s->pPackage->AnyCockpits() )
7274
				continue;
7275
 
7276
			for ( CListNode<SCockpit> *cn = s->pPackage->GetCockpits()->Front(); cn; cn = cn->next() )
7277
			{
7278
				bool foundEntry = false;
7279
				CyString cockpitStr = cn->Data()->sCockpit;
7280
				// search for matching game entry
7281
				for ( CListNode<SWeaponMask> *wm = cn->Data()->lWeaponMask.Front(); wm; wm = wm->next() )
7282
				{
7283
					if ( wm->Data()->iGame == (m_iGame - 1) )
7284
					{
7285
						if ( wm->Data()->iMask != -1 )
7286
							cockpitStr = cockpitStr.RepToken(";", 9, CyString::Number(wm->Data()->iMask));
7287
						foundEntry = true;
7288
						break;
7289
					}
7290
				}
39 cycrow 7291
 
7292
				bool found = false;
1 cycrow 7293
				for ( SStringList *str = cockpitList->Head(); str; str = str->next )
7294
				{
39 cycrow 7295
					if ( str->str.GetToken(";", 19, 19).Compare(CyString(cn->Data()->sCockpit.token(";", 19))) )
1 cycrow 7296
					{
7297
						// only replace existing entry if we have sepeperate weapon masks set
7298
						if ( foundEntry )
7299
							str->str = cockpitStr;
7300
						found = true;
7301
						break;
7302
					}
7303
				}
7304
 
7305
				if ( !found )
7306
					cockpitList->PushBack(cockpitStr);
7307
			}
7308
		}
7309
 
7310
		// finally, write the file
7311
		cockpitList->PushFront(CyString::Number(fileType) + ";" + CyString::Number(cockpitList->Count()) + ";", "");
7312
		cockpitList->PushFront(CyString("// TCockpits file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2), "");
7313
 
7314
		CFileIO WriteFile(m_sTempDir + "/TCockpits.txt");
7315
		if ( WriteFile.WriteFile(cockpitList) )
7316
		{
7317
			this->PackFile(&WriteFile, "types\\TCockpits.pck");
52 cycrow 7318
			WriteFile.remove();
1 cycrow 7319
		}
7320
 
7321
		// remove those entrys
7322
		cockpitList->PopFront();
7323
		cockpitList->PopFront();
7324
	}
7325
 
7326
	return cockpitList;
7327
}
7328
 
7329
CBaseFile *CPackages::FindScriptByAuthor(CyString author, CBaseFile *prev)
7330
{
7331
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
7332
	{
7333
		CBaseFile *p = node->Data();
7334
		if ( prev )
7335
		{
7336
			if ( p == prev )
7337
				prev = NULL;
7338
			continue;
7339
		}
50 cycrow 7340
		if ( p->author().Compare(author.ToString()) )
1 cycrow 7341
			return p;
7342
	}
7343
 
7344
	return NULL;
7345
}
7346
 
7347
CBaseFile *CPackages::LoadPackagerScript(CyString filename, int compression, CyString (*askFunc)(CyString), CyStringList *malformedLines, CyStringList *unknownCommands, CyStringList *variables)
7348
{
7349
	// check the file exists
98 cycrow 7350
	if ( !CFileIO::Exists(filename.ToString()) )
1 cycrow 7351
		return NULL;
7352
 
7353
	// read all the lines
7354
	CFileIO File(filename);
98 cycrow 7355
	if ( !File.startRead() ) 
1 cycrow 7356
		return NULL;
7357
 
98 cycrow 7358
	Utils::CStringList fileData;
7359
 
7360
	int iLine = 0;
7361
 
1 cycrow 7362
	CBaseFile *package = NULL;
7363
 
98 cycrow 7364
	while(!File.atEnd()) {
7365
		// read the next line in the file
7366
		Utils::String line = File.readEndOfLine();
1 cycrow 7367
 
98 cycrow 7368
		// filter out any characters we dont really want
7369
		line.removeChar("\t\r");
7370
		line.removeFirstSpace();
1 cycrow 7371
 
98 cycrow 7372
		if ( line.empty() ) continue;
1 cycrow 7373
 
98 cycrow 7374
		// check for any comments (so we can ignore them)
7375
		if ( line.left(2).Compare("//") || line[0] == '#' ) continue;
1 cycrow 7376
 
98 cycrow 7377
		++iLine;
7378
 
1 cycrow 7379
		// all commands start with a keyword followed by a colon, if one doesn't exist, it cant be a valid line
98 cycrow 7380
		if ( !line.isin(':') )
1 cycrow 7381
		{
7382
			// there are some exeptions, and these are one word entrys only
98 cycrow 7383
			line.removeEndSpace();
7384
			if ( line.isin(" ") )
1 cycrow 7385
			{
7386
				if ( malformedLines )
98 cycrow 7387
					malformedLines->PushBack(CyString(line), CyString::Number(iLine));
1 cycrow 7388
				continue;
7389
			}
7390
		}
7391
 
7392
		// check for the type line
98 cycrow 7393
		if ( !package && line.token(":", 1).Compare("FileType") )
1 cycrow 7394
		{
98 cycrow 7395
			Utils::String sFileType = line.tokens(":", 2).removeFirstSpace();
1 cycrow 7396
			if ( sFileType.Compare("Ship") )
7397
				package = new CXspFile();
7398
			else if ( sFileType.Compare("Script") )
7399
				package = new CSpkFile();
7400
			else if ( sFileType.Compare("Base") )
7401
				package = new CBaseFile();
98 cycrow 7402
			continue;
1 cycrow 7403
		}
7404
 
98 cycrow 7405
		fileData.pushBack(line, Utils::String::Number(iLine));
1 cycrow 7406
	}
7407
 
7408
	// assume its a script if no type is set (all old versions are scripts)
7409
	if ( !package )
7410
		package = new CSpkFile();
7411
 
7412
	if ( compression != -1 )
7413
		package->SetDataCompression(compression);
7414
 
7415
	CyString ftpaddr;
7416
	CyString ftpuser;
7417
	CyString ftppass;
7418
	CyString ftpdir;
98 cycrow 7419
	Utils::String sMainGame;
7420
	Utils::CStringList otherGames;
7421
 
1 cycrow 7422
	// now lets read the rest of the day
7423
	CyStringList listVaribles;
98 cycrow 7424
	for ( Utils::SStringList *line = fileData.First(); line; line = fileData.Next() )
1 cycrow 7425
	{
98 cycrow 7426
		Utils::String cmd = line->str.token(":", 1);
7427
		Utils::String rest = line->str.tokens(":", 2).removeFirstSpace();
1 cycrow 7428
 
98 cycrow 7429
		if ( cmd.Compare("Varible") || cmd.Compare("Variable") )
7430
			listVaribles.PushBack(CyString(rest.token(" ", 1)), CyString(rest.tokens(" ", 2)), true);
1 cycrow 7431
		else
7432
		{
7433
			// replace variables
98 cycrow 7434
			if ( rest.isin("$") )
1 cycrow 7435
			{
7436
				for ( SStringList *strVar = listVaribles.Head(); strVar; strVar = strVar->next )
7437
				{
98 cycrow 7438
					if ( rest.isin(strVar->str.ToString()) )
7439
						rest = rest.findReplace(strVar->str.ToString(), strVar->data.ToString());
1 cycrow 7440
				}
7441
 
7442
				if ( variables )
7443
				{
7444
					for ( SStringList *strVar = variables->Head(); strVar; strVar = strVar->next )
7445
					{
98 cycrow 7446
						if ( rest.isin(strVar->str.ToString()) )
7447
							rest = rest.findReplace(strVar->str.ToString(), strVar->data.ToString());
1 cycrow 7448
					}
7449
				}
7450
			}
7451
 
7452
			//check for the built in varibles
98 cycrow 7453
			if ( rest.isin("$ASK") )
1 cycrow 7454
			{
98 cycrow 7455
				Utils::String replace = "$ASK";
7456
				Utils::String result;
1 cycrow 7457
 
7458
				if ( askFunc )
98 cycrow 7459
					result = askFunc(CyString(cmd)).ToString();
1 cycrow 7460
 
98 cycrow 7461
				if ( rest.isin("$ASK(") )
1 cycrow 7462
				{
98 cycrow 7463
					replace = rest.tokens("$ASK(", 2).token(")", 1);
7464
					if ( result.empty() )
1 cycrow 7465
						result = replace;
98 cycrow 7466
					replace = "$ASK(" + replace + ")";
1 cycrow 7467
				}
7468
 
98 cycrow 7469
				if ( !result.empty() )
7470
					rest = rest.findReplace(replace, result);
1 cycrow 7471
			}
7472
			// todays date
98 cycrow 7473
			if ( rest.isin("$DATE") )
1 cycrow 7474
			{
7475
				time_t now;
7476
				time(&now);
7477
				struct tm *timeinfo = localtime(&now);
98 cycrow 7478
				Utils::String result = Utils::String::Number(timeinfo->tm_mday) + "." + Utils::String::Number(timeinfo->tm_mon + 1) + "." + Utils::String::Number(timeinfo->tm_year + 1900);
7479
				if ( !result.empty() )
7480
					rest = rest.findReplace("$DATE", result);
1 cycrow 7481
			}
7482
			// mydocuments
98 cycrow 7483
			if ( rest.isin("$MYDOCUMENTS") )
1 cycrow 7484
			{
7485
				if ( !m_sMyDoc.Empty() )
98 cycrow 7486
					rest = rest.findReplace("$MYDOCUMENTS", m_sMyDoc.ToString());
1 cycrow 7487
			}
7488
 
7489
			// current path
98 cycrow 7490
			if ( rest.isin("$PATH") )
1 cycrow 7491
			{
102 cycrow 7492
				Utils::String currentDir = CFileIO(filename).dir();
98 cycrow 7493
				if ( !currentDir.empty() )
7494
					rest = rest.findReplace("$PATH", currentDir);
1 cycrow 7495
			}
7496
 
7497
			// now parse the rest of the values
98 cycrow 7498
			if ( cmd.Compare("FtpUpload") )
7499
				ftpaddr = rest.token(" ", 1) + ":" + rest.token(" ", 2);
7500
			else if ( cmd.Compare("FtpUser") )
1 cycrow 7501
				ftpuser = rest;
98 cycrow 7502
			else if ( cmd.Compare("FtpPass") )
1 cycrow 7503
				ftppass = rest;
98 cycrow 7504
			else if ( cmd.Compare("FtpDir") )
1 cycrow 7505
				ftpdir = rest;
98 cycrow 7506
			else if ( cmd.Compare("MultiGames") ) {
7507
				sMainGame = rest.token(" ", 1);
7508
				otherGames.tokenise(rest.tokens(" ", 2), " ");
7509
			}
7510
			else if ( !package->LoadPackageData(cmd, rest, sMainGame, otherGames) )
1 cycrow 7511
			{
7512
				if ( unknownCommands )
98 cycrow 7513
					unknownCommands->PushBack(CyString(cmd), CyString(rest));
1 cycrow 7514
			}
7515
		}
7516
	}
7517
 
50 cycrow 7518
	if ( package->filename().empty() )
98 cycrow 7519
		package->LoadPackageData("AutoSave", "$AUTOSAVE", sMainGame, otherGames);
1 cycrow 7520
 
7521
	if ( !ftpaddr.Empty() )
7522
	{
7523
		if ( !ftpuser.Empty() )
7524
		{
7525
			if ( !ftppass.Empty() )
7526
				ftpaddr = ftpuser + ":" + ftppass + "@" + ftpaddr;
7527
			else
7528
				ftpaddr = ftpuser + "@" + ftpaddr;
7529
		}
7530
 
7531
		if ( !ftpdir.Empty() )
7532
			ftpaddr += ftpdir;
7533
 
7534
		package->SetFtpAddr(ftpaddr);
7535
	}
7536
 
7537
	return package;
7538
}
7539
 
7540
CyString CPackages::GetLanguageName()
7541
{
7542
	return CPackages::ConvertLanguage(m_iLanguage);
7543
}
7544
 
7545
CyString CPackages::ConvertLanguage(int lang)
7546
{
7547
	switch ( lang )
7548
	{
7549
		case 44:
7550
			return "English";
7551
		case 49:
7552
			return "German";
7553
		case 7:
7554
			return "Russian";
7555
		case 33:
7556
			return "French";
7557
		case 30:
7558
			return "Greek";
7559
		case 31:
7560
			return "Dutch";
7561
		case 32:
7562
			return "Belgian";
7563
		case 34:
7564
			return "Spanish";
7565
		case 36:
7566
			return "Hungarian";
7567
		case 39:
7568
			return "Italian";
7569
		case 40:
7570
			return "Romanian";
7571
		case 41:
7572
			return "Swiss";
7573
		case 42:
7574
			return "Czech";
7575
		case 43:
7576
			return "Austrian";
7577
		case 45:
7578
			return "Danish";
7579
		case 46:
7580
			return "Swedish";
7581
		case 47:
7582
			return "Norweigen";
7583
		case 48:
7584
			return "Polish";
7585
	}
7586
 
7587
	return CyString::Number(lang);
7588
}
7589
 
7590
bool CPackages::CheckAccessRights(CyString dir)
7591
{
7592
	if ( dir.Empty() )
7593
		dir = m_sCurrentDir;
7594
 
7595
	// write a file, then read the contents
7596
	CFileIO File(dir + "/accessrightscheck.dat");
7597
 
7598
	// check if file exists and remove it
52 cycrow 7599
	if ( File.exists() )
1 cycrow 7600
	{
7601
		// if we cant remove it, we dont have enough rights
52 cycrow 7602
		if ( !File.remove() )
1 cycrow 7603
			return false;
7604
 
7605
		// if its still there, we dont have enough rights
52 cycrow 7606
		if ( File.exists() )
1 cycrow 7607
			return false;
7608
	}
7609
 
7610
	// now create the file
82 cycrow 7611
	if ( !File.writeString("testing access rights") )
1 cycrow 7612
		return false;
7613
 
7614
	// now check it exists
52 cycrow 7615
	if ( !File.exists() )
1 cycrow 7616
		return false;
7617
 
7618
	// now read the file for the correct contents
7619
	CyStringList *lines = File.ReadLinesStr();
7620
	if ( !lines )
7621
		return false;
7622
 
7623
	// check that one of the lines is correct
7624
	for ( SStringList *s = lines->Head(); s; s = s->next )
7625
	{
7626
		if ( s->str == "testing access rights" )
7627
		{
7628
			delete lines;
7629
			return true;
7630
		}
7631
	}
7632
 
7633
	delete lines;
7634
 
7635
	return false;
7636
}
7637
 
7638
bool CPackages::LoadShipData(CyString file, CyStringList *list)
7639
{
7640
	CFileIO File;
7641
	bool deleteFile = false;
7642
 
7643
	// load from cat file
7644
	if ( CFileIO(file).CheckFileExtension("cat") )
7645
	{
7646
		CCatFile cat;
7647
		if ( cat.Open(file, this->GetAddonDir(), CATREAD_CATDECRYPT, false) != CATERR_NONE )
7648
			return false;
7649
 
7650
		if ( !cat.ExtractFile("types\\TShips.pck", m_sTempDir + "/tships.txt") )
7651
			return false;
7652
 
7653
		File.Open(m_sTempDir + "/tships.txt");
7654
		deleteFile = true;
7655
	}
7656
	// otherwise its a normal file
7657
	else if ( CFileIO(file).CheckFileExtension("pck") )
7658
	{
7659
		C_File f(file);
7660
		if ( !f.ReadFromFile() )
7661
			return false;
7662
		f.UnPCKFile();
7663
 
7664
		f.SetFilename(m_sTempDir + "/tships.txt");
7665
		if ( !f.WriteFilePointer() )
7666
			return false;
7667
 
7668
		File.Open(m_sTempDir + "/tships.txt");
7669
		deleteFile = true;
7670
	}
7671
	else
7672
		File.Open(file);
7673
 
52 cycrow 7674
	if ( !File.exists() )
1 cycrow 7675
		return false;
7676
 
7677
	bool ret = false;
7678
	CyStringList *lines = File.ReadLinesStr();
7679
	if ( lines )
7680
	{
7681
		bool readFirst = false;
7682
		for ( SStringList *str = lines->Head(); str; str = str->next )
7683
		{
7684
			if ( str->str.Empty() )
7685
				continue;
7686
			str->str.RemoveChar('\r');
7687
			str->str.RemoveChar(9);
7688
			str->str.RemoveFirstSpace();
7689
			if ( str->str.Empty() )
7690
				continue;
7691
			if ( str->str[0] == '/' || str->str[0] == '#' )
7692
				continue;
7693
 
7694
			if ( !readFirst )
7695
				readFirst = true;
7696
			else
7697
			{
7698
				CyString t = str->str.GetToken(";", -2);
7699
				while ( t.Right(1) == ";" )
7700
					t.Truncate((int)t.Length() - 1);
7701
				list->PushBack(t, str->str);
7702
			}
7703
		}
7704
 
7705
		delete lines;
7706
		ret = true;
7707
	}
7708
 
7709
	if ( deleteFile )
52 cycrow 7710
		File.remove();
1 cycrow 7711
 
7712
	return ret;
7713
}
7714
 
7715
CyString CPackages::ReadShipData(CyString file, CyString id)
7716
{
7717
	CyStringList *list = this->LoadShipData(file);
7718
	if ( !list )
7719
		return NullString;
7720
 
7721
	CShipData data;
7722
	for ( SStringList *str = list->Head(); str; str = str->next )
7723
	{
7724
		if ( str->str.Compare(id) )
7725
		{
7726
			delete list;
7727
			return str->data;
7728
		}
7729
	}
7730
 
7731
	delete list;
7732
	return NullString;
7733
}
7734
 
7735
CyStringList *CPackages::LoadShipData(CyString file)
7736
{
7737
	CyStringList *list = new CyStringList;
7738
	if ( this->LoadShipData(file, list) )
7739
		return list;
7740
 
7741
	delete list;
7742
	return NULL;
7743
}
7744
 
7745
bool CPackages::ReadTextPage(CyString file, CyStringList *list, bool search, int page)
7746
{
7747
	CFileIO File;
7748
	bool deleteFile = false;
7749
 
7750
	// read all text files from mod
7751
	if ( CFileIO(file).CheckFileExtension("cat") )
7752
	{
7753
		bool done = false;
7754
 
7755
		CCatFile cat;
7756
		if ( cat.Open(file, this->GetAddonDir(), CATREAD_CATDECRYPT, false) != CATERR_NONE )
7757
			return false;
7758
 
7759
		// extract 1 at a time
7760
		for ( int i = 0; i < cat.GetNumFiles(); i++ )
7761
		{
7762
			SInCatFile *f = cat.GetFile(i);
7763
			CyString sF = f->sFile;
7764
			// is a text file
7765
			sF = sF.FindReplace("\\", "/");
7766
			if ( !sF.GetToken("/", 1, 1).Compare("t") )
7767
				continue;
7768
 
57 cycrow 7769
			CyString baseFile = CFileIO(sF.ToString()).baseName();
1 cycrow 7770
			// check language
7771
			int lang = 0;
7772
			if ( baseFile.FindPos("-L") != -1 ) // new language file
7773
				lang = baseFile.Right(3).ToInt();
7774
			else
7775
			{
7776
				baseFile.Truncate((int)baseFile.Length() - 4);
7777
				lang = baseFile.ToInt();
7778
			}
7779
 
7780
			if ( lang != m_iLanguage )
7781
				continue;
7782
 
7783
			// now extract and parse
57 cycrow 7784
			if ( cat.ExtractFile(f->sFile, m_sTempDir + "/" + CFileIO(f->sFile).baseName() + ".xml") )
1 cycrow 7785
			{
57 cycrow 7786
				if ( this->ReadTextPage(m_sTempDir + "/" + CFileIO(f->sFile).baseName() + ".xml", list, search, page) )
1 cycrow 7787
					done = true;
7788
			}
7789
		}
7790
 
7791
		return done;
7792
	}
7793
	// otherwise its a normal file
7794
	else if ( CFileIO(file).CheckFileExtension("pck") )
7795
	{
7796
		C_File f(file);
7797
		if ( !f.ReadFromFile() )
7798
			return false;
7799
		f.UnPCKFile();
7800
 
7801
		f.SetFilename(m_sTempDir + "/textfile.xml");
7802
		if ( !f.WriteFilePointer() )
7803
			return false;
7804
 
7805
		File.Open(m_sTempDir + "/textfile.xml");
7806
		deleteFile = true;
7807
	}
7808
	else
7809
		File.Open(file);
7810
 
52 cycrow 7811
	if ( !File.exists() )
1 cycrow 7812
		return false;
7813
 
7814
	// open and read file
7815
	CyStringList *lines = File.ReadLinesStr();
7816
	if ( !lines )
7817
		return false;
7818
 
7819
	bool inPage = false;
7820
	for ( SStringList *str = lines->Head(); str; str = str->next )
7821
	{
7822
		// search for page
7823
		if ( !inPage )
7824
		{
7825
			if ( str->str.FindPos("<page") > -1 )
7826
			{
7827
				// find the page id
7828
				int pos = str->str.FindPos("\"");
7829
				if ( pos > -1 )
7830
				{
7831
					int endpos = str->str.FindPos("\"", pos + 1);
7832
					if ( endpos > -1 )
7833
					{
7834
						CyString p = str->str.Mid(pos + 2, endpos - pos - 1);
7835
						if ( p.Length() > 4 )
7836
							p = p.Right(4);
7837
						int checkPage = p.ToInt();
7838
						if ( checkPage == page )
7839
							inPage = true;
7840
					}
7841
				}
7842
			}
7843
 
7844
		}
7845
		// add each id
7846
		else
7847
		{
7848
			if ( str->str.FindPos("</page") > -1 )
7849
				break;
7850
 
7851
			if ( str->str.FindPos("<t id") > -1 )
7852
			{
7853
				int pos = str->str.FindPos("\"");
7854
				if ( pos > -1 )
7855
				{
7856
					int endpos = str->str.FindPos("\"", pos + 1);
7857
					if ( endpos > -1 )
7858
					{
7859
						int id = str->str.Mid(pos + 2, endpos - pos - 1).ToInt();
7860
						pos = str->str.FindPos(">", endpos);
7861
						if ( pos > -1 )
7862
						{
7863
							++pos;
7864
							endpos = str->str.FindPos("</", pos);
7865
							if ( endpos > -1 )
7866
							{
7867
								CyString text = str->str.Mid(pos + 1, endpos - pos);
7868
								while ( text.FindPos('(') != -1 && text.FindPos(')') != -1 )
7869
								{
7870
									int s = text.FindPos('(');
7871
									text = text.Erase(s, text.FindPos(')') - s + 1);
7872
								}
7873
								list->PushBack(CyString::Number(id), text, search);
7874
							}
7875
						}
7876
					}
7877
				}
7878
			}
7879
		}
7880
	}
7881
 
7882
	delete lines;
7883
 
7884
	return true;
7885
}
7886
 
7887
CyStringList *CPackages::ReadTextPage(CyString file, bool search, int page)
7888
{
7889
	CyStringList *list = new CyStringList;
7890
	if ( this->ReadTextPage(file, list, search, page) )
7891
		return list;
7892
 
7893
	delete list;
7894
	return NULL;
7895
}
7896
 
7897
int CPackages::AdjustFileType(CyString file, int filetype)
7898
{
7899
	CFileIO File(file);
7900
	CyString dir = File.GetDirIO().TopDir();
57 cycrow 7901
	CyString basename = File.baseName();
1 cycrow 7902
 
7903
	// mod files
7904
	if ( File.CheckFileExtension("cat") || File.CheckFileExtension("dat") )
7905
		return FILETYPE_MOD;
7906
	// check for text files
7907
	if ( File.GetFilename().IsIn("-L") && File.GetFilename().Left(4).ToInt() )
7908
		return FILETYPE_TEXT;
57 cycrow 7909
	if ( File.baseName().Compare("conversations") )
43 cycrow 7910
		return FILETYPE_TEXT;
1 cycrow 7911
	if ( basename.Length() <= 4 && basename.IsNumber() && (File.CheckFileExtension("xml") || File.CheckFileExtension("pck")) )
7912
		return FILETYPE_TEXT;
7913
	// X2/X3 text file
57 cycrow 7914
	if ( basename.Length() >= 5 && basename.Length() <= 8 && ((int)File.baseName()) )
1 cycrow 7915
		return FILETYPE_TEXT;
7916
	if ( filetype == FILETYPE_TEXT ) // should no longer be anything text
7917
		return FILETYPE_SCRIPT;
7918
	if ( File.CheckFileExtension("wav") || File.CheckFileExtension("mp3") )
7919
		return FILETYPE_SOUND;
7920
	return filetype;
7921
}
7922
 
7923
void CPackages::RemoveFailedFiles()
7924
{
7925
	for ( SStringList *str = m_lNonRemovedFiles.Head(); str; str = str->next )
7926
	{
52 cycrow 7927
		if ( CFileIO::Remove(str->str.ToString()) )
1 cycrow 7928
			str->remove = true;
7929
	}
7930
 
7931
	m_lNonRemovedFiles.RemoveMarked();
7932
}
7933
 
35 cycrow 7934
CXspFile *CPackages::extractShip(const Utils::String &sCatFile, const Utils::String &sId, CProgressInfo *progress)
1 cycrow 7935
{
35 cycrow 7936
	CVirtualFileSystem *pVfs = new CVirtualFileSystem();
7937
	if ( !pVfs->addMod(sCatFile) ) {
7938
		delete pVfs;
1 cycrow 7939
		return NULL;
35 cycrow 7940
	}
1 cycrow 7941
 
7942
	CXspFile *newShip = new CXspFile;
35 cycrow 7943
	if ( !newShip->extractShip(pVfs, sId, progress) ) {
1 cycrow 7944
		delete newShip;
35 cycrow 7945
		newShip = NULL;
1 cycrow 7946
	}
7947
 
35 cycrow 7948
	delete pVfs;
7949
 
1 cycrow 7950
	return newShip;
7951
}
7952
 
7953
CyStringList *CPackages::GetMergedFiles(CCatFile *cat1, CCatFile *cat2)
7954
{
7955
	CyStringList *list = new CyStringList;
7956
 
7957
	// first add all files from the "primary" mod
7958
	for ( SInCatFile *f = cat1->GetFiles()->First(); f; f = cat1->GetFiles()->Next() )
7959
		list->PushBack(f->sFile.findreplace("\\", "/"), "1");
7960
 
7961
	// now add the ones from the secondary
7962
	for ( SInCatFile *f = cat2->GetFiles()->First(); f; f = cat2->GetFiles()->Next() )
7963
	{
7964
		CyString sFile = f->sFile.findreplace("\\", "/");
7965
		// if its found on the 2nd list, dont add, just adjust the type
7966
		SStringList *found = list->FindString(sFile);
7967
		if ( found )
7968
			found->data = "-1"; // found in both
7969
		else
7970
			list->PushBack(sFile, "2");
7971
	}
7972
 
7973
	return list;
7974
}
7975
 
58 cycrow 7976
bool CPackages::CanWeMerge(const Utils::String &file) const
1 cycrow 7977
{
7978
	return CModDiff::CanBeDiffed(file);
7979
}
7980
 
7981
bool CPackages::NeedToMerge(CyString file)
7982
{
7983
	CyString firstDir = file.GetToken("/", 1, 1);
7984
	if ( firstDir.Compare("t") )
7985
		return true;
7986
	if ( firstDir.Compare("types") )
7987
		return true;
7988
	if ( firstDir.Compare("maps") )
7989
		return true;
7990
 
7991
	return false;
7992
}
7993
 
7994
bool CPackages::MergeMods(CCatFile *mod1, CCatFile *mod2, CyString outFile, CyStringList *cantMerge)
7995
{
7996
	CyStringList *list = this->GetMergedFiles(mod1, mod2);
7997
	if ( !list )
7998
		return false;
7999
 
8000
	CCatFile newCat;
8001
	if ( newCat.Open(outFile, this->GetAddonDir()) != CATERR_CREATED )
8002
		return false;
8003
 
8004
	// add all the files to the new mod first
8005
	CyStringList conflicts;
8006
	for ( SStringList *str = list->Head(); str; str = str->next )
8007
	{
8008
		int status = str->data.ToInt();
8009
		if ( status == 1 )
8010
		{
8011
			if ( !newCat.WriteFromCat(mod1, str->str) )
8012
			{
8013
				if ( cantMerge )
8014
					cantMerge->PushBack(str->str, "1");
8015
			}
8016
		}
8017
		else if ( status == 2 )
8018
		{
8019
			if ( !newCat.WriteFromCat(mod2, str->str) )
8020
			{
8021
				if ( cantMerge )
8022
					cantMerge->PushBack(str->str, "2");
8023
			}
8024
		}
8025
		else if ( status == -1 )
8026
		{
8027
			if ( this->NeedToMerge(str->str) )
8028
			{
58 cycrow 8029
				if ( this->CanWeMerge(str->str.ToString()) )
1 cycrow 8030
					conflicts.PushBack(str->str);
8031
				else if ( cantMerge )
8032
					cantMerge->PushBack(str->str, "-1");
8033
			}
8034
			else
8035
			{
8036
				if ( !newCat.WriteFromCat(mod1, str->str) )
8037
				{
8038
					if ( cantMerge )
8039
						cantMerge->PushBack(str->str, "1");
8040
				}
8041
			}
8042
		}
8043
	}
8044
 
8045
	delete list;
8046
 
8047
	/* 
8048
		Merging Files
8049
 
8050
		* Text Files: Join all text entries into a single file (excluding page 17)
8051
		* Weapons: TBullets and TLaser (grab matching entrys from text files and adjust ids)
8052
	*/
8053
	// new merge the conflicting files
8054
	// first the text files
8055
//	CyStringList *text = this->MergeTextFiles(conflicts, mod1, mod2);
8056
//	delete text;
8057
 
8058
	// write the cat file when we're done
8059
	if ( !newCat.WriteCatFile() )
8060
		return false;
8061
 
8062
	return true;
8063
}
8064
 
8065
/**
8066
 * Gets the file list from a mod that might have compatability problems
8067
 *
8068
 * This includes all types and text files
8069
 *
8070
 * Returns true if it finds any files
8071
 */
8072
bool CPackages::GetModCompatabilityList(C_File *file, CyStringList *list)
8073
{
8074
	// not a valid file
8075
	if ( !file ) return false;
8076
	if ( file->GetFileType() != FILETYPE_MOD ) return false;
8077
	if ( !file->GetFileExt().Compare("cat") ) return false;
8078
 
8079
	// we need to read the file list for the mod
8080
	CCatFile cat;
8081
	if ( cat.Open(file->GetFilePointer(), this->GetAddonDir(), CATREAD_JUSTCONTENTS, false) == CATERR_NONE )
8082
	{
8083
		for ( int i = 0; i < cat.GetNumFiles(); i++ )
8084
		{
8085
			SInCatFile *f = cat.GetFile(i);
8086
			CyString filename = f->sFile;
8087
			filename = filename.FindReplace("\\", "/");
50 cycrow 8088
			bool found = false;
1 cycrow 8089
			if ( filename.Left(2).Compare("t/") || filename.Left(6).Compare("types/") )
50 cycrow 8090
				found = true;
8091
			else if ( filename.Left(8).Compare("addon/t/") || filename.Left(12).Compare("addon/types/") )
8092
				found = true;
8093
 
8094
			if ( found ) {
1 cycrow 8095
				if ( list )
8096
					list->PushBack(filename, CyString(f->lSize));
8097
				else
8098
					return true;
8099
			}
8100
		}
8101
	}
8102
 
8103
	if ( list && !list->Empty() )
8104
		return true;
8105
 
8106
	return false;
8107
}
8108
 
8109
/**
8110
 * Gets the files that are not compatable with each other
8111
 *
8112
 * Returns true if theres any files that are not compatable
8113
 *
8114
 * If list is specified, fills up with all files that were found
8115
 */
8116
bool CPackages::CheckCompatabilityBetweenModFiles(C_File *from, C_File *to, CyStringList *list)
8117
{
8118
	// not a valid file
8119
	if ( !from || !to ) return false;
8120
	if ( from->GetFileType() != FILETYPE_MOD ) return false;
8121
	if ( to->GetFileType() != FILETYPE_MOD ) return false;
8122
	if ( !from->GetFileExt().Compare("cat") ) return false;
8123
	if ( !to->GetFileExt().Compare("cat") ) return false;
8124
 
8125
	// get file lists from each file
8126
	CyStringList fromList;
8127
	if ( GetModCompatabilityList(from, &fromList) )
8128
	{
8129
		CyStringList toList;
8130
		if ( GetModCompatabilityList(to, &toList) )
8131
		{
8132
			// both have files we need to check, compare them
8133
			for ( SStringList *str = fromList.Head(); str; str = str->next )
8134
			{
8135
				CyString fromFile = str->str;
8136
				fromFile = fromFile.FindReplace("\\", "/");
8137
				fromFile = fromFile.FindReplace("//", "/");
8138
				for ( SStringList *toStr = toList.Head(); toStr; toStr = toStr->next )
8139
				{
8140
					CyString toFile = toStr->str;
8141
					toFile = toFile.FindReplace("\\", "/");
8142
					toFile = toFile.FindReplace("//", "/");
8143
					if ( fromFile.Compare(toFile) )
8144
					{
8145
						if ( list )
8146
							list->PushBack(from->GetFilename() + "::" + str->str, to->GetFilename() + "::" + toStr->str);
8147
						else
8148
							return true;
8149
					}
8150
				}
8151
			}
8152
		}
8153
	}
8154
 
8155
	if ( list && !list->Empty() )
8156
		return true;
8157
 
8158
	return false;
8159
}
8160
 
8161
bool CPackages::CheckCompatabilityBetweenMods(CBaseFile *from, CBaseFile *to, CyStringList *list)
8162
{
8163
	if ( !from || !to ) return false;
8164
	if ( !from->IsEnabled() || !to->IsEnabled() ) return false;
8165
	if ( !from->AnyFileType(FILETYPE_MOD) ) return false;
8166
	if ( !to->AnyFileType(FILETYPE_MOD) ) return false;
8167
 
8168
	if ( from == to ) return false; // cant have incompatabilities to itself
8169
 
8170
	int count = 0;
8171
	for ( C_File *f = from->GetFirstFile(FILETYPE_MOD); f; f = from->GetNextFile(f) )
8172
	{
8173
		if ( !f->IsFakePatch() ) continue;
8174
		if ( f->GetFileExt().Compare("dat") ) continue;
8175
 
8176
		for ( C_File *compareFile = to->GetFirstFile(FILETYPE_MOD); compareFile; compareFile = to->GetNextFile(compareFile) )
8177
		{
8178
			if ( compareFile == f ) continue; // same file we're checking against
8179
			if ( !compareFile->IsFakePatch() ) continue;
8180
			if ( compareFile->GetFileExt().Compare("dat") ) continue;
8181
 
8182
			// now we have to files to compare
8183
			if ( CheckCompatabilityBetweenModFiles(f, compareFile, list) )
8184
				++count;
8185
		}
8186
	}
8187
 
8188
	if ( count )
8189
		return true;
8190
 
8191
	return false;
8192
}
8193
 
8194
int CPackages::CheckCompatabilityAgainstPackages(CBaseFile *newFile, CyStringList *list, CLinkList<CBaseFile> *packages)
8195
{
8196
	if ( !newFile->IsEnabled() ) return 0;
8197
	if ( !newFile->AnyFileType(FILETYPE_MOD) ) return 0;
8198
 
8199
	// we need to extract all mod files
8200
	for ( CListNode<C_File> *fNode = newFile->GetFileList()->Front(); fNode; fNode = fNode->next() )
8201
	{
8202
		C_File *f = fNode->Data();
8203
		if ( f->GetFileType() != FILETYPE_MOD ) continue;
8204
		if ( !f->IsFakePatch() ) continue;
8205
		if ( !f->CheckFileExt("cat") ) continue;
8206
 
8207
		if ( newFile->ExtractFile(f, m_sTempDir) )
8208
			f->SetFullDir(m_sTempDir);
8209
	}
8210
 
8211
	// compare mod files against all installed packages
8212
	int count = 0;
8213
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
8214
	{
8215
		if ( !node->Data() ) continue;
8216
		CBaseFile *p = node->Data();
8217
		if ( !p->IsEnabled() ) continue;
8218
		if ( !p->AnyFileType(FILETYPE_MOD) ) continue;
8219
 
8220
		if ( this->IsSamePackage(p, newFile) ) continue; // dont include self
8221
 
8222
		if ( CheckCompatabilityBetweenMods(newFile, p, list) )
8223
		{
8224
			++count;
8225
			if ( packages && !packages->FindData(p) )
8226
				packages->push_back(p);
8227
		}
8228
	}
8229
 
8230
	for ( CListNode<C_File> *fNode = newFile->GetFileList()->Front(); fNode; fNode = fNode->next() )
8231
	{
8232
		C_File *f = fNode->Data();
52 cycrow 8233
		CFileIO::Remove(f->GetFilePointer().ToString());
1 cycrow 8234
		f->SetFullDir("");
8235
	}
8236
 
8237
	return count;
8238
}
8239
 
8240
bool CPackages::IsSamePackage(CBaseFile *p1, CBaseFile *p2)
8241
{
8242
	if ( !p1 || !p2 ) return false;
8243
	if ( p1 == p2 ) return true;
8244
 
50 cycrow 8245
	if ( p1->name().Compare(p2->name()) && p1->author().Compare(p2->author()) )
1 cycrow 8246
		return true;
8247
	return false;
8248
}
8249
 
8250
void CPackages::ApplyFakePatchOrder(CyStringList *list)
8251
{
8252
	if ( !list ) return;
8253
	m_lFakePatchOrder.Clear();
8254
	for ( SStringList *str = list->Head(); str; str = str->next )
8255
		m_lFakePatchOrder.PushBack(str->str, str->data);
8256
}
8257
 
8258
SAvailablePackage *CPackages::CreateAvailablePackageData(CBaseFile *package)
8259
{
8260
	if ( !package ) return NULL;
8261
 
8262
	SAvailablePackage *p = new SAvailablePackage;
8263
 
8264
	for ( CListNode<SGameCompat> *node = package->GetGameCompatabilityList()->Front(); node; node = node->next() ) {
8265
		SGameCompat *gc = new SGameCompat;
8266
		gc->iGame = node->Data()->iGame;
8267
		gc->iVersion = node->Data()->iVersion;
8268
		gc->sVersion = node->Data()->sVersion;
8269
		p->lGames.push_back(gc);
8270
	}
8271
	p->bSigned = package->IsSigned();
46 cycrow 8272
	p->iChanging = package->gameChanging();
8273
	p->iEase = package->easeOfUse();
48 cycrow 8274
	p->iPluginType = package->pluginType();
46 cycrow 8275
	p->iRec = package->recommended();
1 cycrow 8276
	p->iScriptType = -1;
8277
	if ( package->GetType() == TYPE_XSP )
8278
		p->iType = PACKAGETYPE_SHIP;
8279
	else if ( package->IsMod() )
8280
		p->iType = PACKAGETYPE_MOD;
8281
	else 
8282
	{
8283
		p->iType = ((CSpkFile *)package)->GetPackageType();
8284
		p->iScriptType = ((CSpkFile *)package)->GetScriptType();
8285
	}
50 cycrow 8286
	p->sAuthor = package->author();
48 cycrow 8287
	p->sDesc = package->description().findReplace("\n", "::newline::");
50 cycrow 8288
	p->sName = package->name();
8289
	p->sUpdated = package->creationDate();
8290
	p->sVersion = package->version();
8291
	p->sFilename = CFileIO(package->filename()).GetFilename();
1 cycrow 8292
 
8293
	return p;
8294
}
8295
 
8296
CyString CPackages::FormatAvailablePackageData(CBaseFile *package)
8297
{
8298
	SAvailablePackage *p = CPackages::CreateAvailablePackageData(package);
8299
	CyString ret = CPackages::FormatAvailablePackageData(p);
8300
	delete p;
8301
	return ret;
8302
}
8303
 
8304
CyString CPackages::FormatAvailablePackageData(SAvailablePackage *package)
8305
{
8306
	CyString ret = (long)package->iType;
8307
 
8308
	CyString gameCompat;
8309
	for ( CListNode<SGameCompat> *node = package->lGames.Front(); node; node = node->next() ) {
8310
		if ( !gameCompat.Empty() )
8311
			gameCompat += "!";
8312
		gameCompat += CyString::Number(node->Data()->iGame);
8313
	}
8314
 
8315
	if ( gameCompat.Empty() )
8316
		gameCompat = "0";
8317
 
8318
	ret.AddToken("::", gameCompat);
8319
	ret.AddToken("::", package->sName);
8320
	ret.AddToken("::", package->sAuthor);
8321
	ret.AddToken("::", package->sVersion);
8322
	ret.AddToken("::", package->sUpdated);
8323
	ret.AddToken("::", package->sFilename);
8324
	ret.AddToken("::", CyString::Number(package->iEase));
8325
	ret.AddToken("::", CyString::Number(package->iChanging));
8326
	ret.AddToken("::", CyString::Number(package->iRec));
8327
	ret.AddToken("::", CyString::Number(package->iPluginType));
8328
	ret.AddToken("::", CyString::Number(package->iScriptType));
8329
	ret.AddToken("::", (package->bSigned) ? "1" : "0");
8330
	ret.AddToken("::", package->sDesc);
8331
 
8332
	return ret;
8333
}
8334
 
100 cycrow 8335
void CPackages::ParseAvailablePackage(CyString sStr, CyString webaddress)
1 cycrow 8336
{
8337
	// first check game
100 cycrow 8338
	Utils::String str = sStr.ToString();
1 cycrow 8339
 
8340
	int num = 0;
100 cycrow 8341
	Utils::String *tok = str.tokenise("::", &num);
1 cycrow 8342
	if ( !num || !tok ) return;
100 cycrow 8343
	// invalid number of entries?
1 cycrow 8344
	if ( num < 7 ) { CLEANSPLIT(tok, num); return; }
8345
 
8346
	SAvailablePackage *p = new SAvailablePackage;
100 cycrow 8347
	p->iType = tok[0].toLong();
1 cycrow 8348
	p->bSigned = false;
8349
 
100 cycrow 8350
	// theres multiple games, so we need to split it
8351
	if ( m_iGame ) {
8352
		Utils::String sGame = tok[1];
8353
		if ( sGame.isin("!") ) {
8354
			for(int i = 1; i <= sGame.countToken("!"); i++) {
1 cycrow 8355
				SGameCompat *gc = new SGameCompat;
8356
				gc->iVersion = 0;
100 cycrow 8357
				gc->iGame = sGame.token("!", i).toLong();
1 cycrow 8358
				p->lGames.push_back(gc);
8359
			}
8360
		}
100 cycrow 8361
		else {
8362
			SGameCompat *gc = new SGameCompat;
8363
			gc->iVersion = 0;
8364
			gc->iGame = sGame.toLong();
8365
			p->lGames.push_back(gc);
8366
		}
1 cycrow 8367
	}
100 cycrow 8368
 
1 cycrow 8369
	p->sName = tok[2];
8370
	p->sAuthor = tok[3];
8371
	p->sVersion = tok[4];
8372
	p->sUpdated = tok[5];
8373
	p->sFilename = tok[6];
8374
 
8375
	if ( !webaddress.Empty() )
8376
		p->sFilename = webaddress + "/" + p->sFilename;
8377
 
8378
	p->iChanging = p->iEase = p->iPluginType = p->iRec = p->iScriptType = -1;
8379
 
100 cycrow 8380
	// check if we have the extra values
1 cycrow 8381
	if ( num >= 12 )
8382
	{
100 cycrow 8383
		p->iEase = tok[7].toLong();
8384
		p->iChanging = tok[8].toLong();
8385
		p->iRec = tok[9].toLong();
8386
		p->iPluginType = tok[10].toLong();
8387
		p->iScriptType = tok[11].toLong();
1 cycrow 8388
		if ( num > 12 ) {
8389
			if ( num > 13 ) {
100 cycrow 8390
				p->sDesc = tok[13];
8391
				p->bSigned = tok[12].toBool();
1 cycrow 8392
			}
8393
			else
100 cycrow 8394
				p->sDesc = tok[12];
1 cycrow 8395
		}
8396
	}
8397
	else if ( num > 7 )
100 cycrow 8398
		p->sDesc = tok[8];
1 cycrow 8399
 
8400
	if ( !p->sDesc.Empty() )
100 cycrow 8401
		p->sDesc = p->sDesc.FindReplace("::newline::", "\\n");
1 cycrow 8402
 
8403
	AddAvailablePackage(p);
8404
 
8405
	CLEANSPLIT(tok, num);
8406
}
8407
 
8408
SAvailablePackage *CPackages::FindAvailablePackage(CyString &filename)
8409
{
8410
	for ( CListNode<SAvailablePackage> *node = m_lAvailablePackages.Front(); node; node = node->next() )
8411
	{
8412
		if ( node->Data()->sFilename.Compare(filename) )
8413
			return node->Data();
8414
	}
8415
	return NULL;
8416
}
8417
 
8418
bool CPackages::AddAvailablePackage(SAvailablePackage *package)	
8419
{ 
8420
	if ( !package->lGames.empty() ) {
8421
		bool found = false;
8422
		for ( CListNode<SGameCompat> *node = package->lGames.Front(); node; node = node->next() ) {
8423
			if ( !node->Data()->iGame || node->Data()->iGame == m_iGame ) {
8424
				found = true;
8425
				break;
8426
			}
8427
		}
8428
 
8429
		if ( !found )
8430
			return false;
8431
	}
8432
 
8433
	SAvailablePackage *p = FindAvailablePackage(package->sFilename);
8434
	if ( p )
8435
		m_lAvailablePackages.remove(p);
8436
	m_lAvailablePackages.push_back(package); 
8437
 
8438
	return true;
8439
}
8440
 
8441
bool CPackages::AnyAvailablePackages(int type)
8442
{
8443
	if ( type == -1 ) return !m_lAvailablePackages.empty();
8444
 
8445
	for ( CListNode<SAvailablePackage> *node = m_lAvailablePackages.Front(); node; node = node->next() )
8446
	{
8447
		if ( node->Data()->iType == type )
8448
			return true;
8449
	}
8450
 
8451
	return false;
8452
}
8453
 
8454
int CPackages::FindAllServers(CyStringList *list)
8455
{
8456
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
8457
	{
49 cycrow 8458
		if ( !node->Data()->webAddress().empty() )
8459
			list->PushBack(CyString(node->Data()->webAddress()), true);
1 cycrow 8460
		if ( node->Data()->AnyWebMirrors() )
8461
		{
8462
			for ( SStringList *str = node->Data()->GetWebMirrors()->Head(); str; str = str->next )
8463
				list->PushBack(str->str, true);
8464
		}
8465
	}
8466
 
76 cycrow 8467
	CFileIO File("data\\web");
8468
 
8469
	if ( File.startRead() ) {
8470
		while(!File.atEnd()) {
8471
			Utils::String line = File.readEndOfLine();
8472
			line.removeChar("\n\r\t ");
8473
			if ( !line.empty() )
8474
				list->PushBack(CyString(line), true);
8475
		}
8476
		File.close();
8477
	}
8478
 
8479
	list->PushBack("http://xpluginmanager.co.uk/tcscripts", true);
8480
	list->PushBack("http://xpluginmanager.co.uk/apscripts", true);
8481
 
1 cycrow 8482
	return list->Count();
8483
}
8484
 
8485
void CPackages::ReadArchiveData(CyString filename, CBaseFile *archive)
8486
{
8487
	size_t size;
8488
	char *data = CFileIO(filename).ReadToData(&size);
8489
	if ( size && data )
8490
		ReadArchiveData(data, size, archive);
8491
}
8492
 
8493
void CPackages::ReadArchiveData(const char *buf, size_t len, CBaseFile *archive)
8494
{
98 cycrow 8495
	Utils::CStringList otherGames;
8496
 
1 cycrow 8497
	CyString data(buf);
8498
	int max;
8499
	CyString *str = data.SplitToken("\n", &max);
8500
	if ( str && max )
8501
	{
8502
		for ( int i = 0; i < max; i++ )
8503
		{
8504
			CyString line = str[i];
8505
			if ( line.Empty() )
8506
				continue;
8507
 
8508
			// filter out any spaces, tabs in front
8509
			line.RemoveChar('\t');
8510
			line.RemoveChar('\r');
8511
			CyString linenospace = line;
8512
			linenospace.RemoveFirstSpace();
8513
			if ( linenospace.Empty() )
8514
				continue;
8515
 
8516
			// check for any comments
8517
			if ( linenospace.Left(2) == "//" )
8518
				continue;
8519
			if ( linenospace[0] == '#' )
8520
				continue;
8521
 
8522
			// all commands start with a keyword followed by a colon, if one doesn't exist, it cant be a valid line
8523
			if ( !line.IsIn(':') )
8524
				continue;
8525
 
8526
			CyString first = line.GetToken(":", 1, 1);
8527
			CyString rest = line.GetToken(":", 2).RemoveFirstSpace();
8528
 
8529
			CyString checkType = first;
8530
			bool shared = false;
8531
			if ( checkType.Left(6).Compare("Shared") )
8532
			{
8533
				checkType = first.Right(-6);
8534
				shared = true;
8535
			}
8536
 
8537
			// now check type name
8538
			int filetype = GetFileTypeFromString(checkType);
8539
			if ( filetype == -1 )
98 cycrow 8540
				archive->LoadPackageData(first.ToString(), rest.ToString(), Utils::String::Null(), otherGames);
1 cycrow 8541
		}
8542
	}
8543
 
8544
	CLEANSPLIT(str, max)
8545
}
8546
 
43 cycrow 8547
CBaseFile *CPackages::_archive_fromRar(CyString filename, bool toInstall )
1 cycrow 8548
{
8549
	// make sure we can open the zip file
8550
	CBaseFile *archive = NULL;
8551
#ifdef _RAR
43 cycrow 8552
	HANDLE hArcData;
8553
	int RHCode,PFCode;
8554
	char CmtBuf[16384];
8555
	struct RARHeaderDataEx HeaderData;
8556
	struct RAROpenArchiveDataEx OpenArchiveData;
1 cycrow 8557
 
43 cycrow 8558
	// find the pluginmanager text to covnert to spkfile
8559
	if ( toInstall ) {
1 cycrow 8560
		memset(&OpenArchiveData,0,sizeof(OpenArchiveData));
8561
		OpenArchiveData.ArcName=(char *)filename.c_str();
8562
		OpenArchiveData.CmtBuf=CmtBuf;
8563
		OpenArchiveData.CmtBufSize=sizeof(CmtBuf);
43 cycrow 8564
		OpenArchiveData.OpenMode=RAR_OM_LIST;
1 cycrow 8565
		hArcData=RAROpenArchiveEx(&OpenArchiveData);
8566
 
43 cycrow 8567
		if (OpenArchiveData.OpenResult!=0) return NULL;
1 cycrow 8568
 
8569
		HeaderData.CmtBuf=NULL;
8570
		memset(&OpenArchiveData.Reserved,0,sizeof(OpenArchiveData.Reserved));
8571
 
43 cycrow 8572
		while ((RHCode=RARReadHeaderEx(hArcData,&HeaderData))==0) {
8573
			if ( CyString(HeaderData.FileName).Compare("pluginmanager.txt") ) {
8574
				toInstall = false;
1 cycrow 8575
				break;
8576
			}
43 cycrow 8577
		}
8578
		RARCloseArchive(hArcData);
8579
	}
1 cycrow 8580
 
43 cycrow 8581
	if ( toInstall )
8582
		archive = new CArchiveFile(); // just installing an archive file
8583
	else
8584
		archive = new CSpkFile(); // converting to a spk file
8585
 
8586
	memset(&OpenArchiveData,0,sizeof(OpenArchiveData));
8587
	OpenArchiveData.ArcName=(char *)filename.c_str();
8588
	OpenArchiveData.CmtBuf=CmtBuf;
8589
	OpenArchiveData.CmtBufSize=sizeof(CmtBuf);
8590
	OpenArchiveData.OpenMode=RAR_OM_EXTRACT;
8591
	OpenArchiveData.UserData=EXTRACT;
8592
	hArcData=RAROpenArchiveEx(&OpenArchiveData);
8593
 
8594
	if (OpenArchiveData.OpenResult!=0) return NULL;
8595
 
8596
	HeaderData.CmtBuf=NULL;
8597
	memset(&OpenArchiveData.Reserved,0,sizeof(OpenArchiveData.Reserved));
8598
 
8599
	bool error = false;
8600
	CyString extractedFile = CDirIO(m_sTempDir).File("extracted.tst").findreplace("/", "\\").findreplace("\\\\", "\\");
8601
	while ((RHCode=RARReadHeaderEx(hArcData,&HeaderData))==0)
8602
	{
8603
		CyString fileName = HeaderData.FileName;
8604
 
8605
		if ( HeaderData.FileAttr == 16 )
8606
			continue;
8607
		wchar_t wText[200];
8608
		::MultiByteToWideChar(CP_ACP, NULL, (char *)extractedFile.c_str(), -1, wText, extractedFile.Length() + 1);
8609
		PFCode=RARProcessFileW(hArcData, RAR_EXTRACT, NULL, NULL);
8610
		if (PFCode!=0)
8611
		{
8612
			error = true;
8613
			break;
8614
		}
8615
 
8616
		CFileIO File(fileName);
52 cycrow 8617
		if ( File.exists() )
43 cycrow 8618
		{
8619
			if ( fileName.Compare("pluginmanager.txt") )
102 cycrow 8620
				this->ReadArchiveData(File.fullFilename(), archive);
43 cycrow 8621
			else
1 cycrow 8622
			{
43 cycrow 8623
				CyString extradir;
8624
				int type = SPK::GetAutomaticFiletype(fileName, &extradir, true);
8625
				// check for special file types
8626
				C_File *f = NULL;
1 cycrow 8627
 
43 cycrow 8628
				if ( type == FILETYPE_SCRIPT_UNINSTALL ) {
45 cycrow 8629
					f = archive->AddFile(CFileIO(fileName).GetFilename(), "", FILETYPE_SCRIPT);
43 cycrow 8630
					if ( f ) {
102 cycrow 8631
						f->ReadFromFile(File.fullFilename());
17 cycrow 8632
					}
43 cycrow 8633
					type = FILETYPE_UNINSTALL;
1 cycrow 8634
				}
8635
 
43 cycrow 8636
				if ( type == -1 )
102 cycrow 8637
					f = archive->AddFile(CFileIO(fileName).filename(), CFileIO(fileName).dir(), FILETYPE_EXTRA);
43 cycrow 8638
				else
102 cycrow 8639
					f = archive->AddFile(CFileIO(fileName).filename(), extradir, type);
8640
				f->ReadFromFile(File.fullFilename());
1 cycrow 8641
			}
43 cycrow 8642
 
52 cycrow 8643
			File.remove();
1 cycrow 8644
		}
43 cycrow 8645
	}
1 cycrow 8646
 
43 cycrow 8647
	RARCloseArchive(hArcData);
1 cycrow 8648
 
43 cycrow 8649
	if ( error )
8650
	{
8651
		delete archive;
8652
		archive = NULL;
8653
	}
1 cycrow 8654
#endif
8655
 
43 cycrow 8656
	return archive;
8657
}
1 cycrow 8658
 
43 cycrow 8659
CBaseFile *CPackages::_archive_fromZip(CyString filename, bool toInstall)
8660
{
8661
	CBaseFile *archive = NULL;
1 cycrow 8662
 
43 cycrow 8663
	TCHAR buf[5000];
8664
	wsprintf(buf, L"%hs", filename.c_str());
8665
	HZIP hz = OpenZip(buf, 0);
8666
	if ( !hz ) 
8667
		return NULL;
1 cycrow 8668
 
43 cycrow 8669
	int index;
8670
	// move the files from the zip to the package
8671
	ZIPENTRY ze;
8672
	if ( FindZipItem(hz, L"pluginmanager.txt", true, &index, &ze) == Z_OK )
8673
		toInstall = false;
8674
	CloseZip(hz);
1 cycrow 8675
 
43 cycrow 8676
	hz = OpenZip(buf, 0);
8677
	if ( !hz ) 
8678
		return NULL;
8679
 
8680
	// create the correct package
8681
	if ( toInstall )
8682
		archive = new CArchiveFile(); // just installing an archive file
8683
	else
8684
		archive = new CSpkFile(); // converting to a spk file
8685
 
8686
	GetZipItem(hz, -1, &ze);
8687
	int numitems = ze.index;
8688
 
8689
	bool error = false;
8690
	for ( int zi = 0; zi < numitems; zi++ )
8691
	{
8692
		ZIPENTRY ze;
8693
		if ( GetZipItem(hz, zi, &ze) != Z_OK )
1 cycrow 8694
		{
43 cycrow 8695
			error = true;
8696
			break;
8697
		}
1 cycrow 8698
 
43 cycrow 8699
		if ( ze.attr & FILE_ATTRIBUTE_DIRECTORY )
8700
			continue; // dont do directories
1 cycrow 8701
 
8702
 
43 cycrow 8703
		char *iBuf = new char[ze.unc_size];
8704
		UnzipItem(hz, zi, iBuf, ze.unc_size);
1 cycrow 8705
 
43 cycrow 8706
		CyString Name(ze.name);
1 cycrow 8707
 
43 cycrow 8708
		// if its the data file, dont add it, but extract to get settings from
8709
		if ( Name.Compare("pluginmanager.txt") )
8710
		{
8711
			this->ReadArchiveData(iBuf, ze.unc_size, archive);
8712
			delete[] iBuf;
8713
		}
8714
		else
8715
		{
8716
			CyString extradir;
8717
			int type = SPK::GetAutomaticFiletype(Name, &extradir, true);
1 cycrow 8718
 
43 cycrow 8719
			C_File *f = NULL;
17 cycrow 8720
 
43 cycrow 8721
			// check for special file types
8722
			if ( type == FILETYPE_SCRIPT_UNINSTALL ) {
102 cycrow 8723
				f = archive->AddFile(CFileIO(Name).filename(), CFileIO(Name).dir(), FILETYPE_SCRIPT);
43 cycrow 8724
				if ( f ) {
8725
					f->copyData((const unsigned char *)iBuf, ze.unc_size);
17 cycrow 8726
				}
43 cycrow 8727
				type = FILETYPE_UNINSTALL;
8728
			}
17 cycrow 8729
 
43 cycrow 8730
			if ( type == -1 )
102 cycrow 8731
				f = archive->AddFile(CFileIO(Name).filename(), CFileIO(Name).dir(), FILETYPE_EXTRA);
43 cycrow 8732
			else
102 cycrow 8733
				f = archive->AddFile(CFileIO(Name).filename(), extradir, type);
1 cycrow 8734
 
43 cycrow 8735
			if ( f )
8736
				f->SetData((const unsigned char *)iBuf, ze.unc_size);
8737
			else
8738
				delete[] iBuf;
1 cycrow 8739
		}
43 cycrow 8740
	}
1 cycrow 8741
 
43 cycrow 8742
	CloseZip(hz);
1 cycrow 8743
 
43 cycrow 8744
	if ( error )
8745
	{
8746
		delete archive;
8747
		archive = NULL;
1 cycrow 8748
	}
43 cycrow 8749
	return archive;
8750
}
1 cycrow 8751
 
43 cycrow 8752
CBaseFile *CPackages::CreateFromArchive(CyString filename, bool toInstall )
8753
{
8754
	// make sure we can open the zip file
8755
	CBaseFile *archive = NULL;
8756
	if ( CFileIO(filename).CheckFileExtension("rar") )
8757
		archive = this->_archive_fromRar(filename, toInstall);
8758
	else if ( CFileIO(filename).CheckFileExtension("zip") )
8759
		archive = this->_archive_fromZip(filename, toInstall);
8760
 
8761
	if ( archive ) {
50 cycrow 8762
		archive->setFilename(CFileIO(filename).ChangeFileExtension("spk").ToString());
1 cycrow 8763
		if ( toInstall )
57 cycrow 8764
			archive->setName(CFileIO(filename).filename());
1 cycrow 8765
		else
57 cycrow 8766
			archive->setName(CFileIO(filename).baseName());
1 cycrow 8767
	}
8768
 
8769
	return archive;
8770
}
8771
 
8772
CyString CPackages::CreateFromPackagerScript(CyString filename)
8773
{
102 cycrow 8774
	CyString curDir = CFileIO(filename).dir();
1 cycrow 8775
	CyStringList variables;
8776
	variables.PushBack("$PATH", curDir);
8777
	CPackages p;
8778
	CBaseFile *package = p.LoadPackagerScript(filename, NULL, NULL, NULL, &variables);
8779
 
8780
	if ( !package )
8781
		return NullString;
8782
 
50 cycrow 8783
	CyString saveto = package->filename();
1 cycrow 8784
	saveto = saveto.FindReplace("$DEFAULTDIR", curDir + "/");
8785
	saveto = saveto.FindReplace("$PATH", curDir);
8786
	saveto = saveto.FindReplace("\\", "/");
8787
	saveto = saveto.FindReplace("//", "/");
8788
	if ( !saveto.Right(4).Compare(".spk") && package->GetType() != TYPE_XSP )
8789
		saveto += ".spk";
8790
	else if ( !saveto.Right(4).Compare(".xsp") && package->GetType() == TYPE_XSP )
8791
		saveto += ".xsp";
8792
 
8793
	// write script
8794
	if ( package->WriteFile(saveto) )
8795
	{
8796
		if ( package->AutoGenerateUpdateFile() )
102 cycrow 8797
			package->CreateUpdateFile(CFileIO(saveto).dir());
1 cycrow 8798
		return saveto;
8799
	}
8800
 
8801
	return NullString;
8802
}
8803
 
8804
int CPackages::GeneratePackageUpdateData(CyString dir, bool includeSingle)
8805
{
8806
	CyStringList filedata;
8807
 
8808
	CPackages packages;
8809
 
8810
	CDirIO Dir(dir);
8811
	for ( int i = 0; i < 2; i++ )
8812
	{
8813
		CyString pattern;
8814
		if ( i == 0 ) pattern = "*.spk";
8815
		else if ( i == 1 ) pattern = ".xsp";
8816
		else break;
8817
 
8818
		CyStringList *files = Dir.DirList("", pattern);
8819
		if ( files )
8820
		{
8821
			for ( SStringList *node = files->Head(); node; node = node->next )
8822
			{
8823
				int error = 0;
8824
				CBaseFile *p = packages.OpenPackage(Dir.File(node->str), &error, 0, SPKREAD_NODATA);
8825
				if ( !p )
8826
					continue;
8827
 
8828
				if ( includeSingle )
8829
					p->CreateUpdateFile(dir);
8830
				filedata.PushBack(CPackages::FormatAvailablePackageData(p));
8831
				delete p;
8832
			}
8833
			delete files;
8834
		}
8835
	}
8836
 
8837
	if ( !filedata.Empty() )
8838
	{
8839
		CFileIO File(dir + "/xpackagedata.dat");
8840
		if ( File.WriteFile(&filedata) )
8841
			return filedata.Count();
8842
	}
8843
 
8844
	return 0;
8845
}
8846
 
8847
int CPackages::VerifyInstalledFiles(CyStringList *missingFiles, bool getPackages)
8848
{
8849
	int count = 0;
8850
	for ( CListNode<C_File> *fn = m_lFiles.Front(); fn; fn = fn->next() )
8851
	{
8852
		C_File *f = fn->Data();
8853
		bool exists = false;
8854
		if ( f->GetFilePointer().IsIn("::") ) {
8855
			CyString modFile = f->GetFilePointer().GetToken("::", 1, 1);
8856
			CyString file = f->GetFilePointer().GetToken("::", 2, 2);
8857
 
52 cycrow 8858
			if ( CFileIO(modFile).ExistsOld() ) {
1 cycrow 8859
				CCatFile catFile;
8860
				if ( catFile.Open(modFile, "", CATREAD_CATDECRYPT, false) == CATERR_NONE ) {
8861
					if ( catFile.FindData(file) )
8862
						exists = true;
8863
				}
8864
			}
8865
		}
8866
		else {
52 cycrow 8867
			exists = CFileIO(f->GetFilePointer()).ExistsOld();
1 cycrow 8868
		}
8869
 
8870
		if ( !exists )
8871
		{
8872
			++count;
8873
			if ( missingFiles )
8874
			{
8875
				CyString packages;
8876
				if ( getPackages )
8877
				{
8878
					for ( CListNode<CBaseFile> *p = m_lPackages.Front(); p; p = p->next() )
8879
					{
8880
						CBaseFile *package = p->Data();
8881
						if ( package->IsFileAdded(f) )
8882
						{
8883
							if ( !packages.Empty() )
8884
								packages += "\n";
8885
							packages += package->GetFullPackageName(m_iLanguage);
8886
						}
8887
					}
8888
				}
8889
				CyString filename = f->GetFilePointer();
8890
				filename = filename.Remove(m_sCurrentDir);
8891
				missingFiles->PushBack(filename, packages, false);
8892
			}
8893
		}
8894
	}
8895
	return count;
35 cycrow 8896
}