Subversion Repositories spk

Rev

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