Subversion Repositories spk

Rev

Rev 131 | Rev 134 | 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
 
2937
	errors->PushBack(args, ERRORLOG(type));
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
			{
121 cycrow 3246
				newFilename = Utils::String(m_sCurrentDir.ToString()) + "/PluginManager/Disabled/FakePatches/FakePatch_" + checkPackage->GetNameValidFile().ToString() + "_" + checkPackage->author() + "_" + f->GetName().ToString();
1 cycrow 3247
				shuffle = true;
3248
			}
3249
		}
130 cycrow 3250
		else if ( f->isAutoTextFile() )
1 cycrow 3251
		{
3252
			if ( checkPackage )
3253
			{
121 cycrow 3254
				newFilename = Utils::String(m_sCurrentDir.ToString()) + "/PluginManager/Disabled/TextFiles/Text_" + checkPackage->GetNameValidFile().ToString() + "_" + checkPackage->author() + "_" + f->GetName().ToString();
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");
1 cycrow 4964
	}
4965
}
127 cycrow 4966
void CPackages::startup(const Utils::String &dir, const Utils::String &tempDir, const Utils::String &myDoc, const Utils::String &mod)
4967
{
4968
	startup(dir, tempDir, myDoc);
4969
	m_sSetMod = mod;
4970
}
4971
void CPackages::Startup(CyString dir, CyString tempDir, CyString myDoc, CyString mod)
4972
{
4973
	startup(dir.ToString(), tempDir.ToString(), myDoc.ToString(), mod.ToString());
4974
}
1 cycrow 4975
 
121 cycrow 4976
int CPackages::GetGameLanguage() const
1 cycrow 4977
{
121 cycrow 4978
	return this->GetGameLanguage(m_sCurrentDir.ToString());
4979
}
4980
int CPackages::GetGameLanguage(const Utils::String &sDir) const
4981
{
4982
	Utils::String dir = sDir;
4983
	if (dir.empty())
4984
		dir = m_sCurrentDir.ToString();
4985
	else
4986
		dir = this->getProperDir(dir);
1 cycrow 4987
 
4988
	CDirIO Dir(dir);
4989
 
4990
	// check for lang.dat file
121 cycrow 4991
	if ( Dir.exists("lang.dat") )
1 cycrow 4992
	{
121 cycrow 4993
		CFileIO File(Dir.file("lang.dat"));
1 cycrow 4994
 
4995
		size_t size;
4996
		char *data = File.ReadToData(&size);
4997
 
4998
		if ( data )
4999
		{
121 cycrow 5000
			Utils::String str(data);
5001
			return str.token("\n", 1).token(" ", 1).toLong();
1 cycrow 5002
		}
5003
	}
5004
 
5005
	return 0;
5006
}
121 cycrow 5007
Utils::String CPackages::GetGameRunExe(const Utils::String &dir)
1 cycrow 5008
{
121 cycrow 5009
	return m_gameExe.GetGameRunExe(dir);
1 cycrow 5010
}
121 cycrow 5011
Utils::String CPackages::GetGameRunExe()
5012
{
5013
	return m_gameExe.GetGameRunExe(m_sCurrentDir.ToString());
5014
}
1 cycrow 5015
 
5016
CyString CPackages::GetGameNameFromType(int game)
5017
{
5018
	return m_gameExe.GetGameNameFromType(game - 1);
5019
}
121 cycrow 5020
Utils::String CPackages::getGameName() const
5021
{
5022
	return getGameName(m_sCurrentDir.ToString());
5023
}
5024
 
5025
Utils::String CPackages::getGameName(const Utils::String &dir) const
5026
{
5027
	return m_gameExe.GetGameName(dir.empty() ? m_sCurrentDir.ToString() : dir);
5028
}
5029
 
1 cycrow 5030
CyString CPackages::GetGameName(CyString dir)
5031
{
56 cycrow 5032
	return m_gameExe.GetGameName((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString());
1 cycrow 5033
}
5034
CyString CPackages::GetProperDir(CyString dir)
5035
{
56 cycrow 5036
	return m_gameExe.GetProperDir((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString());
1 cycrow 5037
}
5038
CyString CPackages::GetAddonDir(CyString dir)
5039
{
56 cycrow 5040
	return m_gameExe.GetAddonDir((dir.Empty()) ? m_sCurrentDir.ToString() : dir.ToString());
1 cycrow 5041
}
121 cycrow 5042
Utils::String CPackages::getProperDir() const
1 cycrow 5043
{
121 cycrow 5044
	return getProperDir(m_sCurrentDir.ToString());
1 cycrow 5045
}
121 cycrow 5046
Utils::String CPackages::getProperDir(const Utils::String &dir) const
5047
{
5048
	return m_gameExe.GetProperDir((dir.empty()) ? m_sCurrentDir.ToString() : dir);
5049
}
5050
Utils::String CPackages::getAddonDir() const
5051
{
5052
	return getAddonDir(m_sCurrentDir.ToString());
5053
}
5054
Utils::String CPackages::getAddonDir(const Utils::String &dir) const
5055
{
5056
	return m_gameExe.GetAddonDir((dir.empty()) ? m_sCurrentDir.ToString() : dir);
5057
}
5058
int CPackages::GetGameAddons(Utils::CStringList &exes, const Utils::String &dir)
5059
{
5060
	return m_gameExe.GetGameAddons((dir.empty()) ? m_sCurrentDir.ToString() : dir, exes);
5061
}
5062
int CPackages::GetGameAddons(Utils::CStringList &exes)
5063
{
5064
	return m_gameExe.GetGameAddons(m_sCurrentDir.ToString(), exes);
5065
}
1 cycrow 5066
 
5067
CyString CPackages::GetGameTypesString(CBaseFile *package, bool includeVersion)
5068
{
5069
	if ( !package->AnyGameCompatability() )
5070
		return NullString;
5071
 
98 cycrow 5072
	Utils::String sGames;
1 cycrow 5073
	for ( CListNode<SGameCompat> *gNode = package->GetGameCompatabilityList()->Front(); gNode; gNode = gNode->next() ) {
98 cycrow 5074
		if ( !sGames.empty() )
1 cycrow 5075
			sGames += ", ";
5076
		sGames += m_gameExe.GetGameNameFromType(gNode->Data()->iGame - 1);
5077
		if ( includeVersion ) {
98 cycrow 5078
			Utils::String version = m_gameExe.GetGameVersionFromType(gNode->Data()->iGame - 1, gNode->Data()->iVersion - 1, gNode->Data()->sVersion);
5079
			if ( !version.empty() ) {
5080
				sGames += " (";
5081
				sGames += version;
5082
				sGames += ")";
5083
			}
1 cycrow 5084
		}
5085
	}
5086
	return sGames;
5087
}
5088
 
5089
CyString CPackages::GetGameVersionString(CBaseFile *package)
5090
{
5091
	for ( CListNode<SGameCompat> *gNode = package->GetGameCompatabilityList()->Front(); gNode; gNode = gNode->next() ) {
5092
		if ( gNode->Data()->iGame == m_iGame ) {
5093
			return m_gameExe.GetGameVersionFromType(m_iGame - 1, gNode->Data()->iVersion - 1, gNode->Data()->sVersion);
5094
		}
5095
	}
5096
 
5097
	return NullString;
5098
}
5099
 
5100
CyString CPackages::GetGameVersionFromType(int game, int version, CyString sVersion)
5101
{
56 cycrow 5102
	return m_gameExe.GetGameVersionFromType(game - 1, version - 1, sVersion.ToString());
1 cycrow 5103
}
5104
 
5105
int CPackages::CountBuiltInPackages(bool onlyEnabled)
5106
{
5107
	int count = 0;
5108
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
5109
	{
5110
		if ( !node->Data()->CheckGameCompatability(m_iGame) )
5111
			continue;
5112
		if ( onlyEnabled && !node->Data()->IsEnabled() )
5113
			continue;
50 cycrow 5114
		if ( node->Data()->author().Compare("PluginManager") )
1 cycrow 5115
			++count;
5116
	}
5117
 
5118
	return count;
5119
}
5120
 
5121
int CPackages::CountPackages(int type, bool onlyEnabled)
5122
{
5123
	int count = 0;
5124
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
5125
	{
5126
		CBaseFile *p = node->Data();
5127
 
5128
		if ( (type != TYPE_BASE) && (p->GetType() != type) )
5129
			continue;
5130
 
5131
		if ( (onlyEnabled) && (!p->IsEnabled()) )
5132
			continue;
5133
 
5134
		++count;
5135
	}
5136
 
5137
	return count;
5138
}
5139
 
5140
int CPackages::ExtractGameFile(CyString aFilename, CyString aTo, CyString dir, CyString addon)
5141
{
5142
	// first check the enabled mod
5143
	if ( dir.Empty() )
5144
		dir = m_sCurrentDir;
5145
 
5146
	CyString addonDir = addon;
5147
	if ( addonDir.Empty() ) addonDir = this->GetAddonDir(dir);
5148
 
5149
	if ( m_pEnabledMod && m_pEnabledMod->AnyFileType(FILETYPE_MOD) )
5150
	{
5151
		for ( C_File *file = m_pEnabledMod->GetFirstFile(FILETYPE_MOD); file; file = m_pEnabledMod->GetNextFile(file) )
5152
		{
5153
			if ( !file->CheckFileExt("cat") )
5154
				continue;
5155
 
5156
			CCatFile catFile;
125 cycrow 5157
			if ( catFile.open(file->filePointer(), addonDir.ToString(), CATREAD_CATDECRYPT, false) == CATERR_NONE )
1 cycrow 5158
			{
5159
				if ( catFile.ExtractFile(aFilename, aTo) )
5160
					return 1;
124 cycrow 5161
				if ( catFile.error() == CATERR_INVALIDDEST || catFile.error() == CATERR_CANTCREATEDIR )
1 cycrow 5162
				{
5163
					if ( catFile.ExtractFile(aFilename) )
5164
						return -1;
5165
				}
5166
 
5167
			}
5168
		}
5169
	}
5170
	else if ( !m_sSetMod.Empty() )
5171
	{
52 cycrow 5172
		if ( CFileIO(m_sCurrentDir + "/mods/" + m_sSetMod + ".cat").ExistsOld() )
1 cycrow 5173
		{
5174
			CCatFile catFile;
125 cycrow 5175
			if (catFile.open((m_sCurrentDir + "/mods/" + m_sSetMod + ".cat").ToString(), addonDir.ToString(), CATREAD_CATDECRYPT, false) == CATERR_NONE)
1 cycrow 5176
			{
5177
				if ( catFile.ExtractFile(aFilename, aTo) )
5178
					return 1;
124 cycrow 5179
				if ( catFile.error() == CATERR_INVALIDDEST || catFile.error() == CATERR_CANTCREATEDIR )
1 cycrow 5180
				{
5181
					if ( catFile.ExtractFile(aFilename) )
5182
						return -1;
5183
				}
5184
			}
5185
		}
5186
	}
5187
 
5188
	// find the highest cat number
5189
	int catNumber = 1;
52 cycrow 5190
	while ( CFileIO(dir + "/" + CyString::Number(catNumber).PadNumber(2) + ".cat").ExistsOld() && catNumber < 99 )
1 cycrow 5191
		++catNumber;
5192
 
5193
	// get the last one, not the next free one
5194
	--catNumber;
5195
 
5196
	// work backwards until we find the file
5197
	for ( ; catNumber; catNumber-- )
5198
	{
5199
		CCatFile catFile;
125 cycrow 5200
		if (catFile.open((dir + "/" + CyString::Number(catNumber).PadNumber(2) + ".cat").ToString(), addonDir.ToString(), CATREAD_CATDECRYPT, false) == CATERR_NONE )
1 cycrow 5201
		{
5202
			// check for the file
5203
			if ( catFile.ExtractFile(aFilename, aTo) )
5204
				return 1;
124 cycrow 5205
			if ( catFile.error() == CATERR_INVALIDDEST || catFile.error() == CATERR_CANTCREATEDIR )
1 cycrow 5206
			{
5207
				if ( catFile.ExtractFile(aFilename) )
5208
					return -1;
5209
			}
5210
		}
5211
	}
5212
 
5213
	return 0;
5214
}
5215
 
5216
void CPackages::CreateWareFiles()
5217
{
5218
	// do each ware
5219
	int wareTextID = WARETEXTSTART;
5220
	for ( int i = 0; i < WAREBUFFERS; i++ )
5221
	{
5222
		// its empty, no need to create ware files
5223
		if ( !m_lGameWares[i].size() )
5224
			continue;
5225
 
5226
		// lets extract the ware file
5227
		char wareType = CPackages::ConvertWareTypeBack(i);
118 cycrow 5228
		Utils::String wareFile = "TWare";
1 cycrow 5229
		wareFile += (char)UPPER(wareType);
5230
 
5231
		CyString openFile;
5232
 
5233
		int e;
118 cycrow 5234
		if ( i == WARES_TECH && CFileIO::Exists(m_sTempDir + "/TWareT.txt") )
1 cycrow 5235
			openFile = m_sTempDir + "/TWareT.txt";
5236
		else {
118 cycrow 5237
			e = ExtractGameFile("types/" + wareFile + ".pck", m_sTempDir + "/" + wareFile + ".txt");
1 cycrow 5238
			if ( e == 1 )
5239
				openFile = m_sTempDir + "/" + wareFile + ".txt";
5240
			else if ( e == -2 )
5241
				openFile = wareFile + ".txt";
5242
		}
5243
 
5244
		if ( !openFile.Empty() )
5245
		{
5246
			// read the file into memory
5247
			CyStringList wareLines;
5248
			int oldSize = -1;
5249
			int version = -1;
5250
 
5251
			// read first number
5252
			CFileIO readFile(m_sTempDir + "/" + wareFile + ".txt");
5253
			CyStringList *lines = readFile.ReadLinesStr();
5254
			if ( lines )
5255
			{
5256
				for ( SStringList *str = lines->Head(); str; str = str->next )
5257
				{
5258
					CyString line(str->str);
5259
					line.RemoveFirstSpace();
5260
					line.RemoveChar(9);
5261
					line.RemoveChar('\r');
5262
					if ( line.Empty() )
5263
						continue;
5264
					if ( line[0] == '/' )
5265
						continue;
5266
 
5267
					if ( oldSize == -1 )
5268
					{
5269
						version = line.GetToken(";", 1, 1).ToInt();
5270
						oldSize = line.GetToken(";", 2, 2).ToInt();
5271
					}
5272
					else
5273
					{
5274
						line.RemoveEndSpace();
5275
						if ( line.Right(1) != ';' )
5276
							line += ";";
5277
						wareLines.PushBack(line);
5278
						if ( wareLines.Count() >= oldSize )
5279
							break;
5280
					}
5281
				}
5282
 
5283
				delete lines;
5284
 
5285
				// apply the buffer
5286
				if ( m_iWareBuffer[i] <= 0 )
5287
					m_iWareBuffer[i] = wareLines.Count() + 10;
5288
				// last resort, readjust the buffer
5289
				else if ( wareLines.Count() > m_iWareBuffer[i] )
5290
					m_iWareBuffer[i] = wareLines.Count();
5291
 
5292
				// add the buffers
5293
				while ( wareLines.Count() < m_iWareBuffer[i] )
5294
					wareLines.PushBack("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;SS_WARE_FILLER;");
5295
 
5296
				// add the ware lines
5297
				bool create = false;
5298
				for ( CListNode<SGameWare> *node = m_lGameWares[i].Front(); node; node = node->next() )
5299
				{
5300
					SGameWare *w = node->Data();
5301
 
5302
					if ( w->iType == WARETYPE_NONE )
5303
						continue;
5304
					else if ( w->iType == WARETYPE_DISABLED )
5305
					{
5306
						create = true;
5307
						wareLines.PushBack(CyString("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;") + w->sWareName + "_DISABLED;");
5308
					}
5309
					else if ( w->iType == WARETYPE_DELETED || !w->pWare )
5310
					{
5311
						create = true;
5312
						wareLines.PushBack("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;SS_WARE_DELETED;");
5313
					}
5314
					else if ( w->iType == WARETYPE_ADDED )
5315
					{
5316
						create = true;
5317
						w->pWare->iDescID = wareTextID;
5318
						w->iText = wareTextID;
5319
						wareTextID += 10;
5320
						w->iPos = wareLines.Count();
88 cycrow 5321
						long price = this->customWareOveridePrice(w->pWare->sID);
5322
						int notority = w->pWare->iNotority;
5323
						if ( !this->customWareOverideNoto(w->pWare->sID, &notority) ) notority = w->pWare->iNotority;
5324
						if ( !price ) price = w->pWare->iPrice;
5325
 
5326
						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 5327
					}
5328
				}
5329
 
5330
				if ( create )
5331
				{
5332
					wareLines.PushFront(CyString::Number(version) + ";" + CyString::Number(wareLines.Count()) + ";", NullString);
5333
					CyString strV;
5334
					strV.FromFloat(GetLibraryVersion(), 2);
5335
					wareLines.PushFront(CyString("// Created by SPKInstaller Libraries V") + strV, NullString);
5336
					if ( readFile.WriteFile(&wareLines) )
5337
						this->PackFile(&readFile, CyString("types\\") + wareFile + ".pck");
5338
				}
5339
			}
52 cycrow 5340
			readFile.remove();
1 cycrow 5341
		}
5342
	}
5343
}
5344
 
88 cycrow 5345
Utils::String CPackages::empWaresForGame(int *maxsize)
1 cycrow 5346
{
88 cycrow 5347
	if ( maxsize ) (*maxsize) = 0;
1 cycrow 5348
 
5349
	if ( m_iGame == GAME_X3TC )
5350
	{
88 cycrow 5351
		if ( maxsize ) (*maxsize) = EMP_X3TC;
5352
		return GetX3TCEmp();
1 cycrow 5353
	}
126 cycrow 5354
	else if (m_iGame == GAME_X3AP)
1 cycrow 5355
	{
126 cycrow 5356
		if (maxsize) (*maxsize) = EMP_X3AP;
88 cycrow 5357
		return GetX3TCEmp();
1 cycrow 5358
	}
126 cycrow 5359
	else if (m_iGame == GAME_X3FL)
5360
	{
5361
		if (maxsize) (*maxsize) = EMP_X3FL;
5362
		return GetX3TCEmp();
5363
	}
1 cycrow 5364
	else if ( m_iGame == GAME_X3 )
5365
	{
88 cycrow 5366
		if ( maxsize ) (*maxsize) = EMP_X3;
5367
		return GetX3Emp();
1 cycrow 5368
	}
5369
 
88 cycrow 5370
	return Utils::String::Null();
5371
}
5372
 
5373
void CPackages::_addWareOverride(enum WareTypes type, int pos, const Utils::String &id, int value, bool noto)
5374
{
5375
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
5376
		SWarePriceOverride *wp = node->Data();
5377
		if ( wp->type == type ) {
5378
			if ( wp->type == Ware_Custom && !wp->id.Compare(id) ) continue;
5379
			else if ( wp->type != Ware_Custom && wp->pos != pos ) continue;
5380
			if ( noto ) {
5381
				wp->notority  = value;
89 cycrow 5382
				wp->bNotority = true;
88 cycrow 5383
			}
5384
			else wp->relval = value;
5385
			return;
5386
		}
5387
	}
5388
 
5389
	SWarePriceOverride *ware = new SWarePriceOverride;
5390
	ware->bNotority = noto;
5391
	ware->notority = (noto) ? value : 0;
5392
	ware->relval = (noto) ? 0 : value;
5393
	ware->type = type;
5394
	ware->pos = pos;
5395
	ware->id = id;
5396
 
5397
	m_lWarePrices.push_back(ware);
5398
}
5399
 
5400
void CPackages::addEMPPriceOverride(int empId, int price)
5401
{
5402
	_addWareOverride(Ware_EMP, empId, Utils::String::Null(), price, false);
5403
}
5404
 
5405
void CPackages::addEMPNotoOverride(int empId, int noto)
5406
{
5407
	_addWareOverride(Ware_EMP, empId, Utils::String::Null(), noto, true);
5408
}
5409
 
5410
void CPackages::addBuiltInWarePriceOverride(int empId, int price)
5411
{
5412
	_addWareOverride(Ware_BuiltIn, empId, Utils::String::Null(), price, false);
5413
}
5414
 
5415
void CPackages::addBuiltInWareNotoOverride(int empId, int noto)
5416
{
5417
	_addWareOverride(Ware_BuiltIn, empId, Utils::String::Null(), noto, false);
5418
}
5419
 
5420
void CPackages::addCustomWarePriceOverride(const Utils::String &id, int price)
5421
{
5422
	_addWareOverride(Ware_Custom, 0, id, price, false);
5423
}
5424
 
5425
void CPackages::addCustomWareNotoOverride(const Utils::String &id, int noto)
5426
{
5427
	_addWareOverride(Ware_Custom, 0, id, noto, true);
5428
}
5429
 
5430
 
5431
void CPackages::CreateEMPFile(CyString progDir)
5432
{
5433
	// do emp wares
5434
	int maxsize = 0;
5435
	Utils::String empWares = empWaresForGame(&maxsize);
5436
 
1 cycrow 5437
	if ( maxsize )
5438
	{
5439
		int e = ExtractGameFile("types/TWareT.pck", m_sTempDir + "/TWareT.txt");
5440
		if ( e )
5441
		{
5442
			// read the file into memory
5443
			CyStringList wareLines;
5444
			int oldSize = -1;
5445
			int version = -1;
5446
 
5447
			// read first number
5448
			CFileIO readFile((e == -1) ? "TWareT.txt" : m_sTempDir + "/TWareT.txt");
88 cycrow 5449
			std::vector<Utils::String> *lines = readFile.readLines();
1 cycrow 5450
			if ( lines )
5451
			{
5452
				for ( int i = 0; i < (int)lines->size(); i++ )
5453
				{
88 cycrow 5454
					Utils::String line(lines->at(i));
5455
					line.removeFirstSpace();
5456
					line.removeChar('\r');
5457
					line.removeChar(9);
1 cycrow 5458
					if ( line[0] == '/' )
5459
						continue;
5460
 
5461
					if ( oldSize == -1 )
5462
					{
88 cycrow 5463
						version = line.token(";", 1).toLong();
5464
						oldSize = line.token(";", 2).toLong();
1 cycrow 5465
					}
5466
					else
5467
					{
88 cycrow 5468
						line.removeEndSpace();
5469
						if ( line.right(1) != ";" )
1 cycrow 5470
							line += ";";
88 cycrow 5471
 
5472
						// check for any override values for built in wares
5473
						if ( (i >= 62 && i <= 81) || (i >= 88 && i <= 93) ) {
5474
							int pos = i - ((i >= 88) ? 88 : 62);
5475
							int price = this->builtInWareOveridePrice(pos);
5476
							if ( price ) {
5477
								line = line.replaceToken(";", 9, Utils::String::Number(price));
5478
								line = line.replaceToken(";", 13, Utils::String::Number(price));
5479
							}
5480
 
5481
							int noto = 0;
5482
							if ( this->builtInWareOverideNoto(pos, &noto) ) {
5483
								line = line.replaceToken(";", 14, Utils::String::Number(noto));
5484
							}
5485
						}
5486
 
5487
						// check for any override values for EMP
5488
						if ( i >= 116 ) {
5489
							int price = this->empOveridePrice(i - 116);
5490
							if ( price ) {
5491
								line = line.replaceToken(";", 9, Utils::String::Number(price));
5492
								line = line.replaceToken(";", 13, Utils::String::Number(price));
5493
							}
5494
 
5495
							int noto = 0;
5496
							if ( this->empOverideNoto(i - 116, &noto) ) {
5497
								line = line.replaceToken(";", 14, Utils::String::Number(noto));
5498
							}
5499
						}
5500
 
5501
						wareLines.PushBack(CyString(line));
1 cycrow 5502
						if ( wareLines.Count() >= oldSize )
5503
							break;
5504
					}
5505
				}
5506
 
5507
				delete lines;
5508
			}
5509
 
5510
			// now we too add/remove entries to match
5511
			// need filler entries
5512
			while ( wareLines.Count() < maxsize )
5513
				wareLines.PushBack("27;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;SS_WARE_FILLER;");
5514
 
5515
			int empEntries = 0;
88 cycrow 5516
			Utils::String *empStr = empWares.tokenise("\n", &empEntries);
1 cycrow 5517
 
5518
			if ( empEntries && empStr )
5519
			{
88 cycrow 5520
				// apply any price overrides
5521
				for(int i = 0; i < empEntries; i++) {
5522
					int price = this->empOveridePrice(i);
5523
					if ( price ) {
5524
						empStr[i] = empStr[i].replaceToken(";", 9, Utils::String::Number(price));
5525
						empStr[i] = empStr[i].replaceToken(";", 13, Utils::String::Number(price));
5526
					}
5527
 
5528
					int noto = 0;
5529
					if ( this->empOverideNoto(i, &noto) ) {
5530
						empStr[i] = empStr[i].replaceToken(";", 14, Utils::String::Number(noto));
5531
					}
5532
				}
1 cycrow 5533
				// remove any empty end entries
88 cycrow 5534
				while ( empStr[empEntries - 1].empty() )
1 cycrow 5535
					--empEntries;
5536
 
5537
				CyStringList addAfter;
5538
				if ( wareLines.Count() > maxsize )
5539
				{
5540
					// force emp, remove entries to allow them to be added
5541
					if ( m_bForceEMP )
5542
					{
5543
						// more after emp
5544
						if ( wareLines.Count() > (maxsize + empEntries) )
5545
						{
5546
							SStringList *node = wareLines.GetAt(maxsize + empEntries);
5547
							while ( node )
5548
							{
5549
								addAfter.PushBack(node->str);
5550
								node = node->next;
5551
							}
5552
						}
5553
 
5554
						// no remove them all
5555
						wareLines.DeleteFrom(maxsize);
5556
					}
126 cycrow 5557
					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 5558
					{
5559
						if ( wareLines.Count() > 128 )
5560
						{
5561
							CyString test = wareLines.GetAt(128)->str;
5562
							if ( test.GetToken(";", -2).Compare("SS_WARE_SW_CUSTOM16_1;") )
5563
							{
5564
								// if theres any at the end, remove the last emp entry
5565
								if ( wareLines.Count() > (maxsize + empEntries - 1) )
5566
								{
5567
									SStringList *node = wareLines.GetAt(maxsize + empEntries - 2);
5568
									if ( node )
5569
										node->remove = true;
5570
								}
5571
								wareLines.Insert(128, "0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;128;");
5572
								wareLines.RemoveMarked();
5573
							}
5574
						}
5575
					}
5576
				}
5577
 
5578
				// too many entries, need to remove the first set of EMP wares
5579
				int i = 0;
5580
				if ( wareLines.Count() > maxsize )
5581
					i = wareLines.Count() - maxsize;
5582
 
5583
				for ( ; i < empEntries; i++ )
5584
				{
5585
					CyString str = empStr[i];
5586
					str.RemoveEndSpace();
5587
					str.RemoveChar(9);
5588
					str.RemoveChar('\r');
5589
					if ( str.Empty() )
5590
						continue;
5591
					if ( str.Right(1) != ";" )
5592
						str += ";";
5593
					wareLines.PushBack(str);
5594
				}
5595
 
5596
				for ( SStringList *afterNode = addAfter.Head(); afterNode; afterNode = afterNode->next )
5597
					wareLines.PushBack(afterNode->str);
5598
 
5599
				// finally we write the whole file
5600
				wareLines.PushFront(CyString::Number(version) + ";" + CyString::Number(wareLines.Count()) + ";", NullString);
5601
				CyString strV;
5602
				strV.FromFloat(GetLibraryVersion(), 2);
5603
				wareLines.PushFront(CyString("// Created by SPKInstaller Libraries V") + strV, NullString);
5604
				if ( readFile.WriteFile(&wareLines) )
5605
					this->PackFile(&readFile, "types\\TWareT.pck");
5606
			}
5607
			CLEANSPLIT(empStr, empEntries);
5608
		}
5609
	}
5610
}
5611
 
84 cycrow 5612
Utils::String parseXmlText(const Utils::String &str)
17 cycrow 5613
{
84 cycrow 5614
	Utils::String newStr(str);
17 cycrow 5615
	CyStringList changes;
5616
 
5617
	// find all XML commands, &<command>;
84 cycrow 5618
	Utils::String sStr = str;
5619
	Utils::String::size_type pos = sStr.find_first_of("&", 0);
5620
	while ( pos != Utils::String::npos ) {
17 cycrow 5621
		// find the next space and next ;.  If ; comes first, assume its acommand
84 cycrow 5622
		Utils::String::size_type spacePos = sStr.find_first_of(" ", pos);
5623
		Utils::String::size_type colonPos = sStr.find_first_of(";", pos);
5624
		if ( colonPos != Utils::String::npos && colonPos < spacePos ) {
17 cycrow 5625
			// replace with <::command::> so they the & doesn't get replaced
84 cycrow 5626
			Utils::String repStr = sStr.substr(pos, (colonPos + 1) - pos);
5627
			Utils::String repWithStr = "<::" + sStr.substr(pos + 1, colonPos - pos - 1) + "::>";
5628
			newStr = newStr.findReplace(repStr, repWithStr);
5629
			changes.PushBack(CyString(repStr), CyString(repWithStr));
17 cycrow 5630
		}
5631
 
5632
		// find the next command
5633
		pos = sStr.find_first_of("&", pos + 1);
5634
	}
5635
 
5636
	// replace the & now
84 cycrow 5637
	newStr = newStr.findReplace("&", "&amp;");
17 cycrow 5638
 
5639
	// restore the commands
5640
	for ( SStringList *strNode = changes.Head(); strNode; strNode = strNode->next ) {
84 cycrow 5641
		newStr = newStr.findReplace(strNode->data.ToString(), strNode->str.ToString());
17 cycrow 5642
	}
5643
 
5644
	return newStr;
5645
}
5646
 
84 cycrow 5647
Utils::String CPackages::ConvertTextString(const Utils::String &sText)
1 cycrow 5648
{
17 cycrow 5649
	//process any &
84 cycrow 5650
	Utils::String text = parseXmlText(sText);
17 cycrow 5651
 
5652
	// change special cases
84 cycrow 5653
	text = text.findReplace("(", "\\(");
5654
	text = text.findReplace(")", "\\)");
5655
	text = text.findReplace("[", "{");
5656
	text = text.findReplace("]", "}");
5657
	text = text.findReplace(">", "&gt;");
5658
	text = text.findReplace("<", "&lt;");
1 cycrow 5659
	return text;
5660
}
5661
 
56 cycrow 5662
int CPackages::_gameTextNumber() const
5663
{
5664
	int gameNumber = (m_pCurrentGameExe) ? m_pCurrentGameExe->iTextNum : -1;
5665
	if ( gameNumber != -1 ) return gameNumber;
5666
 
5667
	switch(m_iGame) {
5668
		case GAME_X3: return 30;
5669
		case GAME_X3TC: return 35;
5670
		case GAME_X3AP: return 38;
126 cycrow 5671
		case GAME_X3FL: return 39;
56 cycrow 5672
		default: return 0;
5673
	}
5674
}
5675
 
87 cycrow 5676
void CPackages::createPluginManagerOpenText()
5677
{
5678
	int gameNumber = _gameTextNumber();
5679
 
5680
	int lang = m_iLanguage;
5681
	if ( !lang || lang < 0 )
5682
		lang = 44;
5683
 
5684
	CDirIO Dir(m_sCurrentDir);
121 cycrow 5685
	if ( !Dir.exists("t") )
87 cycrow 5686
		Dir.Create("t");
5687
 
5688
	CyString filename = SPK::FormatTextName(PMTEXTFILE, lang, (m_iGameFlags & EXEFLAG_TCTEXT));
5689
	CFileIO textFile(m_sCurrentDir + "/t/" + filename + ".xml");
5690
 
5691
	std::vector<CyString> writeData;
5692
 
5693
	writeData.push_back(CyString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"));
5694
	writeData.push_back(CyString("<language id=\"") + CyString::Number(lang) + "\">");
5695
 
5696
	if ( !gameNumber )
5697
		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\">");
5698
	else
5699
		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\">");
5700
 
5701
	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>"));
5702
	writeData.push_back(CyString("		<t id=\"99999\">2</t>"));
5703
 
5704
	writeData.push_back(CyString("	</page>"));
5705
 
5706
	writeData.push_back(CyString("</language>"));
5707
	textFile.WriteFileUTF(&writeData);
5708
 
5709
	size_t fileSize;
102 cycrow 5710
	char *fileData = CFileIO(textFile.fullFilename()).ReadToData(&fileSize);
87 cycrow 5711
 
5712
	if ( fileData && fileSize)
5713
	{
5714
		size_t newFileSize;
5715
		unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
5716
		if ( pckData )
5717
		{
5718
			CFileIO pckFile(m_sCurrentDir + "/t/" + filename + ".pck");
5719
			pckFile.WriteData((char *)pckData, newFileSize);
102 cycrow 5720
			this->AddCreatedFile(pckFile.fullFilename());
87 cycrow 5721
		}
5722
	}
5723
	textFile.remove();
5724
}
5725
 
