Subversion Repositories spk

Rev

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