Subversion Repositories spk

Rev

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