1 cycrow 5726
void CPackages::CreatePluginManagerText()
5727
{
56 cycrow 5728
	int gameNumber = _gameTextNumber();
1 cycrow 5729
 
5730
	int lang = m_iLanguage;
5731
	if ( !lang || lang < 0 )
5732
		lang = 44;
5733
 
5734
	CDirIO Dir(m_sCurrentDir);
121 cycrow 5735
	if ( !Dir.exists("t") )
1 cycrow 5736
		Dir.Create("t");
5737
 
5738
	m_iLastUpdated = (int)time(NULL);
5739
 
5740
	CyString filename = SPK::FormatTextName(PMTEXTFILE, lang, (m_iGameFlags & EXEFLAG_TCTEXT));
5741
	CFileIO textFile(m_sCurrentDir + "/t/" + filename + ".xml");
5742
 
5743
	std::vector<CyString> writeData;
5744
 
5745
	CLinkList<SGameWare> lWares;
5746
	CLinkList<SGameShip> lShips;
5747
	for ( int i = 0; i < WAREBUFFERS; i++ )
5748
	{
5749
		for ( CListNode<SGameWare> *node = m_lGameWares[i].Front(); node; node = node->next() )
5750
		{
5751
			SGameWare *w = node->Data();
5752
			if ( w->iType == WARETYPE_NONE )
5753
				continue;
5754
			lWares.push_back(w);
5755
		}
5756
	}
5757
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
5758
	{
5759
		if ( node->Data()->iType == WARETYPE_NONE )
5760
			continue;
5761
		lShips.push_back(node->Data());
5762
	}
5763
 
5764
	writeData.push_back(CyString("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"));
5765
	writeData.push_back(CyString("<language id=\"") + CyString::Number(lang) + "\">");
5766
 
5767
	if ( !gameNumber )
5768
		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\">");
5769
	else
5770
		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\">");
5771
 
5772
	// write the heading
5773
	int start = 10000;
5774
	writeData.push_back(CyString("		<t id=\"1\">") + CyString::Number(m_iLastUpdated) + "</t>");
5775
	writeData.push_back(CyString("		<t id=\"2\">") + CyString::Number(this->CountPackages(TYPE_SPK, true)) + "</t>");
5776
	writeData.push_back(CyString("		<t id=\"3\">") + CyString::Number(start) + "</t>");
5777
	writeData.push_back(CyString("		<t id=\"4\">") + CyString::Number(lWares.size()) + "</t>");
5778
	writeData.push_back(CyString("		<t id=\"6\">") + CyString::Number(lShips.size()) + "</t>");
5779
 
5780
	// write some generic texts
5781
	writeData.push_back(CyString("		<t id=\"110\">") + (long)m_iLanguage + "</t>");
5782
	writeData.push_back(CyString("		<t id=\"109\">Plugin Manager: \\033GPoll Gui Data\\033X</t>"));
5783
	writeData.push_back(CyString("		<t id=\"107\">Plugin Manager: \\033GExport Game Data\\033X </t>"));
5784
	writeData.push_back(CyString("		<t id=\"100\">\\n</t>"));
5785
	writeData.push_back(CyString("		<t id=\"101\">\\033B</t>"));
5786
	writeData.push_back(CyString("		<t id=\"102\">\\033G</t>"));
5787
	writeData.push_back(CyString("		<t id=\"103\">\\033B</t>"));
5788
	writeData.push_back(CyString("		<t id=\"104\">\\033X</t>"));
5789
	writeData.push_back(CyString("		<t id=\"105\">\\033Y</t>"));
5790
	writeData.push_back(CyString("		<t id=\"106\">\\033C</t>"));
5791
	writeData.push_back(CyString("		<t id=\"108\">\\033</t>"));
87 cycrow 5792
 
5793
	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>"));
5794
	writeData.push_back(CyString("		<t id=\"99999\">1</t>"));
1 cycrow 5795
	// now write each package
5796
	int settingStart = 100000;
5797
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
5798
	{
5799
		CBaseFile *p = node->Data();
5800
		if ( !p->IsEnabled() )
5801
			continue;
5802
 
5803
		if ( p->GetType() != TYPE_SPK )
5804
			continue;
5805
 
5806
		CSpkFile *spk = (CSpkFile *)p;
5807
 
5808
		// count text files
5809
		CyString textEntries;
5810
		int textCount = 0;
5811
		C_File *f = p->GetFirstFile(FILETYPE_TEXT);
5812
		while ( f )
5813
		{
5814
			CyString sLang;
5815
			CyString id;
5816
			if ( m_iGameFlags & EXEFLAG_TCTEXT )
5817
			{
5818
				id = f->GetBaseName().GetToken("-", 1, 1);
5819
				sLang = f->GetBaseName().GetToken("-", 2, 2);
5820
				if ( sLang.Empty() )
5821
					sLang = "NULL";
5822
				else
5823
					sLang = sLang.Erase(0, 1);  // remove the "L"
5824
			}
5825
			else
5826
			{
5827
				sLang = f->GetBaseName().Left((int)f->GetBaseName().Length() - 4).PadNumber(3);
5828
				id = f->GetBaseName().Mid(((int)f->GetBaseName().Length() - 4) + 1, 4);
5829
			}
5830
 
5831
			if ( sLang != "NULL" )
5832
			{
5833
				if ( sLang.ToInt() == lang )
5834
				{
5835
					++textCount;
5836
					if ( !textEntries.Empty() )
5837
						textEntries += " ";
5838
					textEntries += id;
5839
				}
5840
			}
5841
			f = p->GetNextFile(f);
5842
		}
5843
 
5844
		CyString sTextCount((long)textCount);
50 cycrow 5845
		writeData.push_back(CyString("		<t id=\"") + (long)start + "\">" + this->ConvertTextString(p->name()) + "</t>");
5846
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 1) + "\">" + this->ConvertTextString(p->author()) + "</t>");
5847
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 2) + "\">" + this->ConvertTextString(p->version()) + "</t>");
84 cycrow 5848
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 3) + "\">" + this->ConvertTextString(p->GetLanguageName(lang).ToString()) + "</t>");
1 cycrow 5849
 
14 cycrow 5850
		CLinkList<SSettingType> *settings = spk->GetSettingsList();
1 cycrow 5851
		if ( settings && settings->size() )
5852
		{
5853
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 4) + "\">" + (long)settings->size() + "</t>");
5854
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 5) + "\">" + (long)settingStart + "</t>");
5855
 
14 cycrow 5856
			for ( CListNode<SSettingType> *sNode = settings->Front(); sNode; sNode = sNode->next() )
1 cycrow 5857
			{
14 cycrow 5858
				SSettingType *st = sNode->Data();
1 cycrow 5859
				writeData.push_back(CyString("		<t id=\"") + (long)(settingStart++) + "\">" + st->sKey + "</t>");
5860
				writeData.push_back(CyString("		<t id=\"") + (long)(settingStart++) + "\">" + spk->GetSetting(st) + "</t>");
5861
			}
5862
		}
5863
		else
5864
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 4) + "\">0</t>");
5865
 
5866
		writeData.push_back(CyString("		<t id=\"") + (long)(start + 6) + "\">" + sTextCount + "</t>");
5867
		if ( textCount )
5868
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 7) + "\">" + textEntries + "</t>");
5869
 
5870
		start += 10;
5871
	}
5872
 
5873
	// write ware names
5874
	if ( lWares.size() )
5875
	{
5876
		writeData.push_back(CyString("		<t id=\"5\">") + CyString::Number(start) + "</t>");
5877
		for ( CListNode<SGameWare> *node = lWares.Front(); node; node = node->next() )
5878
		{
5879
			SGameWare *w = node->Data();
5880
			if ( w->pWare && w->iType == WARETYPE_ADDED )
84 cycrow 5881
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">" + this->ConvertTextString(w->sWareName.ToString()) + "</t>");
1 cycrow 5882
			else
5883
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">-1</t>");
5884
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 1) + "\">" + CyString((char)w->cType) + "</t>");
5885
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 2) + "\">" + (long)w->iPos + "</t>");
5886
			start += 10;
5887
		}
5888
	}
5889
 
5890
	if ( lShips.size() )
5891
	{
5892
		writeData.push_back(CyString("		<t id=\"7\">") + CyString::Number(start) + "</t>");
5893
		for ( CListNode<SGameShip> *node = lShips.Front(); node; node = node->next() )
5894
		{
5895
			SGameShip *gs = node->Data();
5896
			if ( gs->iType == WARETYPE_NONE )
5897
				continue;
5898
			if ( gs->pPackage && gs->iType == WARETYPE_ADDED )
5899
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">" + gs->sShipID + "</t>");
5900
			else
5901
				writeData.push_back(CyString("		<t id=\"") + (long)start + "\">-1</t>");
5902
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 1) + "\">" + (long)gs->iPos + "</t>");
5903
			writeData.push_back(CyString("		<t id=\"") + (long)(start + 2) + "\">Ship</t>");
5904
 
5905
			// write shipyard info
5906
			if ( gs->pPackage )
5907
			{
5908
				int doStart = start + 5;
5909
				for ( int i = SHIPYARD_ARGON; i <= SHIPYARD_MAX; i *= 2 )
5910
				{
5911
					writeData.push_back(CyString("		<t id=\"") + (long)(doStart) + "\">" + ((gs->pPackage->IsShipyard(i)) ? CyString::Number(1) : CyString::Number(0)) + "</t>");
5912
					++doStart;
5913
				}
5914
			}
5915
 
5916
			start += 20;
5917
		}
5918
	}
5919
 
5920
	writeData.push_back(CyString("	</page>"));
5921
 
5922
	// wares
126 cycrow 5923
	if ( m_iGame == GAME_X3AP || m_iGame == GAME_X3TC || m_iGame == GAME_X3FL || m_iGame == GAME_X3 || lWares.size() || lShips.size() )
1 cycrow 5924
	{
5925
		if ( !gameNumber )
5926
			writeData.push_back(CyString("  <page id=\"17\" title=\"Plugin Manager Objects\">"));
5927
		else
5928
			writeData.push_back(CyString("  <page id=\"") + (long)gameNumber + "0017\" title=\"Plugin Manager Objects\">");
5929
 
5930
		writeData.push_back(CyString("		<t id=\"") + (long)(SHIPSTARTTEXT - 1) + "\">ZZ_BLANKSHIP</t>");
5931
		// do emp
126 cycrow 5932
		if ( m_iGame == GAME_X3TC || m_iGame == GAME_X3 || m_iGame == GAME_X3AP || m_iGame == GAME_X3FL)
1 cycrow 5933
			writeData.push_back(GetEMPText());
5934
 
5935
		// object names
5936
		for ( CListNode<SGameWare> *node = lWares.Front(); node; node = node->next() )
5937
		{
5938
			SGameWare *w = node->Data();
5939
			if ( !w->pWare || w->iType != WARETYPE_ADDED )
5940
				continue;
5941
 
5942
			// find the correct text for the language
84 cycrow 5943
			Utils::String name = CSpkFile::GetWareText(w->pWare, m_iLanguage);
5944
			Utils::String desc = CSpkFile::GetWareDesc(w->pWare, m_iLanguage);
5945
			if ( !name.empty() )
17 cycrow 5946
				writeData.push_back(CyString("		<t id=\"") + (long)(w->iText + 3) + "\">" + this->ConvertTextString(name) + "</t>");
84 cycrow 5947
			if ( !desc.empty() )
17 cycrow 5948
				writeData.push_back(CyString("		<t id=\"") + (long)(w->iText + 4) + "\">" + this->ConvertTextString(desc) + "</t>");
1 cycrow 5949
		}
5950
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
5951
		{
5952
			SGameShip *s = node->Data();
5953
			if ( !s->pPackage || s->iType != WARETYPE_ADDED )
5954
				continue;
5955
			if ( s->pPackage->GetOriginalDescription() )
5956
				continue;
5957
 
84 cycrow 5958
			Utils::String name = s->pPackage->GetTextName(m_iLanguage);
5959
			Utils::String desc = s->pPackage->GetTextDescription(m_iLanguage);
5960
			if ( !name.empty() )
17 cycrow 5961
				writeData.push_back(CyString("		<t id=\"") + (long)s->iText + "\">" + this->ConvertTextString(name) + "</t>");
84 cycrow 5962
			if ( !desc.empty() )
17 cycrow 5963
				writeData.push_back(CyString("		<t id=\"") + (long)(s->iText + 1) + "\">" + this->ConvertTextString(desc) + "</t>");
1 cycrow 5964
		}
5965
		writeData.push_back(CyString("  </page>"));
5966
	}
