Subversion Repositories spk

Rev

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