Subversion Repositories spk

Rev

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