5967
	writeData.push_back(CyString("</language>"));
5968
	textFile.WriteFileUTF(&writeData);
5969
 
5970
	size_t fileSize;
102 cycrow 5971
	char *fileData = CFileIO(textFile.fullFilename()).ReadToData(&fileSize);
1 cycrow 5972
 
5973
	if ( fileData && fileSize)
5974
	{
5975
		size_t newFileSize;
5976
		unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
5977
		if ( pckData )
5978
		{
5979
			CFileIO pckFile(m_sCurrentDir + "/t/" + filename + ".pck");
5980
			pckFile.WriteData((char *)pckData, newFileSize);
102 cycrow 5981
			this->AddCreatedFile(pckFile.fullFilename());
1 cycrow 5982
		}
5983
	}
52 cycrow 5984
	textFile.remove();
1 cycrow 5985
}
5986
 
121 cycrow 5987
bool CPackages::isCurrentDir(const Utils::String &dir) const
1 cycrow 5988
{
121 cycrow 5989
	Utils::String cur = m_sCurrentDir.ToString();
5990
 
5991
	if ( dir.Compare(cur) )
1 cycrow 5992
		return true;
5993
 
121 cycrow 5994
	Utils::String checkDir = cur;
5995
	checkDir = checkDir.findReplace("/", "\\");
1 cycrow 5996
	if ( checkDir.Compare(dir) )
5997
		return true;
5998
 
121 cycrow 5999
	checkDir = checkDir.findReplace("\\", "/");
1 cycrow 6000
	if ( checkDir.Compare(dir) )
6001
		return true;
6002
 
6003
	return false;
6004
}
6005
 
126 cycrow 6006
void CPackages::backupSaves(bool vanilla)
1 cycrow 6007
{
126 cycrow 6008
	if (!_sSaveDir.empty())
6009
	{
6010
		// copy any saves into the vanilla directory
6011
		Utils::String dir = (vanilla) ? "Vanilla" : "Modified";
1 cycrow 6012
 
126 cycrow 6013
		// make sure the directory exists
6014
		CDirIO saveDir(this->saveDirectory());
6015
		CDirIO gameSaveDir(saveDir.dir(_sSaveDir));
1 cycrow 6016
 
126 cycrow 6017
		if (!gameSaveDir.exists())
6018
			gameSaveDir.Create();
6019
		if (!gameSaveDir.exists(dir))
6020
			gameSaveDir.Create(dir);
6021
		gameSaveDir.cd(dir);
6022
 
6023
		// backup the saves
6024
		Utils::CStringList files;
6025
		if(saveDir.dirList(files, Utils::String::Null(), "*.sav"))
1 cycrow 6026
		{
126 cycrow 6027
			for(auto itr = files.begin(); itr != files.end(); ++itr)
6028
			{
6029
				CFileIO File(saveDir.file((*itr)->str));
6030
				if (!File.CheckFileExtension("sav"))
6031
					continue;
6032
				// remove the file if already exists
6033
				if (gameSaveDir.exists((*itr)->str))
6034
					CFileIO::Remove(gameSaveDir.file((*itr)->str));
1 cycrow 6035
 
126 cycrow 6036
				// copy the file into the games save dir for backup
6037
				File.copy(gameSaveDir.file(File.filename()), true);
6038
			}
1 cycrow 6039
		}
6040
	}
6041
}
6042
 
126 cycrow 6043
void CPackages::restoreSaves(bool vanilla)
1 cycrow 6044
{
6045
	// get dir to restore from
126 cycrow 6046
	if (!_sSaveDir.empty())
6047
	{
6048
		Utils::String dir = (vanilla) ? "Vanilla" : "Modified";
6049
		CDirIO toDir(this->saveDirectory());
6050
		CDirIO restoreDir(toDir.dir(_sSaveDir));
6051
		restoreDir.cd(dir);
1 cycrow 6052
 
126 cycrow 6053
		if (restoreDir.exists())
6054
		{
6055
			//if we are in vanilla mode, we should remove the saves (so we only have vanilla saves
6056
			/*
6057
			if (vanilla) {
6058
				CyStringList *files = toDir.DirList();
6059
				if (files) {
6060
					for (SStringList *node = files->Head(); node; node = node->next)
6061
					{
6062
						CFileIO saveFile(toDir.File(node->str));
6063
						if (saveFile.extension().Compare("sav")) {
6064
							saveFile.remove();
6065
						}
6066
					}
6067
					delete files;
86 cycrow 6068
				}
6069
			}
126 cycrow 6070
			*/
86 cycrow 6071
 
126 cycrow 6072
			// now we copy of the backed up save games
6073
			Utils::CStringList files;
6074
			if(restoreDir.dirList(files, Utils::String::Null(), "*.sav"))
6075
			{
6076
				for(auto itr = files.begin(); itr != files.end(); itr++)
6077
				{
6078
					CFileIO File(restoreDir.file((*itr)->str));
6079
					// remove the file if already exists
6080
					if (toDir.exists((*itr)->str)) CFileIO::Remove(toDir.file((*itr)->str));
1 cycrow 6081
 
126 cycrow 6082
					// move file over
6083
					File.copy(toDir.file((*itr)->str), true);
6084
				}
6085
			}
1 cycrow 6086
		}
6087
	}
6088
}
6089
 
6090
bool CPackages::RemoveCurrentDirectory()
6091
{
6092
	if ( !m_bLoaded )
6093
		return false;
6094
 
6095
	// remove all package files
6096
	this->RemoveAllPackages();
6097
 
6098
	// remove all plugin manager files
6099
	this->RemoveCreatedFiles();
6100
 
6101
	this->Reset();
6102
	m_bLoaded = false;
6103
 
6104
	// clear the plugin manager directory
6105
	CDirIO Dir(m_sCurrentDir);
6106
	Dir.RemoveDir("PluginManager", true, true, 0);
6107
	Dir.RemoveDir("dds", false, true, 0);
6108
	Dir.RemoveDir("objects", false, true, 0);
6109
	Dir.RemoveDir("types", false, true, 0);
6110
	Dir.RemoveDir("textures", false, true, 0);
6111
 
6112
	// remove the plugin manager mod files
121 cycrow 6113
	if ( Dir.exists("mods/PluginManager.cat") )	CFileIO::Remove(Dir.file("mods/PluginManager.cat"));
6114
	if ( Dir.exists("mods/PluginManager.dat") )	CFileIO::Remove(Dir.file("mods/PluginManager.dat"));
1 cycrow 6115
 
6116
	return true;
6117
}
6118
 
