Subversion Repositories spk

Rev

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