Subversion Repositories spk

Rev

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

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