Subversion Repositories spk

Rev

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