6119
void CPackages::CreateDummies()
6120
{
6121
	// first check we have any ships
6122
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6123
		return;
6124
 
6125
	CLinkList<SDummyEntry> dummyList;
6126
 
6127
	// now extract the existing dummies
6128
	int e = ExtractGameFile("types/Dummies.pck", m_sTempDir + "/Dummies.txt");
6129
	if ( e )
6130
	{
6131
		// read the dummies
6132
		CFileIO File;
118 cycrow 6133
		if ( File.open((e == -1) ? "Dummies.txt" : m_sTempDir + "/Dummies.txt") )
1 cycrow 6134
		{
6135
			std::vector<CyString> *lines = File.ReadLines();
6136
			if ( lines )
6137
			{
6138
				int insection = 0;
6139
				SDummyEntry *currentSection = NULL;
6140
				for ( int j = 0; j < (int)lines->size(); j++ )
6141
				{
6142
					CyString line(lines->at(j));
6143
					line.RemoveChar(9);
6144
					line.RemoveChar('\r');
6145
					line.RemoveFirstSpace();
64 cycrow 6146
					line.RemoveEndSpace();
1 cycrow 6147
					if ( line.Empty() )
6148
						continue;
6149
					if ( line[0] == '/' )
6150
						continue;
6151
 
6152
					// read the section, first entry is section, second is size
6153
					while ( !line.Empty() )
6154
					{
6155
						if ( !insection )
6156
						{
6157
							CyString section = line.GetToken(";", 1, 1);
6158
							insection = line.GetToken(";", 2, 2).ToInt();
6159
 
6160
							// search for the sections
6161
							currentSection = NULL;
6162
							for ( CListNode<SDummyEntry> *node = dummyList.Front(); node; node = node->next() )
6163
							{
6164
								SDummyEntry *d = node->Data();
6165
								if ( d->sSection.Compare(section) )
6166
								{
6167
									currentSection = node->Data();
6168
									break;
6169
								}
6170
							}
6171
 
6172
							if ( !currentSection )
6173
							{
6174
								currentSection = new struct SDummyEntry;
6175
								currentSection->sSection = section;
6176
								dummyList.push_back(currentSection);
6177
							}
6178
 
6179
							// we have some more ?
6180
							line = line.DelToken(";", 1, 2);
6181
						}
6182
						else
6183
						{
6184
							--insection;
6185
							// check the last entry for number of states
6186
							if ( currentSection->sSection.Compare("SDTYPE_GUN") )
6187
							{
6188
								int states = line.GetToken(";", 3, 3).ToInt();
6189
								int parts = line.GetToken(";", 4 + (states * 2), 4 + (states * 2)).ToInt();
6190
								CyString data = line.GetToken(";", 1, 4 + (states * 2) + (parts * 2)) + ";";
6191
								currentSection->lEntries.PushBack(data);
6192
 
6193
								// remove done
6194
								line = line.DelToken(";", 1, 4 + (states * 2) + (parts * 2));
6195
							}
6196
							else
6197
							{
6198
								int states = line.GetToken(";", 3, 3).ToInt();
6199
								CyString data = line.GetToken(";", 1, 3 + (states * 2)) + ";";
6200
								currentSection->lEntries.PushBack(data);
6201
 
6202
								// remove done
6203
								line = line.DelToken(";", 1, 3 + (states * 2));
6204
							}
6205
						}
6206
					}
6207
				}
6208
 
6209
				delete lines;
6210
			}
6211
 
52 cycrow 6212
			File.remove();
1 cycrow 6213
		}
6214
 
6215
		// add the new entries for the ships
6216
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6217
		{
6218
			SGameShip *s = node->Data();
6219
			if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6220
				continue;
6221
 
6222
			// no dummies to add?
6223
			if ( !s->pPackage->AnyDummies() )
6224
				continue;
6225
 
6226
			// add each dummy to list
6227
			for ( CListNode<SDummy> *dNode = s->pPackage->GetDummies()->Front(); dNode; dNode = dNode->next() )
6228
			{
6229
				SDummy *dummy = dNode->Data();
6230
				SDummyEntry *found = NULL;
6231
				for ( CListNode<SDummyEntry> *eNode = dummyList.Front(); eNode; eNode = eNode->next() )
6232
				{
39 cycrow 6233
					if ( eNode->Data()->sSection.Compare(CyString(dummy->sSection)) )
1 cycrow 6234
					{
6235
						found = eNode->Data();
6236
						break;
6237
					}
6238
				}
6239
				if ( !found )
6240
				{
6241
					found = new SDummyEntry;
6242
					found->sSection = dummy->sSection;
6243
					dummyList.push_back(found);
6244
				}
6245
				// check if its already on the list
6246
				else
6247
				{
6248
					bool f = false;
6249
					for ( SStringList *strNode = found->lEntries.Head(); strNode; strNode = strNode->next )
6250
					{
39 cycrow 6251
						if ( strNode->str.GetToken(";", 1, 1).Compare(CyString(dummy->sData.token(";", 1))) )
1 cycrow 6252
						{
6253
							f = true;
6254
							break;
6255
						}
6256
					}
6257
 
6258
					if ( f )
6259
						continue;
6260
				}
6261
 
39 cycrow 6262
				found->lEntries.PushBack(CyString(dummy->sData));
1 cycrow 6263
			}
6264
		}
6265
 
6266
		// finally, write the file
6267
		std::vector<CyString> lines;
6268
		lines.push_back(CyString("// Dummies file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6269
		for ( SDummyEntry *dummy = dummyList.First(); dummy; dummy = dummyList.Next() )
6270
		{
6271
			lines.push_back("");
6272
			lines.push_back(CyString("// Section: ") + dummy->sSection + " Entries: " + (long)dummy->lEntries.Count());
6273
			lines.push_back(dummy->sSection + ";" + CyString::Number(dummy->lEntries.Count()) + ";");
6274
			for ( SStringList *str = dummy->lEntries.Head(); str; str = str->next )
6275
			{
6276
				CyString strLine = str->str;
6277
				strLine.RemoveChar(9);
6278
				strLine.RemoveChar('\r');
6279
				strLine.RemoveEndSpace();
6280
				strLine.RemoveFirstSpace();
6281
				strLine = strLine.FindReplace("<::PiPe::>", "|");
6282
				if ( strLine.Right(1) != ";" )
6283
					strLine += ";";
6284
				lines.push_back(strLine);
6285
			}
6286
		}
6287
		lines.push_back("");
6288
 
6289
		// write the file to disk
6290
		CFileIO WriteFile(m_sTempDir + "/dummies.txt");
6291
		if ( WriteFile.WriteFile(&lines) )
6292
		{
6293
			this->PackFile(&WriteFile, "types\\dummies.pck");
52 cycrow 6294
			WriteFile.remove();
1 cycrow 6295
		}
6296
	}
6297
}
6298
 
6299
void CPackages::CreateCutData()
6300
{
6301
	// first check we have any ships
6302
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6303
		return;
6304
 
6305
	bool found = false;
6306
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6307
	{
6308
		SGameShip *s = node->Data();
6309
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6310
			continue;
6311
 
6312
		// no dummies to add?
6313
		if ( !s->pPackage->AnyCutData() )
6314
			continue;
6315
		found = true;
6316
		break;
6317
	}
6318
 
6319
	if ( !found )
6320
		return;
6321
 
6322
	CyStringList cutList;
6323
	int e = ExtractGameFile("types/CutData.pck", m_sTempDir + "/CutData.txt");
6324
	if ( e )
6325
	{
6326
		CFileIO File;
118 cycrow 6327
		if ( File.open((e == -1) ? "CutData.txt" : m_sTempDir + "/CutData.txt") )
1 cycrow 6328
		{
6329
			std::vector<CyString> *lines = File.ReadLines();
6330
			if ( lines )
6331
			{
6332
				int entries = -1;
6333
				for ( int j = 0; j < (int)lines->size(); j++ )
6334
				{
6335
					CyString line(lines->at(j));
6336
					line.RemoveChar(9);
6337
					line.RemoveChar('\r');
6338
					line.RemoveChar(' ');
6339
					if ( line.Empty() || line[0] == '/' )
6340
						continue;
6341
					if ( entries == -1 )
6342
						entries = line.GetToken(";", 1, 1).ToInt();
6343
					else
6344
					{
6345
						if ( line.Right(1) != ";" )
6346
							line += ";";
6347
						cutList.PushBack(line);
6348
						if ( cutList.Count() == entries )
6349
							break;
6350
					}
6351
				}
6352
 
6353
				delete lines;
6354
			}
6355
 
52 cycrow 6356
			File.remove();
1 cycrow 6357
		}
6358
	}
6359
 
6360
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6361
	{
6362
		SGameShip *s = node->Data();
6363
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6364
			continue;
6365
 
6366
		// no dummies to add?
6367
		if ( !s->pPackage->AnyCutData() )
6368
			continue;
6369
 
6370
		// add each dummy to list
6371
		for ( SStringList *strNode = s->pPackage->GetCutData()->Head(); strNode; strNode = strNode->next )
6372
		{
6373
			CyString str = strNode->str;
6374
			str.RemoveChar(' ');
6375
			if ( str.Right(1) != ";" )
6376
				str += ";";
6377
			cutList.PushBack(str, true);
6378
		}
6379
	}
6380
 
6381
	cutList.PushFront(CyString::Number(cutList.Count()) + ";");
6382
	cutList.PushFront("/cut id;filename (leave blank to use id)");
6383
	cutList.PushFront(CyString("// Cut Data file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6384
 
6385
	// write the file to disk
6386
	CFileIO WriteFile(m_sTempDir + "/CutData.txt");
6387
	if ( WriteFile.WriteFile(&cutList) )
6388
	{
6389
		this->PackFile(&WriteFile, "types\\CutData.pck");
52 cycrow 6390
		WriteFile.remove();
1 cycrow 6391
	}
6392
}
6393
 
6394
void CPackages::CreateAnimations()
6395
{
6396
	// first check we have any ships
6397
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6398
		return;
6399
 
6400
	bool found = false;
6401
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6402
	{
6403
		SGameShip *s = node->Data();
6404
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6405
			continue;
6406
 
6407
		// no dummies to add?
6408
		if ( !s->pPackage->AnyAnimations() )
6409
			continue;
6410
		found = true;
6411
		break;
6412
	}
6413
 
6414
	if ( !found )
6415
		return;
6416
 
6417
	CyStringList aniList;
6418
	int e = ExtractGameFile("types/Animations.pck", m_sTempDir + "/Animations.txt");
6419
	if ( e )
6420
	{
6421
		CFileIO File;
118 cycrow 6422
		if ( File.open((e == -1) ? "Animations.txt" : m_sTempDir + "/Animations.txt") )
1 cycrow 6423
		{
6424
			std::vector<CyString> *lines = File.ReadLines();
6425
			if ( lines )
6426
			{
6427
				for ( int j = 0; j < (int)lines->size(); j++ )
6428
				{
6429
					CyString line(lines->at(j));
6430
					aniList.PushBack(line);
6431
				}
6432
 
6433
				delete lines;
6434
			}
6435
 
52 cycrow 6436
			File.remove();
1 cycrow 6437
		}
6438
	}
6439
 
6440
	CyStringList parsedAniList;
6441
	CXspFile::ReadAnimations(&aniList, &parsedAniList, 0);
6442
 
6443
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6444
	{
6445
		SGameShip *s = node->Data();
6446
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6447
			continue;
6448
 
6449
		// no dummies to add?
6450
		if ( !s->pPackage->AnyAnimations() )
6451
			continue;
6452
 
6453
		// add each dummy to list
6454
		for ( SStringList *strNode = s->pPackage->GetAnimations()->Head(); strNode; strNode = strNode->next )
6455
			parsedAniList.PushBack(strNode->str);
6456
	}
6457
 
6458
	// format the list with added spaces
6459
	CyStringList formatedAniList;
6460
	int lineCount = -1;
6461
	for ( SStringList *strNode = parsedAniList.Head(); strNode; strNode = strNode->next )
6462
	{
6463
		// format the comment to match the line number
6464
		lineCount++;
6465
		CyString oldComment = strNode->str.GetToken("//", 2);
6466
		CyString comment = CyString("//") + CyString::Number(lineCount);
6467
		if ( !oldComment.Empty() )
6468
		{
6469
			comment += " ";
6470
			oldComment.RemoveFirstSpace();
6471
			if ( oldComment.GetToken(" ", 1, 1).IsNumber() )
6472
				comment += oldComment.GetToken(" ", 2);
6473
			else
6474
				comment += oldComment;
6475
		}
6476
		CyString line = strNode->str.GetToken("//", 1, 1);
6477
 
6478
		// split into seperate lines
6479
		CyString first = line.GetToken(";", 1, 1);
6480
		if ( first.Compare("TAT_TAGSINGLESTEP") )
6481
		{
6482
			formatedAniList.PushBack(line.GetToken(";", 1, 5) + ";");
6483
			int max;
6484
			CyString *sLines = line.GetToken(";", 6).SplitToken(";", &max);
6485
			if ( max && sLines )
6486
			{
6487
				if ( sLines[max - 1].Empty() )
6488
					--max; // remove the last ";"
6489
 
6490
				for ( int i = 0; i < max; i++ )
6491
				{
6492
					CyString l = CyString("\t") + sLines[i] + ";";
6493
					if ( i == (max - 1) )
6494
						formatedAniList.PushBack(l + comment);
6495
					else
6496
						formatedAniList.PushBack(l);
6497
				}
6498
			}
6499
			CLEANSPLIT(sLines, max);
6500
		}
6501
		else if ( (first.Compare("TAT_TAGONESHOT") || first.Compare("TAT_TAGLOOP")) && (line.IsIn("TATF_COORDS")) )
6502
		{
6503
			formatedAniList.PushBack(line.GetToken(";", 1, 5) + ";");
6504
			int max;
6505
			CyString *sLines = line.GetToken(";", 6).SplitToken(";", &max);
6506
			if ( max && sLines )
6507
			{
6508
				if ( sLines[max - 1].Empty() )
6509
					--max; // remove the last ";"
6510
 
6511
				CyString prevLine;
6512
				for ( int i = 0; i < max; i++ )
6513
				{
6514
					CyString l = sLines[i] + ";";
6515
					if ( l.IsIn("TATF_COORDS") && !prevLine.Empty() )
6516
					{
6517
						formatedAniList.PushBack(CyString("\t") + prevLine);
6518
						prevLine = "";
6519
					}
6520
					prevLine += l;
6521
				}
6522
 
6523
				if ( !prevLine.Empty() )
6524
					formatedAniList.PushBack(CyString("\t") + prevLine + comment);
6525
 
6526
			}
6527
			CLEANSPLIT(sLines, max);
6528
		}
6529
		else
6530
			formatedAniList.PushBack(line + comment);
6531
	}
6532
 
6533
	formatedAniList.PushFront(CyString::Number(parsedAniList.Count()) + ";");
6534
	formatedAniList.PushFront(CyString("// Animations, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6535
 
6536
	// write the file to disk
6537
	CFileIO WriteFile(m_sTempDir + "/Animations.txt");
6538
	if ( WriteFile.WriteFile(&formatedAniList) )
6539
	{
6540
		this->PackFile(&WriteFile, "types\\Animations.pck");
52 cycrow 6541
		WriteFile.remove();
1 cycrow 6542
	}
6543
}
6544
 
6545
void CPackages::CreateBodies()
6546
{
6547
	// first check we have any ships
6548
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6549
		return;
6550
 
6551
	bool found = false;
6552
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6553
	{
6554
		SGameShip *s = node->Data();
6555
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6556
			continue;
6557
 
6558
		// no dummies to add?
6559
		if ( !s->pPackage->AnyBodies() )
6560
			continue;
6561
		found = true;
6562
		break;
6563
	}
6564
 
6565
	if ( !found )
6566
		return;
6567
 
6568
	// lets read our current bodies file
6569
	CLinkList<SBodies> bodiesList;
6570
	SBodies *currentSection = NULL;
6571
	int e = ExtractGameFile("types/Bodies.pck", m_sTempDir + "/Bodies.txt");
6572
	if ( e )
6573
	{
6574
		CFileIO File;
118 cycrow 6575
		if ( File.open((e == -1) ? "Bodies.txt" : m_sTempDir + "/Bodies.txt") )
1 cycrow 6576
		{
6577
			std::vector<CyString> *lines = File.ReadLines();
6578
			if ( lines )
6579
			{
6580
				int entries = 0;
6581
				for ( int j = 0; j < (int)lines->size(); j++ )
6582
				{
6583
					CyString line(lines->at(j));
6584
					line.RemoveChar(' ');
6585
					line.RemoveChar(9);
6586
					if ( line.Empty() || line[0] == '/' )
6587
						continue;
6588
					if ( entries <= 0 )
6589
					{
6590
						entries = line.GetToken(";", 2, 2).ToInt();
6591
						currentSection = new SBodies;
6592
						currentSection->sSection = line.GetToken(";", 1, 1);
6593
						bodiesList.push_back(currentSection);
6594
					}
6595
					else if ( currentSection )
6596
					{
6597
						int num;
6598
						CyString *strs = line.SplitToken(";", &num);
6599
						if ( num && strs )
6600
						{
6601
							for ( int i = 0; i < num; i++ )
6602
							{
6603
								if ( strs[i].Empty() )
6604
									continue;
6605
								currentSection->lEntries.PushBack(strs[i] + ";", true);
6606
								--entries;
6607
							}
6608
						}
6609
						CLEANSPLIT(strs, num);
6610
					}
6611
				}
6612
 
6613
				delete lines;
6614
			}
52 cycrow 6615
			File.remove();
1 cycrow 6616
		}
6617
	}
6618
 
6619
	// lets now add any new entries
6620
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6621
	{
6622
		SGameShip *s = node->Data();
6623
		if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6624
			continue;
6625
 
6626
		// no dummies to add?
6627
		if ( !s->pPackage->AnyBodies() )
6628
			continue;
6629
 
6630
		// add each dummy to list
6631
		for ( SStringList *strNode = s->pPackage->GetBodies()->Head(); strNode; strNode = strNode->next )
6632
		{
6633
			CyString section = strNode->str.GetToken(";", 1, 1);
6634
			CyString body = strNode->str.GetToken(";", 2).Remove(' ');
6635
			if ( body.Right(1) != ";" )
6636
				body += ";";
6637
 
6638
			// find the section to add into
6639
			SBodies *foundSection = NULL;
6640
			for ( CListNode<SBodies> *checkBody = bodiesList.Front(); checkBody; checkBody = checkBody->next() )
6641
			{
6642
				if ( checkBody->Data()->sSection.Compare(section) )
6643
				{
6644
					foundSection = checkBody->Data();
6645
					break;
6646
				}
6647
			}
6648
 
6649
			if ( !foundSection )
6650
			{
6651
				foundSection = new SBodies;
6652
				foundSection->sSection = section;
6653
				bodiesList.push_back(foundSection);
6654
			}
6655
			foundSection->lEntries.PushBack(body, true);
6656
		}
6657
	}
6658
 
6659
	// now write the file
6660
	CyStringList writeList;
6661
	// the header first
6662
	writeList.PushBack(CyString("// Bodies file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6663
	writeList.PushBack("//body type;num bodies;");
6664
	writeList.PushBack("//[body id/name]");
6665
 
6666
	// now our sections
6667
	for ( SBodies *bSection = bodiesList.First(); bSection; bSection = bodiesList.Next() )
6668
	{
6669
		writeList.PushBack("");
6670
		writeList.PushBack(CyString("// Section: ") + bSection->sSection);
6671
		writeList.PushBack(bSection->sSection + ";" + CyString::Number(bSection->lEntries.Count()) + ";");
6672
		for ( SStringList *strNode = bSection->lEntries.Head(); strNode; strNode = strNode->next )
6673
		{
6674
			CyString str = strNode->str;
6675
			str.RemoveChar(9);
6676
			str.RemoveChar(' ');
6677
			if ( str.Right(1) != ";" )
6678
				str += ";";
6679
			writeList.PushBack(str);
6680
		}
6681
	}
6682
 
6683
	// write the file to disk
6684
	CFileIO WriteFile(m_sTempDir + "/Bodies.txt");
6685
	if ( WriteFile.WriteFile(&writeList) )
6686
	{
6687
		this->PackFile(&WriteFile, "types\\Bodies.pck");
52 cycrow 6688
		WriteFile.remove();
1 cycrow 6689
	}
6690
}
6691
 
6692
void CPackages::CreateCustomStarts()
6693
{
6694
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
6695
	{
6696
		// find all spk files (only ones that can be custom starts
6697
		if ( node->Data()->GetType() != TYPE_SPK )
6698
			continue;
6699
 
6700
		CSpkFile *p = (CSpkFile *)node->Data();
6701
 
6702
		// only use custom starts
6703
		if ( !p->IsCustomStart() )
6704
			continue;
6705
 
6706
		// get the name of the start to use
6707
		CyString name = p->GetCustomStartName();
6708
		if ( name.Empty() )
6709
			continue;
6710
 
6711
		// find if maps file exists
6712
		CyStringList createFiles;
6713
		createFiles.PushBack(name, "maps/x3_universe");
6714
		createFiles.PushBack(name, "types/Jobs");
6715
		createFiles.PushBack(name, "types/JobWings");
6716
 
6717
		for ( SStringList *str = createFiles.Head(); str; str = str->next )
6718
		{
102 cycrow 6719
			Utils::String dir = CFileIO(str->data).dir();
1 cycrow 6720
			int type = FILETYPE_EXTRA;
6721
			if ( dir.Compare("maps") )
6722
				type = FILETYPE_MAP;
6723
 
6724
			if ( !p->FindFile(str->str + ".xml", type) && !p->FindFile(str->str + ".pck", type) )
6725
			{
6726
				// create a maps files
118 cycrow 6727
				int e = this->ExtractGameFile(str->data + ".pck", m_sTempDir + "/" + str->data.ToString() + ".pck");
1 cycrow 6728
				if ( e )
6729
				{
118 cycrow 6730
					CFileIO File((e == -1) ? (str->data + ".pck") : (m_sTempDir + "/" + str->data.ToString() + ".pck"));
52 cycrow 6731
					if ( File.exists() )
1 cycrow 6732
					{
6733
						File.Rename(m_sCurrentDir + "/" + dir + "/" + str->str + ".pck");
102 cycrow 6734
						this->AddCreatedFile(dir + "/" + str->str.ToString() + ".pck");
1 cycrow 6735
					}
6736
				}
6737
			}
6738
		}
6739
	}
6740
}
6741
 
6742
void CPackages::AddCreatedFile(CyString file)
6743
{
6744
	file = file.Remove(m_sCurrentDir);
6745
	while ( file[0] == '/' )
6746
		file.Erase(0, 1);
6747
	while ( file[0] == '\\' )
6748
		file.Erase(0, 1);
6749
 
6750
	m_lCreatedFiles.PushBack(file, true);
6751
}
6752
 
6753
void CPackages::CreateComponants()
6754
{
6755
	// first check we have any ships
6756
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
6757
		return;
6758
 
6759
	CLinkList<SComponantEntry> dummyList;
6760
 
6761
	// now extract the existing dummies
6762
	int e = ExtractGameFile("types/Components.pck", m_sTempDir + "/Components.txt");
6763
	if ( e )
6764
	{
6765
		// read the dummies
6766
		CFileIO File;
118 cycrow 6767
		if ( File.open((e == -1) ? "Components.txt" : m_sTempDir + "/Components.txt") )
1 cycrow 6768
		{
6769
			std::vector<CyString> *lines = File.ReadLines();
6770
			if ( lines )
6771
			{
6772
				int insection = 0;
6773
				int insubsection = 0;
6774
				SComponantEntry *currentSection = NULL;
6775
				SComponantEntry2 *currentSubSection = NULL;
6776
				for ( int j = 0; j < (int)lines->size(); j++ )
6777
				{
6778
					CyString line(lines->at(j));
6779
					if ( line[0] == '/' )
6780
						continue;
6781
					line.RemoveChar('\r');
6782
					line = line.RemoveFirstSpace();
6783
					line = line.RemoveEndSpace();
6784
					if ( line.Empty() )
6785
						continue;
6786
 
6787
 
6788
					// read the section, first entry is section, second is size
6789
					while ( !line.Empty() )
6790
					{
6791
						line = line.RemoveFirstSpace();
6792
						if ( line.Empty() )
6793
							break;
6794
 
6795
						if ( !insection && !insubsection )
6796
						{
6797
							CyString section = line.GetToken(";", 1, 1);
6798
							insection = line.GetToken(";", 2, 2).ToInt();
6799
 
6800
							// search for the sections
6801
							currentSection = NULL;
6802
							for ( CListNode<SComponantEntry> *node = dummyList.Front(); node; node = node->next() )
6803
							{
6804
								SComponantEntry *d = node->Data();
6805
								if ( d->sSection.Compare(section) )
6806
								{
6807
									currentSection = node->Data();
6808
									break;
6809
								}
6810
							}
6811
 
6812
							if ( !currentSection )
6813
							{
6814
								currentSection = new SComponantEntry;
6815
								currentSection->sSection = section;
6816
								dummyList.push_back(currentSection);
6817
							}
6818
 
6819
							// we have some more ?
6820
							line = line.DelToken(";", 1, 2);
6821
						}
6822
						else if ( !insubsection )
6823
						{
6824
							--insection;
6825
							CyString section = line.GetToken(";", 1, 1);
6826
							insubsection = line.GetToken(";", 2, 2).ToInt();
6827
 
6828
							currentSubSection = new SComponantEntry2;
6829
							currentSubSection->sSection = section;
6830
							currentSection->lEntries.push_back(currentSubSection);
6831
 
6832
							line = line.DelToken(";", 1, 2);
6833
						}
6834
						else
6835
						{
6836
							--insubsection;
6837
							currentSubSection->lEntries.PushBack(line.Remove(' '), true);
6838
							line = "";
6839
						}
6840
					}
6841
				}
6842
 
6843
				delete lines;
6844
			}
6845
 
52 cycrow 6846
			File.remove();
1 cycrow 6847
		}
6848
 
6849
		// add the new entries for the ships
6850
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
6851
		{
6852
			SGameShip *s = node->Data();
6853
			if ( s->iType != WARETYPE_ADDED || !s->pPackage )
6854
				continue;
6855
 
6856
			// no dummies to add?
6857
			if ( !s->pPackage->AnyComponents() )
6858
				continue;
6859
 
6860
			// add each dummy to list
6861
			for ( CListNode<SComponent> *dNode = s->pPackage->GetComponents()->Front(); dNode; dNode = dNode->next() )
6862
			{
6863
				SComponent *dummy = dNode->Data();
6864
				SComponantEntry *found = NULL;
6865
				SComponantEntry2 *found2 = NULL;
6866
				for ( CListNode<SComponantEntry> *eNode = dummyList.Front(); eNode; eNode = eNode->next() )
6867
				{
39 cycrow 6868
					if ( eNode->Data()->sSection.Compare(CyString(dummy->sSection)) )
1 cycrow 6869
					{
6870
						found = eNode->Data();
6871
						break;
6872
					}
6873
				}
6874
				if ( !found )
6875
				{
6876
					found = new SComponantEntry;
6877
					found->sSection = dummy->sSection;
6878
					dummyList.push_back(found);
6879
					found2 = new SComponantEntry2;
6880
					found2->sSection = dummy->sSection2;
6881
					found->lEntries.push_back(found2);
6882
				}
6883
				// else check for the 2nd section
6884
				else
6885
				{
6886
					for ( CListNode<SComponantEntry2> *cNode = found->lEntries.Front(); cNode; cNode = cNode->next() )
6887
					{
39 cycrow 6888
						if ( cNode->Data()->sSection.Compare(CyString(dummy->sSection2)) )
1 cycrow 6889
						{
6890
							found2 = cNode->Data();
6891
							break;
6892
						}
6893
					}
6894
 
6895
					if ( !found2 )
6896
					{
6897
						found2 = new SComponantEntry2;
6898
						found2->sSection = dummy->sSection2;
6899
						found->lEntries.push_back(found2);
6900
					}
6901
					else
6902
					{
6903
						bool f = false;
6904
						for ( SStringList *strNode = found2->lEntries.Head(); strNode; strNode = strNode->next )
6905
						{
39 cycrow 6906
							if ( dummy->sData.remove(' ').Compare(strNode->str.ToString()) )
1 cycrow 6907
							{
6908
								f = true;
6909
								break;
6910
							}
6911
						}
6912
 
6913
						if ( f )
6914
							continue;
6915
					}
6916
				}
6917
 
39 cycrow 6918
				found2->lEntries.PushBack(CyString(dummy->sData.remove(' ')));
1 cycrow 6919
			}
6920
		}
6921
 
6922
		// finally, write the file
6923
		std::vector<CyString> lines;
6924
		lines.push_back(CyString("// Components file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2));
6925
		for ( SComponantEntry *dummy = dummyList.First(); dummy; dummy = dummyList.Next() )
6926
		{
6927
			lines.push_back("");
6928
			lines.push_back(CyString("// Section: ") + dummy->sSection + " Entries: " + (long)dummy->lEntries.size());
6929
			lines.push_back(dummy->sSection + ";" + CyString::Number(dummy->lEntries.size()) + ";");
6930
			for ( CListNode<SComponantEntry2> *comp = dummy->lEntries.Front(); comp; comp = comp->next() )
6931
			{
6932
				lines.push_back(comp->Data()->sSection + ";" + (long)comp->Data()->lEntries.Count() + ";");
6933
				for ( SStringList *str = comp->Data()->lEntries.Head(); str; str = str->next )
6934
				{
6935
					CyString cStr = str->str;
6936
					cStr.RemoveEndSpace();
6937
					cStr.RemoveChar(9);
6938
					cStr.RemoveChar('\r');
6939
					if ( cStr.Right(1) != ";" )
6940
						cStr += ";";
6941
					lines.push_back(cStr);
6942
				}
6943
			}
6944
		}
6945
 
6946
		// write the file to disk
6947
		CFileIO WriteFile(m_sTempDir + "/Components.txt");
6948
		if ( WriteFile.WriteFile(&lines) )
6949
		{
6950
			this->PackFile(&WriteFile, "types\\Components.pck");
52 cycrow 6951
			WriteFile.remove();
1 cycrow 6952
		}
6953
	}
6954
}
6955
 
89 cycrow 6956
bool CPackages::readWares(int iLang, CLinkList<SWareEntry> &list)
88 cycrow 6957
{
89 cycrow 6958
	if ( iLang == 0 ) iLang = m_iLanguage;
88 cycrow 6959
 
89 cycrow 6960
	Utils::String empWares = this->empWaresForGame();
6961
 
6962
	for(CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next()) {
91 cycrow 6963
		if ( !node->Data()->IsEnabled() ) continue;
89 cycrow 6964
		node->Data()->readWares(iLang, list, empWares);
88 cycrow 6965
	}
6966
 
89 cycrow 6967
	return true;
6968
}
88 cycrow 6969
 
89 cycrow 6970
bool CPackages::readCommands(int iLang, CLinkList<SCommandSlot> &list)
6971
{
6972
	if ( iLang == 0 ) iLang = m_iLanguage;
6973
 
6974
	for(CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next()) {
91 cycrow 6975
		if ( !node->Data()->IsEnabled() ) continue;
89 cycrow 6976
		node->Data()->readCommands(iLang, list);
88 cycrow 6977
	}
6978
 
89 cycrow 6979
	return true;
6980
}
88 cycrow 6981
 
89 cycrow 6982
bool CPackages::readWingCommands(int iLang, CLinkList<SCommandSlot> &list)
6983
{
6984
	if ( iLang == 0 ) iLang = m_iLanguage;
6985
 
6986
	for(CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next()) {
91 cycrow 6987
		if ( !node->Data()->IsEnabled() ) continue;
89 cycrow 6988
		node->Data()->readWingCommands(iLang, list);
6989
	}
6990
 
88 cycrow 6991
	return true;
6992
}
6993
 
6994
int CPackages::_warePriceOverride(enum WareTypes type, int pos, const Utils::String &id)
6995
{
6996
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
6997
		if ( node->Data()->type == type ) {
6998
			if ( node->Data()->type == Ware_Custom && id.Compare(node->Data()->id) ) return node->Data()->relval;
6999
			else if ( node->Data()->type != Ware_Custom && node->Data()->pos == pos ) return node->Data()->relval;
7000
		}
7001
	}
7002
	return 0;
7003
}
7004
 
7005
bool CPackages::_wareNotoOverride(enum WareTypes type, int pos, const Utils::String &id, int *noto)
7006
{
7007
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
7008
		if ( node->Data()->type == type && node->Data()->bNotority ) {
7009
			if ( node->Data()->type == Ware_Custom && !id.Compare(node->Data()->id) ) continue;
7010
			else if ( node->Data()->type != Ware_Custom && node->Data()->pos != pos ) continue;
7011
 
7012
			(*noto) = node->Data()->notority;
7013
			return true;
7014
		}
7015
	}
7016
	return false;
7017
}
7018
 
7019
void CPackages::_removeWareOverride(enum WareTypes type, int pos, const Utils::String &id)
7020
{
7021
	for(CListNode<SWarePriceOverride> *node = m_lWarePrices.Front(); node; node = node->next()) {
7022
		if ( node->Data()->type == type ) {
7023
			if ( node->Data()->type == Ware_Custom && !id.Compare(node->Data()->id) ) continue;
7024
			else if ( node->Data()->type != Ware_Custom && node->Data()->pos != pos ) continue;
7025
			m_lWarePrices.remove(node);
7026
			break;
7027
		}
7028
	}
7029
}
7030
 
7031
int CPackages::empOveridePrice(int id)
7032
{
7033
	return _warePriceOverride(Ware_EMP, id, Utils::String::Null()); 
7034
}
7035
 
7036
bool CPackages::empOverideNoto(int id, int *noto)
7037
{
7038
	return _wareNotoOverride(Ware_EMP, id, Utils::String::Null(), noto);
7039
}
7040
 
7041
int CPackages::builtInWareOveridePrice(int id)
7042
{
7043
	return _warePriceOverride(Ware_BuiltIn, id, Utils::String::Null()); 
7044
}
7045
 
7046
bool CPackages::builtInWareOverideNoto(int id, int *noto)
7047
{
7048
	return _wareNotoOverride(Ware_BuiltIn, id, Utils::String::Null(), noto);
7049
}
7050
 
7051
int CPackages::customWareOveridePrice(const Utils::String &id)
7052
{
7053
	return _warePriceOverride(Ware_Custom, 0, id); 
7054
}
7055
 
7056
bool CPackages::customWareOverideNoto(const Utils::String &id, int *noto)
7057
{
7058
	return _wareNotoOverride(Ware_Custom, 0, id, noto);
7059
}
7060
 
7061
void CPackages::removeEmpOverride(int pos)
7062
{
7063
	_removeWareOverride(Ware_EMP, pos, Utils::String::Null());
7064
}
7065
 
7066
void CPackages::removeBuiltinWareOverride(int pos)
7067
{
7068
	_removeWareOverride(Ware_BuiltIn, pos, Utils::String::Null());
7069
}
7070
 
7071
void CPackages::removeCustomWareOverride(const Utils::String &id)
7072
{
7073
	_removeWareOverride(Ware_Custom, 0, id);
7074
}
7075
 
7076
 
1 cycrow 7077
bool CPackages::ReadGlobals(CyStringList &globals)
7078
{
7079
	int e = ExtractGameFile("types/Globals.pck", m_sTempDir);
7080
	if ( e )
7081
	{
118 cycrow 7082
		CFileIO File((e == -1) ? "Globals.txt" : m_sTempDir + "/Globals.txt");
52 cycrow 7083
		if ( File.exists() )
1 cycrow 7084
		{
7085
			CyStringList *lines = File.ReadLinesStr();
7086
			if ( lines )
7087
			{
7088
				int entries = -1;
7089
				for ( SStringList *str = lines->Head(); str; str = str->next )
7090
				{
7091
					str->str.RemoveChar('\r');
7092
					str->str.RemoveChar(9);
7093
					str->str.RemoveFirstSpace();
7094
 
7095
					if ( str->str.Empty() )
7096
						continue;
7097
					if ( str->str[0] == '/' )
7098
						continue;
7099
 
7100
					// remove comments
7101
					CyString l = str->str;
7102
					if ( l.IsIn("/") ) 
7103
						l = l.GetToken("/", 1, 1);
7104
 
7105
					if ( entries == -1 )
7106
						entries = l.GetToken(";", 1, 1).ToInt();
7107
					else
7108
						globals.PushBack(l.GetToken(";", 1, 1), l.GetToken(";", 2, 2));
7109
				}
7110
 
7111
				delete lines;
7112
 
7113
				return true;
7114
			}
7115
		}
7116
	}
7117
 
7118
	return false;
7119
}
7120
 
7121
void CPackages::CreateGlobals()
7122
{
7123
	if ( m_lGlobals.Empty() )
7124
		return; // no global settings
7125
 
7126
	CyStringList globals;
7127
	if ( ReadGlobals(globals) )
7128
	{
7129
		// apply out settings
7130
		for ( SStringList *str = m_lGlobals.Head(); str; str = str->next )
7131
		{
7132
			SStringList *found = globals.FindString(str->str);
7133
			if ( found )
7134
				found->data = str->data;
7135
		}
7136
 
7137
		// now write it
7138
		CyStringList writeList;
7139
		for ( SStringList *str = globals.Head(); str; str = str->next )
7140
			writeList.PushBack(str->str + ";" + str->data + ";");
7141
 
7142
		// finally, write the file
7143
		writeList.PushFront(CyString::Number(writeList.Count()) + "; /globals amount", "");
7144
		writeList.PushFront(CyString("// Globals file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2), "");
7145
 
7146
		CFileIO WriteFile(m_sTempDir + "/Globals.txt");
7147
		if ( WriteFile.WriteFile(&writeList) )
7148
		{
7149
			this->PackFile(&WriteFile, "types/Globals.pck");
52 cycrow 7150
			WriteFile.remove();
1 cycrow 7151
		}
7152
	}
7153
}
7154
 
7155
void CPackages::CreateTShips()
7156
{
7157
	// no ships ?
7158
	if ( m_lGameShips.empty() )
7159
		return;
7160
 
7161
	// get the cockpit list to match with ships turrets
7162
	CyStringList Cockpits;
7163
	CyStringList *cockpitList = this->CreateCockpits();
7164
	if ( cockpitList )
7165
	{
7166
		for ( SStringList *str = cockpitList->Head(); str; str = str->next )
7167
		{
7168
			CyString id = str->str.GetToken(";", 19, 19);
7169
			Cockpits.PushBack(id);
7170
		}
7171
 
7172
		delete cockpitList;
7173
	}
7174
 
7175
	CLinkList<SGameShip> shipOverrides;
7176
	for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
7177
	{
7178
		if ( node->Data()->iType != WARETYPE_ADDED || !node->Data()->pPackage )
7179
			continue;		
7180
		if ( !node->Data()->pPackage->IsExistingShip() )
7181
			continue;
7182
		shipOverrides.push_back(node->Data());
7183
	}
7184
 
7185
	// read the existing tships file
7186
	int e = ExtractGameFile("types/TShips.pck", m_sTempDir + "/TShips.txt");
7187
	if ( e )
7188
	{
7189
		int fileType = 51;
7190
		CyStringList tshipsList;
7191
 
7192
		// if we have no buffer, lets create one
7193
		CFileIO File;
118 cycrow 7194
		if ( File.open((e == -1) ? "TShips.txt" : m_sTempDir + "/TShips.txt") )
1 cycrow 7195
		{
7196
			int shiptext = SHIPSTARTTEXT;
7197
 
7198
			std::vector<CyString> *lines = File.ReadLines();
7199
			if ( lines )
7200
			{
7201
				int count = -1;
7202
				for ( int j = 0; j < (int)lines->size(); j++ )
7203
				{
7204
					CyString line(lines->at(j));
7205
					if ( line[0] == '/' )
7206
						continue;
7207
					line.RemoveChar('\r');
7208
					line.RemoveChar(9);
7209
					line = line.RemoveFirstSpace();
7210
					line = line.RemoveEndSpace();
7211
					if ( line.Empty() )
7212
						continue;
7213
 
7214
					if ( count == -1 )
7215
					{
7216
						fileType = line.GetToken(";", 1, 1).ToInt();
7217
						count = line.GetToken(";", 2, 2).ToInt();
7218
					}
7219
					else
7220
					{
7221
						if ( line.Right(1) != ";" )
7222
							line += ";";
7223
 
7224
						// check for any ship overrides
7225
						bool added = false;
7226
						if ( !shipOverrides.empty() )
7227
						{
7228
							CShipData shipData;
7229
							if ( shipData.ReadShipData(line) )
7230
							{
7231
								for ( CListNode<SGameShip> *node = shipOverrides.Front(); node; node = node->next() )
7232
								{
7233
									SGameShip *s = node->Data();
14 cycrow 7234
									if ( !s->pPackage->GetShipID().Compare(shipData.sID.ToString()) )
1 cycrow 7235
										continue;
7236
									s->iText = shiptext;
7237
									if ( !s->pPackage->GetOriginalDescription() )
7238
										shiptext += 2;
7239
									s->iPos = tshipsList.Count();
7240
									added = true;
39 cycrow 7241
									tshipsList.PushBack(CyString(s->pPackage->FormatShipData(&Cockpits, &s->iText, m_iGame)));
1 cycrow 7242
									shipOverrides.remove(node);
7243
									break;
7244
								}
7245
							}
7246
						}
7247
 
7248
						if ( !added )
7249
							tshipsList.PushBack(line);
7250
						--count;
7251
						if ( count < 0 )
7252
							break;
7253
					}
7254
				}
7255
 
7256
				delete lines;
7257
 
7258
			}
7259
 
52 cycrow 7260
			File.remove();
1 cycrow 7261
 
7262
			// assign the ship buffer
7263
			if ( !m_iShipBuffer )
7264
				m_iShipBuffer = tshipsList.Count() + 15;
7265
			// there seems to be too many additional entries, we have no choise but to change the buffer
7266
			else if ( m_iShipBuffer <= tshipsList.Count() )
7267
				m_iShipBuffer = tshipsList.Count() + 15;
7268
 
7269
			CyString bufferStart;
7270
			if ( m_iGame == GAME_X3 )
7271
				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;";
7272
			else
7273
				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;";
7274
			// add the buffers now
7275
			for ( int i = tshipsList.Count(); i < m_iShipBuffer; i++ )
7276
				tshipsList.PushBack(bufferStart + "SHIP_BUFFER;");
7277
 
7278
			// now lets add our tships line
7279
			for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
7280
			{
7281
				SGameShip *s = node->Data();
7282
				if ( s->pPackage && s->pPackage->IsExistingShip() )
7283
					continue;
7284
				s->iPos = tshipsList.Count();
7285
				if ( s->iType == WARETYPE_ADDED && s->pPackage )
7286
				{
7287
					s->iText = shiptext;
7288
					if ( !s->pPackage->GetOriginalDescription() )
7289
						shiptext += 2;
7290
 
39 cycrow 7291
					tshipsList.PushBack(CyString(s->pPackage->FormatShipData(&Cockpits, &s->iText, m_iGame)));
1 cycrow 7292
				}
7293
				else if ( s->iType == WARETYPE_DELETED )
7294
					tshipsList.PushBack(bufferStart + "SHIP_DELETED;");
7295
				else if ( s->iType == WARETYPE_DISABLED )
7296
					tshipsList.PushBack(bufferStart + "SHIP_DISABLED;");
7297
				else
7298
					tshipsList.PushBack(bufferStart + "SHIP_SPACER;");
7299
			}
7300
 
7301
			// finally, write the file
7302
			tshipsList.PushFront(CyString::Number(fileType) + ";" + CyString::Number(tshipsList.Count()) + ";", "");
7303
			tshipsList.PushFront(CyString("// TShips file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2), "");
7304
 
7305
			CFileIO WriteFile(m_sTempDir + "/TShips.txt");
7306
			if ( WriteFile.WriteFile(&tshipsList) )
7307
			{
7308
				this->PackFile(&WriteFile, "types/TShips.pck");
52 cycrow 7309
				WriteFile.remove();
1 cycrow 7310
			}
7311
		}
7312
	}
7313
 
7314
}
7315
 
7316
bool CPackages::PackFile(CyString filename)
7317
{
7318
	// compress the file
7319
	CFileIO File(filename);
7320
	size_t fileSize;
7321
	char *fileData = File.ReadToData(&fileSize);
7322
 
7323
	if ( fileData && fileSize)
7324
	{
7325
		size_t newFileSize;
7326
		unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
7327
		if ( pckData )
7328
		{
7329
			CyString ext = "pck";
7330
			if ( File.CheckFileExtension("bob") )
7331
				ext = "pbb";
7332
			else if ( File.CheckFileExtension("bod") )
7333
				ext = "pbd";
7334
			CFileIO pckFile(File.ChangeFileExtension(ext));
121 cycrow 7335
			if ( !CDirIO(pckFile.dir()).exists() )
102 cycrow 7336
				CDirIO(pckFile.dir()).Create();
1 cycrow 7337
			pckFile.WriteData((char *)pckData, newFileSize);
7338
			return true;
7339
		}
7340
	}
7341
 
7342
	return false;
7343
}
7344
 
7345
bool CPackages::UnPackFile(CyString filename, bool checkxml)
7346
{
7347
	// compress the file
7348
	CFileIO File(filename);
7349
	size_t fileSize;
7350
	char *fileData = File.ReadToData(&fileSize);
7351
 
7352
	if ( fileData && fileSize)
7353
	{
7354
		size_t newFileSize;
96 cycrow 7355
		unsigned char *pckData = UnPCKData((unsigned char *)fileData, fileSize, &newFileSize, false);
7356
		if ( !pckData )
7357
			pckData = UnPCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
7358
 
1 cycrow 7359
		if ( pckData )
7360
		{
7361
			CyString ext = "txt";
7362
			if ( File.CheckFileExtension("pbb") )
7363
				ext = "bob";
7364
			else if ( File.CheckFileExtension("pbd") )
7365
				ext = "bod";
7366
			CFileIO pckFile(File.ChangeFileExtension(ext));
121 cycrow 7367
			if ( !CDirIO(pckFile.dir()).exists() )
102 cycrow 7368
				CDirIO(pckFile.dir()).Create();
1 cycrow 7369
			pckFile.WriteData((char *)pckData, newFileSize);
7370
 
7371
			// check for xml and rename
7372
			if ( checkxml )
7373
			{
7374
				int readmaxlines = 20;
7375
				bool isxml = false;
7376
				do {
52 cycrow 7377
					CyString line = pckFile.readEndOfLine();
1 cycrow 7378
					if ( line.IsIn("<language id=") )
7379
					{
7380
						isxml = true;
7381
						break;
7382
					}
7383
					else if ( line.IsIn("<page id=") )
7384
					{
7385
						isxml = true;
7386
						break;
7387
					}
7388
					else if ( line.IsIn("<?xml") || line.IsIn("<script>") )
7389
					{
7390
						isxml = true;
7391
						break;
7392
					}
7393
					--readmaxlines;
7394
					if ( readmaxlines <= 0 )
7395
						break;
52 cycrow 7396
				} while (pckFile.isOpened());
1 cycrow 7397
 
52 cycrow 7398
				if ( pckFile.isOpened() )
82 cycrow 7399
					pckFile.close();
1 cycrow 7400
 
7401
				if ( isxml )
7402
					pckFile.Rename(pckFile.ChangeFileExtension("xml"));
7403
			}
7404
 
7405
			return true;
7406
		}
7407
	}
7408
 
7409
	return false;
7410
}
7411
 
7412
bool CPackages::PackFile(CFileIO *File, CyString filename)
7413
{
7414
	filename = filename.FindReplace("\\", "/");
7415
	if ( m_iGame == GAME_X3 )
7416
	{
7417
		CCatFile catFile;
125 cycrow 7418
		int error = catFile.open((m_sCurrentDir + "/mods/PluginManager.cat").ToString(), this->getAddonDir(), CATREAD_CATDECRYPT, true);
1 cycrow 7419
		if ( error == CATERR_NONE || error == CATERR_CREATED )
7420
		{
7421
			// it it wrote ok, remove the old ones
102 cycrow 7422
			if ( !catFile.AppendFile(File->fullFilename(), filename.ToString(), true, true) )
1 cycrow 7423
				return false;
7424
			return true;
7425
		}
7426
	}
7427
	else
7428
	{
7429
		// compress the file
7430
		size_t fileSize;
102 cycrow 7431
		char *fileData = CFileIO(File->fullFilename()).ReadToData(&fileSize);
1 cycrow 7432
 
7433
		if ( fileData && fileSize)
7434
		{
7435
			size_t newFileSize;
7436
			unsigned char *pckData = PCKData((unsigned char *)fileData, fileSize, &newFileSize, true);
7437
			if ( pckData )
7438
			{
7439
//				if ( !this->GetAddonDir().Empty() && CCatFile::IsAddonDir(filename) )
7440
//					filename = this->GetAddonDir() + "/" + filename;
7441
				CFileIO pckFile(m_sCurrentDir + "/" + filename);
121 cycrow 7442
				if ( !CDirIO(pckFile.dir()).exists() )
102 cycrow 7443
					CDirIO(pckFile.dir()).Create();
1 cycrow 7444
				pckFile.WriteData((char *)pckData, newFileSize);
102 cycrow 7445
				this->AddCreatedFile(pckFile.fullFilename());
1 cycrow 7446
				return true;
7447
			}
7448
		}
7449
	}
7450
 
7451
	return false;
7452
}
7453
 
7454
CyStringList *CPackages::CreateCockpits()
7455
{
7456
	// first check we have any ships
7457
	if ( m_lGameShips.empty() || !this->CountPackages(TYPE_XSP, true) )
7458
		return NULL;
7459
 
7460
	CyStringList *cockpitList = new CyStringList;
7461
 
7462
	// now extract the existing cockpits
7463
	int fileType = 51;
7464
	int e = ExtractGameFile("types/TCockpits.pck", m_sTempDir + "/TCockpits.txt");
7465
	if ( e )
7466
	{
7467
		// read the dummies
7468
		CFileIO File;
118 cycrow 7469
		if ( File.open((e == -1) ? "TCockpits.txt" : m_sTempDir + "/TCockpits.txt") )
1 cycrow 7470
		{
7471
			CyStringList *lines = File.ReadLinesStr();
7472
			if ( lines )
7473
			{
7474
				int count = -1;
7475
				for ( SStringList *str = lines->Head(); str; str = str->next )
7476
				{
7477
					CyString line(str->str);
7478
					line.RemoveChar('\r');
7479
					line.RemoveChar(9);
7480
					line = line.RemoveFirstSpace();
7481
					line = line.RemoveEndSpace();
7482
					if ( line.Empty() )
7483
						continue;
7484
					if ( line[0] == '/' )
7485
						continue;
7486
 
7487
					if ( count == -1 )
7488
					{
7489
						fileType = line.GetToken(";", 1, 1).ToInt();
7490
						count = line.GetToken(";", 2, 2).ToInt();
7491
					}
7492
					else
7493
					{
7494
						while ( !line.Empty() )
7495
						{
7496
							CyString data = line.GetToken(";", 1, 19);
7497
							cockpitList->PushBack(data + ";");
7498
							line = line.DelToken(";", 1, 19);
7499
 
7500
							--count;
7501
							if ( count < 1 )
7502
								break;
7503
						}
7504
					}
7505
				}
7506
 
7507
				delete lines;
7508
			}
7509
 
52 cycrow 7510
			File.remove();
1 cycrow 7511
		}
7512
 
7513
		// now add the new ones
7514
		for ( CListNode<SGameShip> *node = m_lGameShips.Front(); node; node = node->next() )
7515
		{
7516
			SGameShip *s = node->Data();
7517
			if ( s->iType != WARETYPE_ADDED || !s->pPackage )
7518
				continue;
7519
 
7520
			if ( !s->pPackage->AnyCockpits() )
7521
				continue;
7522
 
7523
			for ( CListNode<SCockpit> *cn = s->pPackage->GetCockpits()->Front(); cn; cn = cn->next() )
7524
			{
7525
				bool foundEntry = false;
7526
				CyString cockpitStr = cn->Data()->sCockpit;
7527
				// search for matching game entry
7528
				for ( CListNode<SWeaponMask> *wm = cn->Data()->lWeaponMask.Front(); wm; wm = wm->next() )
7529
				{
7530
					if ( wm->Data()->iGame == (m_iGame - 1) )
7531
					{
7532
						if ( wm->Data()->iMask != -1 )
7533
							cockpitStr = cockpitStr.RepToken(";", 9, CyString::Number(wm->Data()->iMask));
7534
						foundEntry = true;
7535
						break;
7536
					}
7537
				}
39 cycrow 7538
 
7539
				bool found = false;
1 cycrow 7540
				for ( SStringList *str = cockpitList->Head(); str; str = str->next )
7541
				{
39 cycrow 7542
					if ( str->str.GetToken(";", 19, 19).Compare(CyString(cn->Data()->sCockpit.token(";", 19))) )
1 cycrow 7543
					{
7544
						// only replace existing entry if we have sepeperate weapon masks set
7545
						if ( foundEntry )
7546
							str->str = cockpitStr;
7547
						found = true;
7548
						break;
7549
					}
7550
				}
7551
 
7552
				if ( !found )
7553
					cockpitList->PushBack(cockpitStr);
7554
			}
7555
		}
7556
 
7557
		// finally, write the file
7558
		cockpitList->PushFront(CyString::Number(fileType) + ";" + CyString::Number(cockpitList->Count()) + ";", "");
7559
		cockpitList->PushFront(CyString("// TCockpits file, created by SPK Libraries V") + CyString::CreateFromFloat(GetLibraryVersion(), 2), "");
7560
 
7561
		CFileIO WriteFile(m_sTempDir + "/TCockpits.txt");
7562
		if ( WriteFile.WriteFile(cockpitList) )
7563
		{
7564
			this->PackFile(&WriteFile, "types\\TCockpits.pck");
52 cycrow 7565
			WriteFile.remove();
1 cycrow 7566
		}
7567
 
7568
		// remove those entrys
7569
		cockpitList->PopFront();
7570
		cockpitList->PopFront();
7571
	}
7572
 
7573
	return cockpitList;
7574
}
7575
 
7576
CBaseFile *CPackages::FindScriptByAuthor(CyString author, CBaseFile *prev)
7577
{
7578
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
7579
	{
7580
		CBaseFile *p = node->Data();
7581
		if ( prev )
7582
		{
7583
			if ( p == prev )
7584
				prev = NULL;
7585
			continue;
7586
		}
50 cycrow 7587
		if ( p->author().Compare(author.ToString()) )
1 cycrow 7588
			return p;
7589
	}
7590
 
7591
	return NULL;
7592
}
7593
 
129 cycrow 7594
bool CPackages::extractAll(CBaseFile *baseFile, const Utils::String &dir, int game, bool includedir, CProgressInfo *progress) const
7595
{
7596
	if (!baseFile)
7597
		return false;
7598
 
7599
	Utils::CStringList gameAddons;
7600
	for (unsigned int i = 0; i < m_gameExe.gameCount(); ++i)
7601
	{
7602
		SGameExe *exe = m_gameExe.GetGame(i);
7603
		if (!exe->sAddon.empty())
7604
			gameAddons.pushBack(Utils::String::Number(i + 1), exe->sAddon);
7605
	}
7606
 
7607
	return baseFile->extractAll(dir, game, gameAddons, includedir, progress);
7608
}
7609
 
127 cycrow 7610
bool CPackages::generatePackagerScript(CBaseFile *baseFile, bool wildcard, Utils::CStringList *list, int game, bool datafile) const
7611
{	
7612
	if (!baseFile)
7613
		return false;
7614
 
7615
	Utils::CStringList gameAddons;
7616
	for (unsigned int i = 0; i < m_gameExe.gameCount(); ++i)
7617
	{
7618
		SGameExe *exe = m_gameExe.GetGame(i);
7619
		if (!exe->sAddon.empty())
7620
			gameAddons.pushBack(Utils::String::Number(i + 1), exe->sAddon);
7621
	}
7622
 
7623
	return baseFile->GeneratePackagerScript(wildcard, list, game, gameAddons, datafile);
7624
}
7625
 
131 cycrow 7626
CBaseFile *CPackages::LoadPackagerScript(const Utils::String &filename, int compression, Utils::String (*askFunc)(const Utils::String &), Utils::CStringList *malformedLines, Utils::CStringList *unknownCommands, Utils::CStringList *variables)
1 cycrow 7627
{
7628
	// check the file exists
131 cycrow 7629
	if ( !CFileIO::Exists(filename) )
1 cycrow 7630
		return NULL;
7631
 
7632
	// read all the lines
7633
	CFileIO File(filename);
98 cycrow 7634
	if ( !File.startRead() ) 
1 cycrow 7635
		return NULL;
7636
 
98 cycrow 7637
	Utils::CStringList fileData;
7638
 
7639
	int iLine = 0;
7640
 
1 cycrow 7641
	CBaseFile *package = NULL;
7642
 
98 cycrow 7643
	while(!File.atEnd()) {
7644
		// read the next line in the file
7645
		Utils::String line = File.readEndOfLine();
1 cycrow 7646
 
98 cycrow 7647
		// filter out any characters we dont really want
7648
		line.removeChar("\t\r");
7649
		line.removeFirstSpace();
1 cycrow 7650
 
98 cycrow 7651
		if ( line.empty() ) continue;
1 cycrow 7652
 
98 cycrow 7653
		// check for any comments (so we can ignore them)
7654
		if ( line.left(2).Compare("//") || line[0] == '#' ) continue;
1 cycrow 7655
 
98 cycrow 7656
		++iLine;
7657
 
1 cycrow 7658
		// all commands start with a keyword followed by a colon, if one doesn't exist, it cant be a valid line
131 cycrow 7659
		if ( !line.contains(':') )
1 cycrow 7660
		{
7661
			// there are some exeptions, and these are one word entrys only
98 cycrow 7662
			line.removeEndSpace();
131 cycrow 7663
			if ( line.contains(" ") )
1 cycrow 7664
			{
7665
				if ( malformedLines )
131 cycrow 7666
					malformedLines->pushBack(line, Utils::String::Number(iLine));
1 cycrow 7667
				continue;
7668
			}
7669
		}
7670
 
7671
		// check for the type line
98 cycrow 7672
		if ( !package && line.token(":", 1).Compare("FileType") )
1 cycrow 7673
		{
98 cycrow 7674
			Utils::String sFileType = line.tokens(":", 2).removeFirstSpace();
1 cycrow 7675
			if ( sFileType.Compare("Ship") )
7676
				package = new CXspFile();
7677
			else if ( sFileType.Compare("Script") )
7678
				package = new CSpkFile();
7679
			else if ( sFileType.Compare("Base") )
7680
				package = new CBaseFile();
98 cycrow 7681
			continue;
1 cycrow 7682
		}
7683
 
98 cycrow 7684
		fileData.pushBack(line, Utils::String::Number(iLine));
1 cycrow 7685
	}
7686
 
7687
	// assume its a script if no type is set (all old versions are scripts)
7688
	if ( !package )
7689
		package = new CSpkFile();
7690
 
7691
	if ( compression != -1 )
7692
		package->SetDataCompression(compression);
7693
 
7694
	CyString ftpaddr;
7695
	CyString ftpuser;
7696
	CyString ftppass;
7697
	CyString ftpdir;
98 cycrow 7698
	Utils::String sMainGame;
7699
	Utils::CStringList otherGames;
127 cycrow 7700
	Utils::CStringList gameAddons;
7701
	for (unsigned int i = 0; i < m_gameExe.gameCount(); ++i)
7702
	{
7703
		SGameExe *exe = m_gameExe.GetGame(i);
7704
		if (!exe->sAddon.empty())
7705
			gameAddons.pushBack(Utils::String::Number(i + 1), exe->sAddon);
7706
	}
98 cycrow 7707
 
1 cycrow 7708
	// now lets read the rest of the day
131 cycrow 7709
	Utils::CStringList listVaribles;
7710
	for (Utils::SStringList *line = fileData.first(); line; line = fileData.next())
1 cycrow 7711
	{
98 cycrow 7712
		Utils::String cmd = line->str.token(":", 1);
7713
		Utils::String rest = line->str.tokens(":", 2).removeFirstSpace();
1 cycrow 7714
 
131 cycrow 7715
		if (cmd.Compare("Varible") || cmd.Compare("Variable"))
7716
		{
7717
			Utils::String s1 = rest.token(" ", 1);
7718
			Utils::String s2 = rest.tokens(" ", 2);
7719
			if(!listVaribles.changeData(s1, s2))
7720
				listVaribles.pushBack(s1, s2);
7721
		}
1 cycrow 7722
		else
7723
		{
7724
			// replace variables
98 cycrow 7725
			if ( rest.isin("$") )
1 cycrow 7726
			{
131 cycrow 7727
				for (Utils::SStringList *strVar = listVaribles.first(); strVar; strVar = listVaribles.next())
1 cycrow 7728
				{
131 cycrow 7729
					if ( rest.contains(strVar->str) )
7730
						rest = rest.findReplace(strVar->str, strVar->data);
1 cycrow 7731
				}
7732
 
7733
				if ( variables )
7734
				{
131 cycrow 7735
					for (Utils::SStringList *strVar = variables->first(); strVar; strVar = variables->next())
1 cycrow 7736
					{
131 cycrow 7737
						if ( rest.contains(strVar->str) )
7738
							rest = rest.findReplace(strVar->str, strVar->data);
1 cycrow 7739
					}
7740
				}
7741
			}
7742
 
7743
			//check for the built in varibles
127 cycrow 7744
			if ( rest.contains("$ASK") )
1 cycrow 7745
			{
98 cycrow 7746
				Utils::String replace = "$ASK";
7747
				Utils::String result;
1 cycrow 7748
 
7749
				if ( askFunc )
127 cycrow 7750
					result = askFunc(cmd);
1 cycrow 7751
 
127 cycrow 7752
				if ( rest.contains("$ASK(") )
1 cycrow 7753
				{
98 cycrow 7754
					replace = rest.tokens("$ASK(", 2).token(")", 1);
7755
					if ( result.empty() )
1 cycrow 7756
						result = replace;
98 cycrow 7757
					replace = "$ASK(" + replace + ")";
1 cycrow 7758
				}
7759
 
98 cycrow 7760
				if ( !result.empty() )
7761
					rest = rest.findReplace(replace, result);
1 cycrow 7762
			}
7763
			// todays date
98 cycrow 7764
			if ( rest.isin("$DATE") )
1 cycrow 7765
			{
7766
				time_t now;
7767
				time(&now);
7768
				struct tm *timeinfo = localtime(&now);
98 cycrow 7769
				Utils::String result = Utils::String::Number(timeinfo->tm_mday) + "." + Utils::String::Number(timeinfo->tm_mon + 1) + "." + Utils::String::Number(timeinfo->tm_year + 1900);
7770
				if ( !result.empty() )
7771
					rest = rest.findReplace("$DATE", result);
1 cycrow 7772
			}
7773
			// mydocuments
98 cycrow 7774
			if ( rest.isin("$MYDOCUMENTS") )
1 cycrow 7775
			{
127 cycrow 7776
				if ( !m_sMyDoc.empty() )
7777
					rest = rest.findReplace("$MYDOCUMENTS", m_sMyDoc);
1 cycrow 7778
			}
7779
 
7780
			// current path
98 cycrow 7781
			if ( rest.isin("$PATH") )
1 cycrow 7782
			{
102 cycrow 7783
				Utils::String currentDir = CFileIO(filename).dir();
98 cycrow 7784
				if ( !currentDir.empty() )
7785
					rest = rest.findReplace("$PATH", currentDir);
1 cycrow 7786
			}
7787
 
7788
			// now parse the rest of the values
98 cycrow 7789
			if ( cmd.Compare("FtpUpload") )
7790
				ftpaddr = rest.token(" ", 1) + ":" + rest.token(" ", 2);
7791
			else if ( cmd.Compare("FtpUser") )
1 cycrow 7792
				ftpuser = rest;
98 cycrow 7793
			else if ( cmd.Compare("FtpPass") )
1 cycrow 7794
				ftppass = rest;
98 cycrow 7795
			else if ( cmd.Compare("FtpDir") )
1 cycrow 7796
				ftpdir = rest;
98 cycrow 7797
			else if ( cmd.Compare("MultiGames") ) {
7798
				sMainGame = rest.token(" ", 1);
7799
				otherGames.tokenise(rest.tokens(" ", 2), " ");
7800
			}
127 cycrow 7801
			else if ( !package->LoadPackageData(cmd, rest, sMainGame, otherGames, gameAddons) )
1 cycrow 7802
			{
7803
				if ( unknownCommands )
131 cycrow 7804
					unknownCommands->pushBack(cmd, rest);
1 cycrow 7805
			}
7806
		}
7807
	}
7808
 
50 cycrow 7809
	if ( package->filename().empty() )
127 cycrow 7810
		package->LoadPackageData("AutoSave", "$AUTOSAVE", sMainGame, otherGames, gameAddons);
1 cycrow 7811
 
131 cycrow 7812
	if (package->autoExtraction())
7813
	{
7814
		for (auto itr = package->autoExtraction()->begin(); itr != package->autoExtraction()->end(); itr++)
7815
		{
7816
			unsigned int game = itr->first;
7817
			for (auto node = package->fileList()->Front(); node; node = node->next())
7818
			{
7819
				C_File *f = node->Data();
7820
				if (f->game() && f->game() != GAME_ALLNEW && !(f->game() & (1 << game)))
7821
					continue;
7822
				package->extractFile(f, itr->second, game, gameAddons);
7823
			}
7824
		}
7825
	}
7826
 
7827
	if (package->autoExporter())
7828
	{
7829
		for (auto itr = package->autoExporter()->begin(); itr != package->autoExporter()->end(); itr++)
7830
			package->saveToArchive(itr->second, itr->first, &m_gameExe);
7831
	}
7832
 
1 cycrow 7833
	if ( !ftpaddr.Empty() )
7834
	{
7835
		if ( !ftpuser.Empty() )
7836
		{
7837
			if ( !ftppass.Empty() )
7838
				ftpaddr = ftpuser + ":" + ftppass + "@" + ftpaddr;
7839
			else
7840
				ftpaddr = ftpuser + "@" + ftpaddr;
7841
		}
7842
 
7843
		if ( !ftpdir.Empty() )
7844
			ftpaddr += ftpdir;
7845
 
7846
		package->SetFtpAddr(ftpaddr);
7847
	}
7848
 
7849
	return package;
7850
}
7851
 
121 cycrow 7852
CyString CPackages::GetLanguageName() const
1 cycrow 7853
{
7854
	return CPackages::ConvertLanguage(m_iLanguage);
7855
}
7856
 
133 cycrow 7857
int CPackages::findAllPackages(CLinkList<CBaseFile> &packages, const Utils::String &dir)
7858
{
7859
	int count = 0;
7860
	if (!dir.empty())
7861
	{
7862
		count += findPackageDirectories(packages, dir + "/Addons");
7863
		count += findPackageDirectories(packages, dir + "/Downloads");
7864
	}
7865
 
7866
	count += findPackageDirectories(packages, "./Addons");
7867
	count += findPackageDirectories(packages, "./Downloads");
7868
 
7869
	if (_pCurrentDir)
7870
	{
7871
		count += findPackageDirectories(packages, _pCurrentDir->dir + "/Addons");
7872
		count += findPackageDirectories(packages, _pCurrentDir->dir + "/Downloads");
7873
		count += findPackageDirectories(packages, _pCurrentDir->dir + "/ExtraContent");
7874
	}
7875
 
7876
	return count;
7877
}
7878
int CPackages::findPackageDirectories(CLinkList<CBaseFile> &packages, const Utils::String &dir)
7879
{
7880
	CDirIO Dir(dir);
7881
	int count = 0;
7882
	Utils::CStringList files;
7883
	if (Dir.dirList(files))
7884
	{
7885
		for (auto itr = files.begin(); itr != files.end(); itr++)
7886
		{
7887
			Utils::String d = Dir.file((*itr)->str);
7888
			if (CDirIO(d).isDir())
7889
				count += findPackageDirectories(packages, d);
7890
		}
7891
	}
7892
 
7893
	count += findPackageFiles(packages, dir);
7894
	return count;
7895
}
7896
int CPackages::findPackageFiles(CLinkList<CBaseFile> &packages, const Utils::String &dir)
7897
{
7898
	CDirIO Dir(dir);
7899
	int count = 0;
7900
	for (int type = 0; type < 2; type++)
7901
	{
7902
		Utils::CStringList files;
7903
		if (type == 0)
7904
			Dir.dirList(files, Utils::String::Null(), "*.spk");
7905
		else if(type == 1)
7906
			Dir.dirList(files, Utils::String::Null(), "*.xsp");
7907
		else
7908
			break;
7909
 
7910
		for(auto itr = files.begin(); itr != files.end(); itr++)
7911
		{
7912
			Utils::String f = Dir.file((*itr)->str);
7913
			int error = 0;
7914
			CBaseFile *p = this->OpenPackage(f, &error, 0, SPKREAD_NODATA, READFLAG_NOUNCOMPRESS);
7915
			if (!p)
7916
				continue;
7917
			if (p->IsMod() || this->FindSpkPackage(p->name(), p->author()))
7918
			{
7919
				delete p;
7920
				continue;
7921
			}
7922
 
7923
			// check its for the correct game
7924
			if (!p->CheckGameCompatability(this->GetGame()))
7925
			{
7926
				delete p;
7927
				continue;
7928
			}
7929
 
7930
			// check if its already on the list
7931
			bool found = false;
7932
			for (CBaseFile *checkp = packages.First(); checkp; checkp = packages.Next())
7933
			{
7934
				if (p->name().Compare(checkp->name()) && p->author().Compare(checkp->author()))
7935
				{
7936
					found = true;
7937
					break;
7938
				}
7939
			}
7940
 
7941
			if (found)
7942
			{
7943
				delete p;
7944
				continue;
7945
			}
7946
 
7947
			if (p->GetIcon())
7948
			{
7949
				bool addedIcon = false;
7950
				p->ReadIconFileToMemory();
7951
				p->GetIcon()->SetFilename(this->tempDirectory().findReplace("\\", "/") + "/" + p->author() + "_" + p->name() + "." + p->GetIconExt().ToString());
7952
				p->GetIcon()->SetFullDir(this->tempDirectory());
7953
				if (p->GetIcon()->UncompressData())
7954
				{
7955
					if (p->GetIcon()->writeFilePointer())
7956
						addedIcon = true;
7957
				}
7958
 
7959
				if (!addedIcon)
7960
					p->SetIcon(NULL, "");
7961
			}
7962
 
7963
			// get an advert to display
7964
			if (p->GetFirstFile(FILETYPE_ADVERT))
7965
			{
7966
				bool done = false;
7967
				C_File *f = p->GetFirstFile(FILETYPE_ADVERT);
7968
				if (p->ReadFileToMemory(f))
7969
				{
7970
					f->SetFullDir(this->tempDirectory());
7971
					if (f->UncompressData())
7972
					{
7973
						if (f->writeFilePointer())
7974
							done = true;
7975
					}
7976
				}
7977
 
7978
				if (!done)
7979
					f->DeleteData();
7980
			}
7981
 
7982
			packages.push_back(p);
7983
			++count;
7984
		}
7985
	}
7986
 
7987
	return count;
7988
}
7989
 
121 cycrow 7990
Utils::String CPackages::ConvertLanguage(int lang)
1 cycrow 7991
{
7992
	switch ( lang )
7993
	{
7994
		case 44:
7995
			return "English";
7996
		case 49:
7997
			return "German";
7998
		case 7:
7999
			return "Russian";
8000
		case 33:
8001
			return "French";
8002
		case 30:
8003
			return "Greek";
8004
		case 31:
8005
			return "Dutch";
8006
		case 32:
8007
			return "Belgian";
8008
		case 34:
8009
			return "Spanish";
8010
		case 36:
8011
			return "Hungarian";
8012
		case 39:
8013
			return "Italian";
8014
		case 40:
8015
			return "Romanian";
8016
		case 41:
8017
			return "Swiss";
8018
		case 42:
8019
			return "Czech";
8020
		case 43:
8021
			return "Austrian";
8022
		case 45:
8023
			return "Danish";
8024
		case 46:
8025
			return "Swedish";
8026
		case 47:
8027
			return "Norweigen";
8028
		case 48:
8029
			return "Polish";
8030
	}
8031
 
121 cycrow 8032
	return Utils::String::Number(lang);
1 cycrow 8033
}
8034
 
8035
bool CPackages::CheckAccessRights(CyString dir)
8036
{
8037
	if ( dir.Empty() )
8038
		dir = m_sCurrentDir;
8039
 
8040
	// write a file, then read the contents
8041
	CFileIO File(dir + "/accessrightscheck.dat");
8042
 
8043
	// check if file exists and remove it
52 cycrow 8044
	if ( File.exists() )
1 cycrow 8045
	{
8046
		// if we cant remove it, we dont have enough rights
52 cycrow 8047
		if ( !File.remove() )
1 cycrow 8048
			return false;
8049
 
8050
		// if its still there, we dont have enough rights
52 cycrow 8051
		if ( File.exists() )
1 cycrow 8052
			return false;
8053
	}
8054
 
8055
	// now create the file
82 cycrow 8056
	if ( !File.writeString("testing access rights") )
1 cycrow 8057
		return false;
8058
 
8059
	// now check it exists
52 cycrow 8060
	if ( !File.exists() )
1 cycrow 8061
		return false;
8062
 
8063
	// now read the file for the correct contents
8064
	CyStringList *lines = File.ReadLinesStr();
8065
	if ( !lines )
8066
		return false;
8067
 
8068
	// check that one of the lines is correct
8069
	for ( SStringList *s = lines->Head(); s; s = s->next )
8070
	{
8071
		if ( s->str == "testing access rights" )
8072
		{
8073
			delete lines;
8074
			return true;
8075
		}
8076
	}
8077
 
8078
	delete lines;
8079
 
8080
	return false;
8081
}
8082
 
8083
bool CPackages::LoadShipData(CyString file, CyStringList *list)
8084
{
8085
	CFileIO File;
8086
	bool deleteFile = false;
8087
 
8088
	// load from cat file
8089
	if ( CFileIO(file).CheckFileExtension("cat") )
8090
	{
8091
		CCatFile cat;
125 cycrow 8092
		if ( cat.open(file.ToString(), this->getAddonDir(), CATREAD_CATDECRYPT, false) != CATERR_NONE )
1 cycrow 8093
			return false;
8094
 
8095
		if ( !cat.ExtractFile("types\\TShips.pck", m_sTempDir + "/tships.txt") )
8096
			return false;
8097
 
118 cycrow 8098
		File.open(m_sTempDir + "/tships.txt");
1 cycrow 8099
		deleteFile = true;
8100
	}
8101
	// otherwise its a normal file
8102
	else if ( CFileIO(file).CheckFileExtension("pck") )
8103
	{
127 cycrow 8104
		C_File f(file.ToString());
1 cycrow 8105
		if ( !f.ReadFromFile() )
8106
			return false;
8107
		f.UnPCKFile();
8108
 
8109
		f.SetFilename(m_sTempDir + "/tships.txt");
129 cycrow 8110
		if ( !f.writeFilePointer() )
1 cycrow 8111
			return false;
8112
 
118 cycrow 8113
		File.open(m_sTempDir + "/tships.txt");
1 cycrow 8114
		deleteFile = true;
8115
	}
8116
	else
118 cycrow 8117
		File.open(file.ToString());
1 cycrow 8118
 
52 cycrow 8119
	if ( !File.exists() )
1 cycrow 8120
		return false;
8121
 
8122
	bool ret = false;
8123
	CyStringList *lines = File.ReadLinesStr();
8124
	if ( lines )
8125
	{
8126
		bool readFirst = false;
8127
		for ( SStringList *str = lines->Head(); str; str = str->next )
8128
		{
8129
			if ( str->str.Empty() )
8130
				continue;
8131
			str->str.RemoveChar('\r');
8132
			str->str.RemoveChar(9);
8133
			str->str.RemoveFirstSpace();
8134
			if ( str->str.Empty() )
8135
				continue;
8136
			if ( str->str[0] == '/' || str->str[0] == '#' )
8137
				continue;
8138
 
8139
			if ( !readFirst )
8140
				readFirst = true;
8141
			else
8142
			{
8143
				CyString t = str->str.GetToken(";", -2);
8144
				while ( t.Right(1) == ";" )
8145
					t.Truncate((int)t.Length() - 1);
8146
				list->PushBack(t, str->str);
8147
			}
8148
		}
8149
 
8150
		delete lines;
8151
		ret = true;
8152
	}
8153
 
8154
	if ( deleteFile )
52 cycrow 8155
		File.remove();
1 cycrow 8156
 
8157
	return ret;
8158
}
8159
 
8160
CyString CPackages::ReadShipData(CyString file, CyString id)
8161
{
8162
	CyStringList *list = this->LoadShipData(file);
8163
	if ( !list )
8164
		return NullString;
8165
 
8166
	CShipData data;
8167
	for ( SStringList *str = list->Head(); str; str = str->next )
8168
	{
8169
		if ( str->str.Compare(id) )
8170
		{
8171
			delete list;
8172
			return str->data;
8173
		}
8174
	}
8175
 
8176
	delete list;
8177
	return NullString;
8178
}
8179
 
8180
CyStringList *CPackages::LoadShipData(CyString file)
8181
{
8182
	CyStringList *list = new CyStringList;
8183
	if ( this->LoadShipData(file, list) )
8184
		return list;
8185
 
8186
	delete list;
8187
	return NULL;
8188
}
8189
 
8190
bool CPackages::ReadTextPage(CyString file, CyStringList *list, bool search, int page)
8191
{
8192
	CFileIO File;
8193
	bool deleteFile = false;
8194
 
8195
	// read all text files from mod
8196
	if ( CFileIO(file).CheckFileExtension("cat") )
8197
	{
8198
		bool done = false;
8199
 
8200
		CCatFile cat;
125 cycrow 8201
		if ( cat.open(file.ToString(), this->getAddonDir(), CATREAD_CATDECRYPT, false) != CATERR_NONE )
1 cycrow 8202
			return false;
8203
 
8204
		// extract 1 at a time
124 cycrow 8205
		for (unsigned int i = 0; i < cat.GetNumFiles(); i++ )
1 cycrow 8206
		{
8207
			SInCatFile *f = cat.GetFile(i);
8208
			CyString sF = f->sFile;
8209
			// is a text file
8210
			sF = sF.FindReplace("\\", "/");
8211
			if ( !sF.GetToken("/", 1, 1).Compare("t") )
8212
				continue;
8213
 
57 cycrow 8214
			CyString baseFile = CFileIO(sF.ToString()).baseName();
1 cycrow 8215
			// check language
8216
			int lang = 0;
8217
			if ( baseFile.FindPos("-L") != -1 ) // new language file
8218
				lang = baseFile.Right(3).ToInt();
8219
			else
8220
			{
8221
				baseFile.Truncate((int)baseFile.Length() - 4);
8222
				lang = baseFile.ToInt();
8223
			}
8224
 
8225
			if ( lang != m_iLanguage )
8226
				continue;
8227
 
8228
			// now extract and parse
57 cycrow 8229
			if ( cat.ExtractFile(f->sFile, m_sTempDir + "/" + CFileIO(f->sFile).baseName() + ".xml") )
1 cycrow 8230
			{
57 cycrow 8231
				if ( this->ReadTextPage(m_sTempDir + "/" + CFileIO(f->sFile).baseName() + ".xml", list, search, page) )
1 cycrow 8232
					done = true;
8233
			}
8234
		}
8235
 
8236
		return done;
8237
	}
8238
	// otherwise its a normal file
8239
	else if ( CFileIO(file).CheckFileExtension("pck") )
8240
	{
127 cycrow 8241
		C_File f(file.ToString());
1 cycrow 8242
		if ( !f.ReadFromFile() )
8243
			return false;
8244
		f.UnPCKFile();
8245
 
8246
		f.SetFilename(m_sTempDir + "/textfile.xml");
129 cycrow 8247
		if ( !f.writeFilePointer() )
1 cycrow 8248
			return false;
8249
 
118 cycrow 8250
		File.open(m_sTempDir + "/textfile.xml");
1 cycrow 8251
		deleteFile = true;
8252
	}
8253
	else
118 cycrow 8254
		File.open(file.ToString());
1 cycrow 8255
 
52 cycrow 8256
	if ( !File.exists() )
1 cycrow 8257
		return false;
8258
 
8259
	// open and read file
8260
	CyStringList *lines = File.ReadLinesStr();
8261
	if ( !lines )
8262
		return false;
8263
 
8264
	bool inPage = false;
8265
	for ( SStringList *str = lines->Head(); str; str = str->next )
8266
	{
8267
		// search for page
8268
		if ( !inPage )
8269
		{
8270
			if ( str->str.FindPos("<page") > -1 )
8271
			{
8272
				// find the page id
8273
				int pos = str->str.FindPos("\"");
8274
				if ( pos > -1 )
8275
				{
8276
					int endpos = str->str.FindPos("\"", pos + 1);
8277
					if ( endpos > -1 )
8278
					{
8279
						CyString p = str->str.Mid(pos + 2, endpos - pos - 1);
8280
						if ( p.Length() > 4 )
8281
							p = p.Right(4);
8282
						int checkPage = p.ToInt();
8283
						if ( checkPage == page )
8284
							inPage = true;
8285
					}
8286
				}
8287
			}
8288
 
8289
		}
8290
		// add each id
8291
		else
8292
		{
8293
			if ( str->str.FindPos("</page") > -1 )
8294
				break;
8295
 
8296
			if ( str->str.FindPos("<t id") > -1 )
8297
			{
8298
				int pos = str->str.FindPos("\"");
8299
				if ( pos > -1 )
8300
				{
8301
					int endpos = str->str.FindPos("\"", pos + 1);
8302
					if ( endpos > -1 )
8303
					{
8304
						int id = str->str.Mid(pos + 2, endpos - pos - 1).ToInt();
8305
						pos = str->str.FindPos(">", endpos);
8306
						if ( pos > -1 )
8307
						{
8308
							++pos;
8309
							endpos = str->str.FindPos("</", pos);
8310
							if ( endpos > -1 )
8311
							{
8312
								CyString text = str->str.Mid(pos + 1, endpos - pos);
8313
								while ( text.FindPos('(') != -1 && text.FindPos(')') != -1 )
8314
								{
8315
									int s = text.FindPos('(');
8316
									text = text.Erase(s, text.FindPos(')') - s + 1);
8317
								}
8318
								list->PushBack(CyString::Number(id), text, search);
8319
							}
8320
						}
8321
					}
8322
				}
8323
			}
8324
		}
8325
	}
8326
 
8327
	delete lines;
8328
 
8329
	return true;
8330
}
8331
 
8332
CyStringList *CPackages::ReadTextPage(CyString file, bool search, int page)
8333
{
8334
	CyStringList *list = new CyStringList;
8335
	if ( this->ReadTextPage(file, list, search, page) )
8336
		return list;
8337
 
8338
	delete list;
8339
	return NULL;
8340
}
8341
 
8342
int CPackages::AdjustFileType(CyString file, int filetype)
8343
{
8344
	CFileIO File(file);
121 cycrow 8345
	Utils::String dir = File.GetDirIO().topDir();
57 cycrow 8346
	CyString basename = File.baseName();
1 cycrow 8347
 
8348
	// mod files
8349
	if ( File.CheckFileExtension("cat") || File.CheckFileExtension("dat") )
8350
		return FILETYPE_MOD;
8351
	// check for text files
111 cycrow 8352
	if ( File.filename().isin("-L") && File.filename().left(4).isNumber() )
1 cycrow 8353
		return FILETYPE_TEXT;
57 cycrow 8354
	if ( File.baseName().Compare("conversations") )
43 cycrow 8355
		return FILETYPE_TEXT;
1 cycrow 8356
	if ( basename.Length() <= 4 && basename.IsNumber() && (File.CheckFileExtension("xml") || File.CheckFileExtension("pck")) )
8357
		return FILETYPE_TEXT;
8358
	// X2/X3 text file
57 cycrow 8359
	if ( basename.Length() >= 5 && basename.Length() <= 8 && ((int)File.baseName()) )
1 cycrow 8360
		return FILETYPE_TEXT;
8361
	if ( filetype == FILETYPE_TEXT ) // should no longer be anything text
8362
		return FILETYPE_SCRIPT;
8363
	if ( File.CheckFileExtension("wav") || File.CheckFileExtension("mp3") )
8364
		return FILETYPE_SOUND;
8365
	return filetype;
8366
}
8367
 
8368
void CPackages::RemoveFailedFiles()
8369
{
8370
	for ( SStringList *str = m_lNonRemovedFiles.Head(); str; str = str->next )
8371
	{
52 cycrow 8372
		if ( CFileIO::Remove(str->str.ToString()) )
1 cycrow 8373
			str->remove = true;
8374
	}
8375
 
8376
	m_lNonRemovedFiles.RemoveMarked();
8377
}
8378
 
35 cycrow 8379
CXspFile *CPackages::extractShip(const Utils::String &sCatFile, const Utils::String &sId, CProgressInfo *progress)
1 cycrow 8380
{
35 cycrow 8381
	CVirtualFileSystem *pVfs = new CVirtualFileSystem();
8382
	if ( !pVfs->addMod(sCatFile) ) {
8383
		delete pVfs;
1 cycrow 8384
		return NULL;
35 cycrow 8385
	}
1 cycrow 8386
 
8387
	CXspFile *newShip = new CXspFile;
35 cycrow 8388
	if ( !newShip->extractShip(pVfs, sId, progress) ) {
1 cycrow 8389
		delete newShip;
35 cycrow 8390
		newShip = NULL;
1 cycrow 8391
	}
8392
 
35 cycrow 8393
	delete pVfs;
8394
 
1 cycrow 8395
	return newShip;
8396
}
8397
 
124 cycrow 8398
void CPackages::getMergedFiles(Utils::CStringList &list, CCatFile *cat1, CCatFile *cat2)
1 cycrow 8399
{
8400
	// first add all files from the "primary" mod
124 cycrow 8401
	for (auto itr = cat1->GetFiles()->cbegin(); itr != cat1->GetFiles()->cend(); itr++)
8402
		list.pushBack((*itr)->sFile.findReplace("\\", "/"), "1");
1 cycrow 8403
 
8404
	// now add the ones from the secondary
124 cycrow 8405
	for (auto itr = cat2->GetFiles()->cbegin(); itr != cat2->GetFiles()->cend(); itr++)
1 cycrow 8406
	{
124 cycrow 8407
		Utils::String sFile = (*itr)->sFile.findReplace("\\", "/");
1 cycrow 8408
		// if its found on the 2nd list, dont add, just adjust the type
124 cycrow 8409
		if(!list.changeData(sFile, "-1"))
8410
			list.pushBack(sFile, "2");
1 cycrow 8411
	}
8412
}
8413
 
58 cycrow 8414
bool CPackages::CanWeMerge(const Utils::String &file) const
1 cycrow 8415
{
8416
	return CModDiff::CanBeDiffed(file);
8417
}
8418
 
8419
bool CPackages::NeedToMerge(CyString file)
8420
{
8421
	CyString firstDir = file.GetToken("/", 1, 1);
8422
	if ( firstDir.Compare("t") )
8423
		return true;
8424
	if ( firstDir.Compare("types") )
8425
		return true;
8426
	if ( firstDir.Compare("maps") )
8427
		return true;
8428
 
8429
	return false;
8430
}
8431
 
8432
bool CPackages::MergeMods(CCatFile *mod1, CCatFile *mod2, CyString outFile, CyStringList *cantMerge)
8433
{
8434
	CCatFile newCat;
125 cycrow 8435
	if ( newCat.open(outFile.ToString(), this->getAddonDir()) != CATERR_CREATED )
1 cycrow 8436
		return false;
8437
 
124 cycrow 8438
	Utils::CStringList list;
8439
	this->getMergedFiles(list, mod1, mod2);
8440
	if (list.empty())
8441
		return false;
8442
 
1 cycrow 8443
	// add all the files to the new mod first
124 cycrow 8444
	Utils::CStringList conflicts;
8445
	for(auto itr = list.begin(); itr != list.end(); itr++)
8446
	{		
8447
		int status = (*itr)->data.toInt();
1 cycrow 8448
		if ( status == 1 )
8449
		{
124 cycrow 8450
			if ( !newCat.WriteFromCat(mod1, (*itr)->str) )
1 cycrow 8451
			{
8452
				if ( cantMerge )
124 cycrow 8453
					cantMerge->PushBack(CyString((*itr)->str), "1");
1 cycrow 8454
			}
8455
		}
8456
		else if ( status == 2 )
8457
		{
124 cycrow 8458
			if ( !newCat.WriteFromCat(mod2, (*itr)->str) )
1 cycrow 8459
			{
8460
				if ( cantMerge )
124 cycrow 8461
					cantMerge->PushBack(CyString((*itr)->str), "2");
1 cycrow 8462
			}
8463
		}
8464
		else if ( status == -1 )
8465
		{
124 cycrow 8466
			if ( this->NeedToMerge((*itr)->str) )
1 cycrow 8467
			{
124 cycrow 8468
				if ( this->CanWeMerge((*itr)->str) )
8469
					conflicts.pushBack((*itr)->str);
1 cycrow 8470
				else if ( cantMerge )
124 cycrow 8471
					cantMerge->PushBack(CyString((*itr)->str), "-1");
1 cycrow 8472
			}
8473
			else
8474
			{
124 cycrow 8475
				if ( !newCat.WriteFromCat(mod1, (*itr)->str) )
1 cycrow 8476
				{
8477
					if ( cantMerge )
124 cycrow 8478
						cantMerge->PushBack(CyString((*itr)->str), "1");
1 cycrow 8479
				}
8480
			}
8481
		}
8482
	}
8483
 
8484
	/* 
8485
		Merging Files
8486
 
8487
		* Text Files: Join all text entries into a single file (excluding page 17)
8488
		* Weapons: TBullets and TLaser (grab matching entrys from text files and adjust ids)
8489
	*/
8490
	// new merge the conflicting files
8491
	// first the text files
8492
//	CyStringList *text = this->MergeTextFiles(conflicts, mod1, mod2);
8493
//	delete text;
8494
 
8495
	// write the cat file when we're done
8496
	if ( !newCat.WriteCatFile() )
8497
		return false;
8498
 
8499
	return true;
8500
}
8501
 
8502
/**
8503
 * Gets the file list from a mod that might have compatability problems
8504
 *
8505
 * This includes all types and text files
8506
 *
8507
 * Returns true if it finds any files
8508
 */
8509
bool CPackages::GetModCompatabilityList(C_File *file, CyStringList *list)
8510
{
8511
	// not a valid file
8512
	if ( !file ) return false;
8513
	if ( file->GetFileType() != FILETYPE_MOD ) return false;
8514
	if ( !file->GetFileExt().Compare("cat") ) return false;
8515
 
8516
	// we need to read the file list for the mod
8517
	CCatFile cat;
125 cycrow 8518
	if ( cat.open(file->filePointer(), this->getAddonDir(), CATREAD_JUSTCONTENTS, false) == CATERR_NONE )
1 cycrow 8519
	{
124 cycrow 8520
		for (unsigned int i = 0; i < cat.GetNumFiles(); i++ )
1 cycrow 8521
		{
8522
			SInCatFile *f = cat.GetFile(i);
8523
			CyString filename = f->sFile;
8524
			filename = filename.FindReplace("\\", "/");
50 cycrow 8525
			bool found = false;
1 cycrow 8526
			if ( filename.Left(2).Compare("t/") || filename.Left(6).Compare("types/") )
50 cycrow 8527
				found = true;
8528
			else if ( filename.Left(8).Compare("addon/t/") || filename.Left(12).Compare("addon/types/") )
8529
				found = true;
8530
 
8531
			if ( found ) {
1 cycrow 8532
				if ( list )
8533
					list->PushBack(filename, CyString(f->lSize));
8534
				else
8535
					return true;
8536
			}
8537
		}
8538
	}
8539
 
8540
	if ( list && !list->Empty() )
8541
		return true;
8542
 
8543
	return false;
8544
}
8545
 
8546
/**
8547
 * Gets the files that are not compatable with each other
8548
 *
8549
 * Returns true if theres any files that are not compatable
8550
 *
8551
 * If list is specified, fills up with all files that were found
8552
 */
8553
bool CPackages::CheckCompatabilityBetweenModFiles(C_File *from, C_File *to, CyStringList *list)
8554
{
8555
	// not a valid file
8556
	if ( !from || !to ) return false;
8557
	if ( from->GetFileType() != FILETYPE_MOD ) return false;
8558
	if ( to->GetFileType() != FILETYPE_MOD ) return false;
8559
	if ( !from->GetFileExt().Compare("cat") ) return false;
8560
	if ( !to->GetFileExt().Compare("cat") ) return false;
8561
 
8562
	// get file lists from each file
8563
	CyStringList fromList;
8564
	if ( GetModCompatabilityList(from, &fromList) )
8565
	{
8566
		CyStringList toList;
8567
		if ( GetModCompatabilityList(to, &toList) )
8568
		{
8569
			// both have files we need to check, compare them
8570
			for ( SStringList *str = fromList.Head(); str; str = str->next )
8571
			{
8572
				CyString fromFile = str->str;
8573
				fromFile = fromFile.FindReplace("\\", "/");
8574
				fromFile = fromFile.FindReplace("//", "/");
8575
				for ( SStringList *toStr = toList.Head(); toStr; toStr = toStr->next )
8576
				{
8577
					CyString toFile = toStr->str;
8578
					toFile = toFile.FindReplace("\\", "/");
8579
					toFile = toFile.FindReplace("//", "/");
8580
					if ( fromFile.Compare(toFile) )
8581
					{
8582
						if ( list )
8583
							list->PushBack(from->GetFilename() + "::" + str->str, to->GetFilename() + "::" + toStr->str);
8584
						else
8585
							return true;
8586
					}
8587
				}
8588
			}
8589
		}
8590
	}
8591
 
8592
	if ( list && !list->Empty() )
8593
		return true;
8594
 
8595
	return false;
8596
}
8597
 
8598
bool CPackages::CheckCompatabilityBetweenMods(CBaseFile *from, CBaseFile *to, CyStringList *list)
8599
{
8600
	if ( !from || !to ) return false;
8601
	if ( !from->IsEnabled() || !to->IsEnabled() ) return false;
8602
	if ( !from->AnyFileType(FILETYPE_MOD) ) return false;
8603
	if ( !to->AnyFileType(FILETYPE_MOD) ) return false;
8604
 
8605
	if ( from == to ) return false; // cant have incompatabilities to itself
8606
 
8607
	int count = 0;
8608
	for ( C_File *f = from->GetFirstFile(FILETYPE_MOD); f; f = from->GetNextFile(f) )
8609
	{
8610
		if ( !f->IsFakePatch() ) continue;
8611
		if ( f->GetFileExt().Compare("dat") ) continue;
8612
 
8613
		for ( C_File *compareFile = to->GetFirstFile(FILETYPE_MOD); compareFile; compareFile = to->GetNextFile(compareFile) )
8614
		{
8615
			if ( compareFile == f ) continue; // same file we're checking against
8616
			if ( !compareFile->IsFakePatch() ) continue;
8617
			if ( compareFile->GetFileExt().Compare("dat") ) continue;
8618
 
8619
			// now we have to files to compare
8620
			if ( CheckCompatabilityBetweenModFiles(f, compareFile, list) )
8621
				++count;
8622
		}
8623
	}
8624
 
8625
	if ( count )
8626
		return true;
8627
 
8628
	return false;
8629
}
8630
 
8631
int CPackages::CheckCompatabilityAgainstPackages(CBaseFile *newFile, CyStringList *list, CLinkList<CBaseFile> *packages)
8632
{
8633
	if ( !newFile->IsEnabled() ) return 0;
8634
	if ( !newFile->AnyFileType(FILETYPE_MOD) ) return 0;
8635
 
8636
	// we need to extract all mod files
8637
	for ( CListNode<C_File> *fNode = newFile->GetFileList()->Front(); fNode; fNode = fNode->next() )
8638
	{
8639
		C_File *f = fNode->Data();
8640
		if ( f->GetFileType() != FILETYPE_MOD ) continue;
8641
		if ( !f->IsFakePatch() ) continue;
8642
		if ( !f->CheckFileExt("cat") ) continue;
8643
 
8644
		if ( newFile->ExtractFile(f, m_sTempDir) )
8645
			f->SetFullDir(m_sTempDir);
8646
	}
8647
 
8648
	// compare mod files against all installed packages
8649
	int count = 0;
8650
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
8651
	{
8652
		if ( !node->Data() ) continue;
8653
		CBaseFile *p = node->Data();
8654
		if ( !p->IsEnabled() ) continue;
8655
		if ( !p->AnyFileType(FILETYPE_MOD) ) continue;
8656
 
8657
		if ( this->IsSamePackage(p, newFile) ) continue; // dont include self
8658
 
8659
		if ( CheckCompatabilityBetweenMods(newFile, p, list) )
8660
		{
8661
			++count;
8662
			if ( packages && !packages->FindData(p) )
8663
				packages->push_back(p);
8664
		}
8665
	}
8666
 
8667
	for ( CListNode<C_File> *fNode = newFile->GetFileList()->Front(); fNode; fNode = fNode->next() )
8668
	{
8669
		C_File *f = fNode->Data();
129 cycrow 8670
		CFileIO::Remove(f->filePointer());
1 cycrow 8671
		f->SetFullDir("");
8672
	}
8673
 
8674
	return count;
8675
}
8676
 
8677
bool CPackages::IsSamePackage(CBaseFile *p1, CBaseFile *p2)
8678
{
8679
	if ( !p1 || !p2 ) return false;
8680
	if ( p1 == p2 ) return true;
8681
 
50 cycrow 8682
	if ( p1->name().Compare(p2->name()) && p1->author().Compare(p2->author()) )
1 cycrow 8683
		return true;
8684
	return false;
8685
}
8686
 
8687
void CPackages::ApplyFakePatchOrder(CyStringList *list)
8688
{
8689
	if ( !list ) return;
8690
	m_lFakePatchOrder.Clear();
8691
	for ( SStringList *str = list->Head(); str; str = str->next )
8692
		m_lFakePatchOrder.PushBack(str->str, str->data);
8693
}
8694
 
8695
SAvailablePackage *CPackages::CreateAvailablePackageData(CBaseFile *package)
8696
{
8697
	if ( !package ) return NULL;
8698
 
8699
	SAvailablePackage *p = new SAvailablePackage;
8700
 
8701
	for ( CListNode<SGameCompat> *node = package->GetGameCompatabilityList()->Front(); node; node = node->next() ) {
8702
		SGameCompat *gc = new SGameCompat;
8703
		gc->iGame = node->Data()->iGame;
8704
		gc->iVersion = node->Data()->iVersion;
8705
		gc->sVersion = node->Data()->sVersion;
8706
		p->lGames.push_back(gc);
8707
	}
8708
	p->bSigned = package->IsSigned();
46 cycrow 8709
	p->iChanging = package->gameChanging();
8710
	p->iEase = package->easeOfUse();
48 cycrow 8711
	p->iPluginType = package->pluginType();
46 cycrow 8712
	p->iRec = package->recommended();
1 cycrow 8713
	p->iScriptType = -1;
8714
	if ( package->GetType() == TYPE_XSP )
8715
		p->iType = PACKAGETYPE_SHIP;
8716
	else if ( package->IsMod() )
8717
		p->iType = PACKAGETYPE_MOD;
8718
	else 
8719
	{
8720
		p->iType = ((CSpkFile *)package)->GetPackageType();
8721
		p->iScriptType = ((CSpkFile *)package)->GetScriptType();
8722
	}
50 cycrow 8723
	p->sAuthor = package->author();
48 cycrow 8724
	p->sDesc = package->description().findReplace("\n", "::newline::");
50 cycrow 8725
	p->sName = package->name();
8726
	p->sUpdated = package->creationDate();
8727
	p->sVersion = package->version();
111 cycrow 8728
	p->sFilename = CFileIO(package->filename()).filename();
1 cycrow 8729
 
8730
	return p;
8731
}
8732
 
126 cycrow 8733
Utils::String CPackages::FormatAvailablePackageData(CBaseFile *package)
1 cycrow 8734
{
8735
	SAvailablePackage *p = CPackages::CreateAvailablePackageData(package);
126 cycrow 8736
	Utils::String ret = CPackages::FormatAvailablePackageData(p);
1 cycrow 8737
	delete p;
8738
	return ret;
8739
}
8740
 
126 cycrow 8741
Utils::String CPackages::FormatAvailablePackageData(SAvailablePackage *package)
1 cycrow 8742
{
126 cycrow 8743
	Utils::String ret = (long)package->iType;
1 cycrow 8744
 
126 cycrow 8745
	Utils::String gameCompat;
1 cycrow 8746
	for ( CListNode<SGameCompat> *node = package->lGames.Front(); node; node = node->next() ) {
126 cycrow 8747
		if ( !gameCompat.empty() )
1 cycrow 8748
			gameCompat += "!";
126 cycrow 8749
		gameCompat += Utils::String::Number(node->Data()->iGame);
1 cycrow 8750
	}
8751
 
126 cycrow 8752
	if ( gameCompat.empty() )
1 cycrow 8753
		gameCompat = "0";
8754
 
126 cycrow 8755
	ret = ret.addToken("::", gameCompat);
8756
	ret = ret.addToken("::", package->sName);
8757
	ret = ret.addToken("::", package->sAuthor);
8758
	ret = ret.addToken("::", package->sVersion);
8759
	ret = ret.addToken("::", package->sUpdated);
8760
	ret = ret.addToken("::", package->sFilename);
8761
	ret = ret.addToken("::", Utils::String::Number(package->iEase));
8762
	ret = ret.addToken("::", Utils::String::Number(package->iChanging));
8763
	ret = ret.addToken("::", Utils::String::Number(package->iRec));
8764
	ret = ret.addToken("::", Utils::String::Number(package->iPluginType));
8765
	ret = ret.addToken("::", Utils::String::Number(package->iScriptType));
8766
	ret = ret.addToken("::", (package->bSigned) ? "1" : "0");
8767
	ret = ret.addToken("::", package->sDesc);
1 cycrow 8768
 
8769
	return ret;
8770
}
8771
 
100 cycrow 8772
void CPackages::ParseAvailablePackage(CyString sStr, CyString webaddress)
1 cycrow 8773
{
8774
	// first check game
100 cycrow 8775
	Utils::String str = sStr.ToString();
1 cycrow 8776
 
8777
	int num = 0;
100 cycrow 8778
	Utils::String *tok = str.tokenise("::", &num);
1 cycrow 8779
	if ( !num || !tok ) return;
100 cycrow 8780
	// invalid number of entries?
1 cycrow 8781
	if ( num < 7 ) { CLEANSPLIT(tok, num); return; }
8782
 
8783
	SAvailablePackage *p = new SAvailablePackage;
100 cycrow 8784
	p->iType = tok[0].toLong();
1 cycrow 8785
	p->bSigned = false;
8786
 
100 cycrow 8787
	// theres multiple games, so we need to split it
8788
	if ( m_iGame ) {
8789
		Utils::String sGame = tok[1];
8790
		if ( sGame.isin("!") ) {
8791
			for(int i = 1; i <= sGame.countToken("!"); i++) {
1 cycrow 8792
				SGameCompat *gc = new SGameCompat;
8793
				gc->iVersion = 0;
100 cycrow 8794
				gc->iGame = sGame.token("!", i).toLong();
1 cycrow 8795
				p->lGames.push_back(gc);
8796
			}
8797
		}
100 cycrow 8798
		else {
8799
			SGameCompat *gc = new SGameCompat;
8800
			gc->iVersion = 0;
8801
			gc->iGame = sGame.toLong();
8802
			p->lGames.push_back(gc);
8803
		}
1 cycrow 8804
	}
100 cycrow 8805
 
1 cycrow 8806
	p->sName = tok[2];
8807
	p->sAuthor = tok[3];
8808
	p->sVersion = tok[4];
8809
	p->sUpdated = tok[5];
8810
	p->sFilename = tok[6];
8811
 
8812
	if ( !webaddress.Empty() )
126 cycrow 8813
		p->sFilename = webaddress.ToString() + "/" + p->sFilename;
1 cycrow 8814
 
8815
	p->iChanging = p->iEase = p->iPluginType = p->iRec = p->iScriptType = -1;
8816
 
100 cycrow 8817
	// check if we have the extra values
1 cycrow 8818
	if ( num >= 12 )
8819
	{
100 cycrow 8820
		p->iEase = tok[7].toLong();
8821
		p->iChanging = tok[8].toLong();
8822
		p->iRec = tok[9].toLong();
8823
		p->iPluginType = tok[10].toLong();
8824
		p->iScriptType = tok[11].toLong();
1 cycrow 8825
		if ( num > 12 ) {
8826
			if ( num > 13 ) {
100 cycrow 8827
				p->sDesc = tok[13];
8828
				p->bSigned = tok[12].toBool();
1 cycrow 8829
			}
8830
			else
100 cycrow 8831
				p->sDesc = tok[12];
1 cycrow 8832
		}
8833
	}
8834
	else if ( num > 7 )
100 cycrow 8835
		p->sDesc = tok[8];
1 cycrow 8836
 
126 cycrow 8837
	if ( !p->sDesc.empty() )
8838
		p->sDesc = p->sDesc.findReplace("::newline::", "\\n");
1 cycrow 8839
 
8840
	AddAvailablePackage(p);
8841
 
8842
	CLEANSPLIT(tok, num);
8843
}
8844
 
126 cycrow 8845
SAvailablePackage *CPackages::FindAvailablePackage(const Utils::String &filename)
1 cycrow 8846
{
8847
	for ( CListNode<SAvailablePackage> *node = m_lAvailablePackages.Front(); node; node = node->next() )
8848
	{
8849
		if ( node->Data()->sFilename.Compare(filename) )
8850
			return node->Data();
8851
	}
8852
	return NULL;
8853
}
8854
 
8855
bool CPackages::AddAvailablePackage(SAvailablePackage *package)	
8856
{ 
8857
	if ( !package->lGames.empty() ) {
8858
		bool found = false;
8859
		for ( CListNode<SGameCompat> *node = package->lGames.Front(); node; node = node->next() ) {
8860
			if ( !node->Data()->iGame || node->Data()->iGame == m_iGame ) {
8861
				found = true;
8862
				break;
8863
			}
8864
		}
8865
 
8866
		if ( !found )
8867
			return false;
8868
	}
8869
 
8870
	SAvailablePackage *p = FindAvailablePackage(package->sFilename);
8871
	if ( p )
8872
		m_lAvailablePackages.remove(p);
8873
	m_lAvailablePackages.push_back(package); 
8874
 
8875
	return true;
8876
}
8877
 
8878
bool CPackages::AnyAvailablePackages(int type)
8879
{
8880
	if ( type == -1 ) return !m_lAvailablePackages.empty();
8881
 
8882
	for ( CListNode<SAvailablePackage> *node = m_lAvailablePackages.Front(); node; node = node->next() )
8883
	{
8884
		if ( node->Data()->iType == type )
8885
			return true;
8886
	}
8887
 
8888
	return false;
8889
}
8890
 
8891
int CPackages::FindAllServers(CyStringList *list)
8892
{
8893
	for ( CListNode<CBaseFile> *node = m_lPackages.Front(); node; node = node->next() )
8894
	{
49 cycrow 8895
		if ( !node->Data()->webAddress().empty() )
8896
			list->PushBack(CyString(node->Data()->webAddress()), true);
1 cycrow 8897
		if ( node->Data()->AnyWebMirrors() )
8898
		{
8899
			for ( SStringList *str = node->Data()->GetWebMirrors()->Head(); str; str = str->next )
8900
				list->PushBack(str->str, true);
8901
		}
8902
	}
8903
 
76 cycrow 8904
	CFileIO File("data\\web");
8905
 
8906
	if ( File.startRead() ) {
8907
		while(!File.atEnd()) {
8908
			Utils::String line = File.readEndOfLine();
8909
			line.removeChar("\n\r\t ");
8910
			if ( !line.empty() )
8911
				list->PushBack(CyString(line), true);
8912
		}
8913
		File.close();
8914
	}
8915
 
8916
	list->PushBack("http://xpluginmanager.co.uk/tcscripts", true);
8917
	list->PushBack("http://xpluginmanager.co.uk/apscripts", true);
8918
 
1 cycrow 8919
	return list->Count();
8920
}
8921
 
8922
void CPackages::ReadArchiveData(CyString filename, CBaseFile *archive)
8923
{
8924
	size_t size;
8925
	char *data = CFileIO(filename).ReadToData(&size);
8926
	if ( size && data )
8927
		ReadArchiveData(data, size, archive);
8928
}
8929
 
8930
void CPackages::ReadArchiveData(const char *buf, size_t len, CBaseFile *archive)
8931
{
98 cycrow 8932
	Utils::CStringList otherGames;
127 cycrow 8933
	Utils::CStringList gameAddons;
8934
	for (unsigned int i = 0; i < m_gameExe.gameCount(); ++i)
8935
	{
8936
		SGameExe *exe = m_gameExe.GetGame(i);
8937
		if (!exe->sAddon.empty())
8938
			gameAddons.pushBack(Utils::String::Number(i + 1), exe->sAddon);
8939
	}
98 cycrow 8940
 
1 cycrow 8941
	CyString data(buf);
8942
	int max;
8943
	CyString *str = data.SplitToken("\n", &max);
8944
	if ( str && max )
8945
	{
8946
		for ( int i = 0; i < max; i++ )
8947
		{
8948
			CyString line = str[i];
8949
			if ( line.Empty() )
8950
				continue;
8951
 
8952
			// filter out any spaces, tabs in front
8953
			line.RemoveChar('\t');
8954
			line.RemoveChar('\r');
8955
			CyString linenospace = line;
8956
			linenospace.RemoveFirstSpace();
8957
			if ( linenospace.Empty() )
8958
				continue;
8959
 
8960
			// check for any comments
8961
			if ( linenospace.Left(2) == "//" )
8962
				continue;
8963
			if ( linenospace[0] == '#' )
8964
				continue;
8965
 
8966
			// all commands start with a keyword followed by a colon, if one doesn't exist, it cant be a valid line
8967
			if ( !line.IsIn(':') )
8968
				continue;
8969
 
8970
			CyString first = line.GetToken(":", 1, 1);
8971
			CyString rest = line.GetToken(":", 2).RemoveFirstSpace();
8972
 
8973
			CyString checkType = first;
8974
			bool shared = false;
8975
			if ( checkType.Left(6).Compare("Shared") )
8976
			{
8977
				checkType = first.Right(-6);
8978
				shared = true;
8979
			}
8980
 
8981
			// now check type name
8982
			int filetype = GetFileTypeFromString(checkType);
8983
			if ( filetype == -1 )
127 cycrow 8984
				archive->LoadPackageData(first.ToString(), rest.ToString(), Utils::String::Null(), otherGames, gameAddons);
1 cycrow 8985
		}
8986
	}
8987
 
8988
	CLEANSPLIT(str, max)
8989
}
8990
 
43 cycrow 8991
CBaseFile *CPackages::_archive_fromRar(CyString filename, bool toInstall )
1 cycrow 8992
{
8993
	// make sure we can open the zip file
8994
	CBaseFile *archive = NULL;
8995
#ifdef _RAR
43 cycrow 8996
	HANDLE hArcData;
8997
	int RHCode,PFCode;
8998
	char CmtBuf[16384];
8999
	struct RARHeaderDataEx HeaderData;
9000
	struct RAROpenArchiveDataEx OpenArchiveData;
1 cycrow 9001
 
43 cycrow 9002
	// find the pluginmanager text to covnert to spkfile
9003
	if ( toInstall ) {
1 cycrow 9004
		memset(&OpenArchiveData,0,sizeof(OpenArchiveData));
9005
		OpenArchiveData.ArcName=(char *)filename.c_str();
9006
		OpenArchiveData.CmtBuf=CmtBuf;
9007
		OpenArchiveData.CmtBufSize=sizeof(CmtBuf);
43 cycrow 9008
		OpenArchiveData.OpenMode=RAR_OM_LIST;
1 cycrow 9009
		hArcData=RAROpenArchiveEx(&OpenArchiveData);
9010
 
43 cycrow 9011
		if (OpenArchiveData.OpenResult!=0) return NULL;
1 cycrow 9012
 
9013
		HeaderData.CmtBuf=NULL;
9014
		memset(&OpenArchiveData.Reserved,0,sizeof(OpenArchiveData.Reserved));
9015
 
43 cycrow 9016
		while ((RHCode=RARReadHeaderEx(hArcData,&HeaderData))==0) {
9017
			if ( CyString(HeaderData.FileName).Compare("pluginmanager.txt") ) {
9018
				toInstall = false;
1 cycrow 9019
				break;
9020
			}
43 cycrow 9021
		}
9022
		RARCloseArchive(hArcData);
9023
	}
1 cycrow 9024
 
43 cycrow 9025
	if ( toInstall )
9026
		archive = new CArchiveFile(); // just installing an archive file
9027
	else
9028
		archive = new CSpkFile(); // converting to a spk file
9029
 
9030
	memset(&OpenArchiveData,0,sizeof(OpenArchiveData));
9031
	OpenArchiveData.ArcName=(char *)filename.c_str();
9032
	OpenArchiveData.CmtBuf=CmtBuf;
9033
	OpenArchiveData.CmtBufSize=sizeof(CmtBuf);
9034
	OpenArchiveData.OpenMode=RAR_OM_EXTRACT;
9035
	OpenArchiveData.UserData=EXTRACT;
9036
	hArcData=RAROpenArchiveEx(&OpenArchiveData);
9037
 
9038
	if (OpenArchiveData.OpenResult!=0) return NULL;
9039
 
9040
	HeaderData.CmtBuf=NULL;
9041
	memset(&OpenArchiveData.Reserved,0,sizeof(OpenArchiveData.Reserved));
9042
 
9043
	bool error = false;
9044
	CyString extractedFile = CDirIO(m_sTempDir).File("extracted.tst").findreplace("/", "\\").findreplace("\\\\", "\\");
9045
	while ((RHCode=RARReadHeaderEx(hArcData,&HeaderData))==0)
9046
	{
9047
		CyString fileName = HeaderData.FileName;
9048
 
9049
		if ( HeaderData.FileAttr == 16 )
9050
			continue;
9051
		wchar_t wText[200];
9052
		::MultiByteToWideChar(CP_ACP, NULL, (char *)extractedFile.c_str(), -1, wText, extractedFile.Length() + 1);
9053
		PFCode=RARProcessFileW(hArcData, RAR_EXTRACT, NULL, NULL);
9054
		if (PFCode!=0)
9055
		{
9056
			error = true;
9057
			break;
9058
		}
9059
 
9060
		CFileIO File(fileName);
52 cycrow 9061
		if ( File.exists() )
43 cycrow 9062
		{
9063
			if ( fileName.Compare("pluginmanager.txt") )
102 cycrow 9064
				this->ReadArchiveData(File.fullFilename(), archive);
43 cycrow 9065
			else
1 cycrow 9066
			{
43 cycrow 9067
				CyString extradir;
9068
				int type = SPK::GetAutomaticFiletype(fileName, &extradir, true);
9069
				// check for special file types
9070
				C_File *f = NULL;
1 cycrow 9071
 
43 cycrow 9072
				if ( type == FILETYPE_SCRIPT_UNINSTALL ) {
111 cycrow 9073
					f = archive->AddFile(CFileIO(fileName).filename(), "", FILETYPE_SCRIPT);
43 cycrow 9074
					if ( f ) {
102 cycrow 9075
						f->ReadFromFile(File.fullFilename());
17 cycrow 9076
					}
43 cycrow 9077
					type = FILETYPE_UNINSTALL;
1 cycrow 9078
				}
9079
 
43 cycrow 9080
				if ( type == -1 )
102 cycrow 9081
					f = archive->AddFile(CFileIO(fileName).filename(), CFileIO(fileName).dir(), FILETYPE_EXTRA);
43 cycrow 9082
				else
102 cycrow 9083
					f = archive->AddFile(CFileIO(fileName).filename(), extradir, type);
9084
				f->ReadFromFile(File.fullFilename());
1 cycrow 9085
			}
43 cycrow 9086
 
52 cycrow 9087
			File.remove();
1 cycrow 9088
		}
43 cycrow 9089
	}
1 cycrow 9090
 
43 cycrow 9091
	RARCloseArchive(hArcData);
1 cycrow 9092
 
43 cycrow 9093
	if ( error )
9094
	{
9095
		delete archive;
9096
		archive = NULL;
9097
	}
1 cycrow 9098
#endif
9099
 
43 cycrow 9100
	return archive;
9101
}
1 cycrow 9102
 
43 cycrow 9103
CBaseFile *CPackages::_archive_fromZip(CyString filename, bool toInstall)
9104
{
9105
	CBaseFile *archive = NULL;
1 cycrow 9106
 
43 cycrow 9107
	TCHAR buf[5000];
9108
	wsprintf(buf, L"%hs", filename.c_str());
9109
	HZIP hz = OpenZip(buf, 0);
9110
	if ( !hz ) 
9111
		return NULL;
1 cycrow 9112
 
43 cycrow 9113
	int index;
9114
	// move the files from the zip to the package
9115
	ZIPENTRY ze;
9116
	if ( FindZipItem(hz, L"pluginmanager.txt", true, &index, &ze) == Z_OK )
9117
		toInstall = false;
9118
	CloseZip(hz);
1 cycrow 9119
 
43 cycrow 9120
	hz = OpenZip(buf, 0);
9121
	if ( !hz ) 
9122
		return NULL;
9123
 
9124
	// create the correct package
9125
	if ( toInstall )
9126
		archive = new CArchiveFile(); // just installing an archive file
9127
	else
9128
		archive = new CSpkFile(); // converting to a spk file
9129
 
9130
	GetZipItem(hz, -1, &ze);
9131
	int numitems = ze.index;
9132
 
9133
	bool error = false;
9134
	for ( int zi = 0; zi < numitems; zi++ )
9135
	{
9136
		ZIPENTRY ze;
9137
		if ( GetZipItem(hz, zi, &ze) != Z_OK )
1 cycrow 9138
		{
43 cycrow 9139
			error = true;
9140
			break;
9141
		}
1 cycrow 9142
 
43 cycrow 9143
		if ( ze.attr & FILE_ATTRIBUTE_DIRECTORY )
9144
			continue; // dont do directories
1 cycrow 9145
 
9146
 
43 cycrow 9147
		char *iBuf = new char[ze.unc_size];
9148
		UnzipItem(hz, zi, iBuf, ze.unc_size);
1 cycrow 9149
 
43 cycrow 9150
		CyString Name(ze.name);
1 cycrow 9151
 
43 cycrow 9152
		// if its the data file, dont add it, but extract to get settings from
9153
		if ( Name.Compare("pluginmanager.txt") )
9154
		{
9155
			this->ReadArchiveData(iBuf, ze.unc_size, archive);
9156
			delete[] iBuf;
9157
		}
9158
		else
9159
		{
9160
			CyString extradir;
9161
			int type = SPK::GetAutomaticFiletype(Name, &extradir, true);
1 cycrow 9162
 
43 cycrow 9163
			C_File *f = NULL;
17 cycrow 9164
 
126 cycrow 9165
			Utils::String filename = CFileIO(Name).filename();
9166
			Utils::String dir = CFileIO(Name).dir();
9167
 
43 cycrow 9168
			// check for special file types
9169
			if ( type == FILETYPE_SCRIPT_UNINSTALL ) {
126 cycrow 9170
				f = archive->AddFile(filename, dir, FILETYPE_SCRIPT);
43 cycrow 9171
				if ( f ) {
9172
					f->copyData((const unsigned char *)iBuf, ze.unc_size);
17 cycrow 9173
				}
43 cycrow 9174
				type = FILETYPE_UNINSTALL;
9175
			}
17 cycrow 9176
 
126 cycrow 9177
			int game = 0;
9178
			// check for addons
9179
			if (dir.contains('/', true)) 
9180
			{
9181
				Utils::String first = dir.token("/", 1);
9182
				int g = m_gameExe.findAddonType(first);
9183
				if (g != -1)
9184
					game = g + 1;
9185
			}
9186
 
43 cycrow 9187
			if ( type == -1 )
126 cycrow 9188
				f = archive->AddFile(filename, dir, FILETYPE_EXTRA, game);
43 cycrow 9189
			else
126 cycrow 9190
				f = archive->AddFile(filename, extradir, type, game);
1 cycrow 9191
 
43 cycrow 9192
			if ( f )
9193
				f->SetData((const unsigned char *)iBuf, ze.unc_size);
9194
			else
9195
				delete[] iBuf;
1 cycrow 9196
		}
43 cycrow 9197
	}
1 cycrow 9198
 
43 cycrow 9199
	CloseZip(hz);
1 cycrow 9200
 
43 cycrow 9201
	if ( error )
9202
	{
9203
		delete archive;
9204
		archive = NULL;
1 cycrow 9205
	}
43 cycrow 9206
	return archive;
9207
}
1 cycrow 9208
 
43 cycrow 9209
CBaseFile *CPackages::CreateFromArchive(CyString filename, bool toInstall )
9210
{
9211
	// make sure we can open the zip file
9212
	CBaseFile *archive = NULL;
9213
	if ( CFileIO(filename).CheckFileExtension("rar") )
9214
		archive = this->_archive_fromRar(filename, toInstall);
9215
	else if ( CFileIO(filename).CheckFileExtension("zip") )
9216
		archive = this->_archive_fromZip(filename, toInstall);
9217
 
9218
	if ( archive ) {
50 cycrow 9219
		archive->setFilename(CFileIO(filename).ChangeFileExtension("spk").ToString());
1 cycrow 9220
		if ( toInstall )
57 cycrow 9221
			archive->setName(CFileIO(filename).filename());
1 cycrow 9222
		else
57 cycrow 9223
			archive->setName(CFileIO(filename).baseName());
1 cycrow 9224
	}
9225
 
9226
	return archive;
9227
}
9228
 
131 cycrow 9229
Utils::String CPackages::CreateFromPackagerScript(CPackages *packages, const Utils::String &filename)
1 cycrow 9230
{
131 cycrow 9231
	Utils::String curDir = CFileIO(filename).dir();
9232
	Utils::CStringList variables;
9233
	variables.pushBack("$PATH", curDir);
9234
	CBaseFile *package = packages->LoadPackagerScript(filename, NULL, NULL, NULL, &variables);
1 cycrow 9235
 
9236
	if ( !package )
131 cycrow 9237
		return Utils::String::Null();
1 cycrow 9238
 
131 cycrow 9239
	Utils::String saveto = package->filename();
9240
	saveto = saveto.findReplace("$DEFAULTDIR", curDir + "/");
9241
	saveto = saveto.findReplace("$PATH", curDir);
9242
	saveto = saveto.findReplace("\\", "/");
9243
	saveto = saveto.findReplace("//", "/");
9244
	if ( !saveto.right(4).Compare(".spk") && package->GetType() != TYPE_XSP )
1 cycrow 9245
		saveto += ".spk";
131 cycrow 9246
	else if ( !saveto.right(4).Compare(".xsp") && package->GetType() == TYPE_XSP )
1 cycrow 9247
		saveto += ".xsp";
9248
 
9249
	// write script
9250
	if ( package->WriteFile(saveto) )
9251
	{
9252
		if ( package->AutoGenerateUpdateFile() )
102 cycrow 9253
			package->CreateUpdateFile(CFileIO(saveto).dir());
1 cycrow 9254
		return saveto;
9255
	}
9256
 
131 cycrow 9257
	return Utils::String::Null();
1 cycrow 9258
}
9259
 
9260
int CPackages::GeneratePackageUpdateData(CyString dir, bool includeSingle)
9261
{
126 cycrow 9262
	Utils::CStringList filedata;
1 cycrow 9263
 
9264
	CPackages packages;
9265
 
9266
	CDirIO Dir(dir);
9267
	for ( int i = 0; i < 2; i++ )
9268
	{
126 cycrow 9269
		Utils::String pattern;
1 cycrow 9270
		if ( i == 0 ) pattern = "*.spk";
9271
		else if ( i == 1 ) pattern = ".xsp";
9272
		else break;
9273
 
126 cycrow 9274
		Utils::CStringList files;
9275
		if(Dir.dirList(files, "", pattern))
1 cycrow 9276
		{
126 cycrow 9277
			for(auto itr = files.begin(); itr != files.end(); itr++)
1 cycrow 9278
			{
9279
				int error = 0;
126 cycrow 9280
				CBaseFile *p = packages.OpenPackage(Dir.file((*itr)->str), &error, 0, SPKREAD_NODATA);
1 cycrow 9281
				if ( !p )
9282
					continue;
9283
 
9284
				if ( includeSingle )
9285
					p->CreateUpdateFile(dir);
126 cycrow 9286
				filedata.pushBack(CPackages::FormatAvailablePackageData(p));
1 cycrow 9287
				delete p;
9288
			}
9289
		}
9290
	}
9291
 
126 cycrow 9292
	if ( !filedata.empty() )
1 cycrow 9293
	{
9294
		CFileIO File(dir + "/xpackagedata.dat");
126 cycrow 9295
		if ( File.writeFile(&filedata) )
9296
			return filedata.size();
1 cycrow 9297
	}
9298
 
9299
	return 0;
9300
}
9301
 
9302
int CPackages::VerifyInstalledFiles(CyStringList *missingFiles, bool getPackages)
9303
{
9304
	int count = 0;
9305
	for ( CListNode<C_File> *fn = m_lFiles.Front(); fn; fn = fn->next() )
9306
	{
9307
		C_File *f = fn->Data();
9308
		bool exists = false;
9309
		if ( f->GetFilePointer().IsIn("::") ) {
9310
			CyString modFile = f->GetFilePointer().GetToken("::", 1, 1);
9311
			CyString file = f->GetFilePointer().GetToken("::", 2, 2);
9312
 
52 cycrow 9313
			if ( CFileIO(modFile).ExistsOld() ) {
1 cycrow 9314
				CCatFile catFile;
125 cycrow 9315
				if ( catFile.open(modFile.ToString(), "", CATREAD_CATDECRYPT, false) == CATERR_NONE ) {
1 cycrow 9316
					if ( catFile.FindData(file) )
9317
						exists = true;
9318
				}
9319
			}
9320
		}
9321
		else {
52 cycrow 9322
			exists = CFileIO(f->GetFilePointer()).ExistsOld();
1 cycrow 9323
		}
9324
 
9325
		if ( !exists )
9326
		{
9327
			++count;
9328
			if ( missingFiles )
9329
			{
9330
				CyString packages;
9331
				if ( getPackages )
9332
				{
9333
					for ( CListNode<CBaseFile> *p = m_lPackages.Front(); p; p = p->next() )
9334
					{
9335
						CBaseFile *package = p->Data();
9336
						if ( package->IsFileAdded(f) )
9337
						{
9338
							if ( !packages.Empty() )
9339
								packages += "\n";
9340
							packages += package->GetFullPackageName(m_iLanguage);
9341
						}
9342
					}
9343
				}
9344
				CyString filename = f->GetFilePointer();
9345
				filename = filename.Remove(m_sCurrentDir);
9346
				missingFiles->PushBack(filename, packages, false);
9347
			}
9348
		}
9349
	}
9350
	return count;
35 cycrow 9351
}