ViewVC Help
View File | Revision Log | View Changeset | Root Listing
root/Oni2/AE/installer2/src/net/oni2/aeinstaller/backend/oni/Installer.java
Revision: 702
Committed: Tue Mar 19 10:00:06 2013 UTC (12 years, 8 months ago) by alloc
Content type: text/x-java
File size: 29383 byte(s)
Log Message:
AEI2 0.99u:
- Fixed a few bugs in apply patches
- Added some log output to apply patches

File Contents

# Content
1 package net.oni2.aeinstaller.backend.oni;
2
3 import java.io.File;
4 import java.io.FileFilter;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.FileOutputStream;
8 import java.io.FilenameFilter;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.PrintWriter;
12 import java.text.SimpleDateFormat;
13 import java.util.Date;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Scanner;
18 import java.util.TreeMap;
19 import java.util.TreeSet;
20 import java.util.Vector;
21 import java.util.regex.Pattern;
22
23 import net.oni2.aeinstaller.AEInstaller2;
24 import net.oni2.aeinstaller.backend.CaseInsensitiveFile;
25 import net.oni2.aeinstaller.backend.Paths;
26 import net.oni2.aeinstaller.backend.Settings;
27 import net.oni2.aeinstaller.backend.Settings.Platform;
28 import net.oni2.aeinstaller.backend.appexecution.AppExecutionResult;
29 import net.oni2.aeinstaller.backend.packages.EBSLInstallType;
30 import net.oni2.aeinstaller.backend.packages.Package;
31 import net.oni2.aeinstaller.backend.packages.PackageManager;
32
33 import org.apache.commons.io.FileUtils;
34 import org.apache.commons.io.filefilter.RegexFileFilter;
35 import org.apache.commons.io.filefilter.TrueFileFilter;
36 import org.javabuilders.swing.SwingJavaBuilder;
37
38 import com.thoughtworks.xstream.XStream;
39 import com.thoughtworks.xstream.io.xml.StaxDriver;
40
41 /**
42 * @author Christian Illy
43 */
44 public class Installer {
45 private static FileFilter dirFileFilter = new FileFilter() {
46 @Override
47 public boolean accept(File pathname) {
48 return pathname.isDirectory();
49 }
50 };
51
52 /**
53 * @return Is Edition Core initialized
54 */
55 public static boolean isEditionInitialized() {
56 return Paths.getVanillaOnisPath().exists();
57 }
58
59 private static void createEmptyPath(File path) throws IOException {
60 if (path.exists())
61 FileUtils.deleteDirectory(path);
62 path.mkdirs();
63 }
64
65 /**
66 * @return list of currently installed mods
67 */
68 public static Vector<Integer> getInstalledMods() {
69 File installCfg = new File(Paths.getEditionGDF(), "installed_mods.xml");
70 return PackageManager.getInstance().loadModSelection(installCfg);
71 }
72
73 /**
74 * @return Currently installed tools
75 */
76 @SuppressWarnings("unchecked")
77 public static TreeSet<Integer> getInstalledTools() {
78 File installCfg = new File(Paths.getInstallerPath(),
79 "installed_tools.xml");
80 TreeSet<Integer> res = new TreeSet<Integer>();
81 try {
82 if (installCfg.exists()) {
83 FileInputStream fis = new FileInputStream(installCfg);
84 XStream xs = new XStream(new StaxDriver());
85 Object obj = xs.fromXML(fis);
86 if (obj instanceof TreeSet<?>)
87 res = (TreeSet<Integer>) obj;
88 fis.close();
89 }
90 } catch (FileNotFoundException e) {
91 e.printStackTrace();
92 } catch (IOException e) {
93 e.printStackTrace();
94 }
95 return res;
96 }
97
98 private static void writeInstalledTools(TreeSet<Integer> tools) {
99 File installCfg = new File(Paths.getInstallerPath(),
100 "installed_tools.xml");
101 try {
102 FileOutputStream fos = new FileOutputStream(installCfg);
103 XStream xs = new XStream(new StaxDriver());
104 xs.toXML(tools, fos);
105 fos.close();
106 } catch (FileNotFoundException e) {
107 e.printStackTrace();
108 } catch (IOException e) {
109 e.printStackTrace();
110 }
111 }
112
113 /**
114 * @param tools
115 * Tools to (un)install
116 * @param uninstall
117 * Uninstall tools or install?
118 */
119 public static void installTools(TreeSet<Package> tools, boolean uninstall) {
120 TreeSet<Integer> installed = getInstalledTools();
121 for (Package m : tools) {
122 if (!uninstall || installed.contains(m.getPackageNumber())) {
123 File plain = CaseInsensitiveFile.getCaseInsensitiveFile(
124 m.getLocalPath(), "plain");
125 if (plain.exists()) {
126 if (m.hasSeparatePlatformDirs()) {
127 File plainCommon = CaseInsensitiveFile
128 .getCaseInsensitiveFile(plain, "common");
129 File plainMac = CaseInsensitiveFile
130 .getCaseInsensitiveFile(plain, "mac_only");
131 File plainWin = CaseInsensitiveFile
132 .getCaseInsensitiveFile(plain, "win_only");
133 if (plainCommon.exists())
134 copyRemoveToolsFiles(plainCommon,
135 Paths.getEditionBasePath(), uninstall);
136 if (Settings.getPlatform() == Platform.MACOS
137 && plainMac.exists())
138 copyRemoveToolsFiles(plainMac,
139 Paths.getEditionBasePath(), uninstall);
140 else if (plainWin.exists())
141 copyRemoveToolsFiles(plainWin,
142 Paths.getEditionBasePath(), uninstall);
143 } else {
144 copyRemoveToolsFiles(plain, Paths.getEditionBasePath(),
145 uninstall);
146 }
147 }
148 }
149 if (uninstall)
150 installed.remove(m.getPackageNumber());
151 else
152 installed.add(m.getPackageNumber());
153 }
154 writeInstalledTools(installed);
155 }
156
157 private static void copyRemoveToolsFiles(File srcFolder, File targetFolder,
158 boolean remove) {
159 for (File f : srcFolder.listFiles()) {
160 try {
161 if (f.isDirectory())
162 copyRemoveToolsFiles(f,
163 CaseInsensitiveFile.getCaseInsensitiveFile(
164 targetFolder, f.getName()), remove);
165 else {
166 File targetFile = CaseInsensitiveFile
167 .getCaseInsensitiveFile(targetFolder, f.getName());
168 if (remove) {
169 if (targetFile.exists())
170 targetFile.delete();
171 } else {
172 if (!targetFile.getName().equals(f.getName()))
173 targetFile.delete();
174 FileUtils.copyFileToDirectory(f, targetFolder);
175 }
176 }
177 } catch (IOException e) {
178 e.printStackTrace();
179 }
180 }
181 if (remove)
182 if (targetFolder.list().length == 0)
183 targetFolder.delete();
184 }
185
186 /**
187 * Install the given set of mods
188 *
189 * @param mods
190 * Mods to install
191 * @param listener
192 * Listener for install progress updates
193 */
194 public static void install(TreeSet<Package> mods,
195 InstallProgressListener listener) {
196 File logFile = new File(Paths.getInstallerPath(), "Installation.log");
197 PrintWriter log = null;
198 try {
199 log = new PrintWriter(logFile);
200 } catch (FileNotFoundException e) {
201 e.printStackTrace();
202 }
203 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
204 Date start = new Date();
205 log.println("Installation of mods started at " + sdf.format(start));
206
207 log.println();
208 log.println("AEI2 version: "
209 + SwingJavaBuilder.getConfig().getResource("appversion"));
210 log.println("Installed tools:");
211 for (Package t : PackageManager.getInstance().getInstalledTools()) {
212 log.println(String.format(" - %s (%s)", t.getName(), t.getVersion()));
213 }
214 log.println("Installing mods:");
215 for (Package m : mods) {
216 log.println(String.format(" - %s (%s)", m.getName(), m.getVersion()));
217 }
218 log.println();
219
220 Paths.getEditionGDF().mkdirs();
221 for (File f : Paths.getEditionGDF().listFiles(new FilenameFilter() {
222 public boolean accept(File arg0, String arg1) {
223 String s = arg1.toLowerCase();
224 return s.endsWith(".dat")
225 || s.endsWith(".raw")
226 || s.endsWith(".sep")
227 || (s.equals("intro.bik") && !Settings.getInstance()
228 .get("copyintro", false))
229 || (s.equals("outro.bik") && !Settings.getInstance()
230 .get("copyoutro", false));
231 }
232 })) {
233 f.delete();
234 }
235 File IGMD = new File(Paths.getEditionGDF(), "IGMD");
236 if (IGMD.exists()) {
237 for (File f : IGMD.listFiles(new FileFilter() {
238 @Override
239 public boolean accept(File pathname) {
240 return pathname.isDirectory();
241 }
242 })) {
243 File ignore = CaseInsensitiveFile.getCaseInsensitiveFile(f,
244 "ignore.txt");
245 if (!ignore.exists()) {
246 try {
247 FileUtils.deleteDirectory(f);
248 } catch (IOException e) {
249 e.printStackTrace();
250 }
251 }
252 }
253 }
254
255 File installCfg = new File(Paths.getEditionGDF(), "installed_mods.xml");
256 PackageManager.getInstance().saveModSelection(installCfg, mods);
257
258 TreeSet<Integer> unlockLevels = new TreeSet<Integer>();
259
260 Vector<File> foldersOni = new Vector<File>();
261 foldersOni.add(Paths.getVanillaOnisPath());
262
263 Vector<File> foldersPatches = new Vector<File>();
264
265 for (Package m : mods) {
266 for (int lev : m.getUnlockLevels())
267 unlockLevels.add(lev);
268
269 File oni = CaseInsensitiveFile.getCaseInsensitiveFile(
270 m.getLocalPath(), "oni");
271 if (oni.exists()) {
272 if (m.hasSeparatePlatformDirs()) {
273 File oniCommon = CaseInsensitiveFile
274 .getCaseInsensitiveFile(oni, "common");
275 File oniMac = CaseInsensitiveFile.getCaseInsensitiveFile(
276 oni, "mac_only");
277 File oniWin = CaseInsensitiveFile.getCaseInsensitiveFile(
278 oni, "win_only");
279 if (oniCommon.exists())
280 foldersOni.add(oniCommon);
281 if (Settings.getPlatform() == Platform.MACOS
282 && oniMac.exists())
283 foldersOni.add(oniMac);
284 else if (oniWin.exists())
285 foldersOni.add(oniWin);
286 } else {
287 foldersOni.add(oni);
288 }
289 }
290
291 File patches = CaseInsensitiveFile.getCaseInsensitiveFile(
292 m.getLocalPath(), "patches");
293 if (patches.exists()) {
294 if (m.hasSeparatePlatformDirs()) {
295 File patchesCommon = CaseInsensitiveFile
296 .getCaseInsensitiveFile(patches, "common");
297 File patchesMac = CaseInsensitiveFile
298 .getCaseInsensitiveFile(patches, "mac_only");
299 File patchesWin = CaseInsensitiveFile
300 .getCaseInsensitiveFile(patches, "win_only");
301 if (patchesCommon.exists())
302 foldersPatches.add(patchesCommon);
303 if (Settings.getPlatform() == Platform.MACOS
304 && patchesMac.exists())
305 foldersPatches.add(patchesMac);
306 else if (patchesWin.exists())
307 foldersPatches.add(patchesWin);
308 } else {
309 foldersPatches.add(patches);
310 }
311 }
312 }
313
314 TreeMap<String, Vector<File>> levels = new TreeMap<String, Vector<File>>();
315 for (File path : foldersOni) {
316 for (File levelF : path.listFiles()) {
317 String fn = levelF.getName().toLowerCase();
318 String levelN = null;
319 if (levelF.isDirectory()) {
320 levelN = fn;
321 } else if (fn.endsWith(".dat")) {
322 levelN = fn.substring(0, fn.lastIndexOf('.')).toLowerCase();
323 }
324 if (levelN != null) {
325 if (!levels.containsKey(levelN))
326 levels.put(levelN, new Vector<File>());
327 levels.get(levelN).add(levelF);
328 }
329 }
330 }
331
332 applyPatches(levels, foldersPatches, listener, log);
333
334 combineBinaryFiles(levels, listener, log);
335 combineBSLFolders(mods, listener, log);
336
337 copyVideos(log);
338
339 if (unlockLevels.size() > 0) {
340 unlockLevels(unlockLevels, log);
341 }
342
343 log.println();
344 Date end = new Date();
345 log.println("Initialization ended at " + sdf.format(end));
346 log.println("Process took "
347 + ((end.getTime() - start.getTime()) / 1000) + " seconds");
348 log.close();
349 }
350
351 private static void combineBSLFolders(TreeSet<Package> mods,
352 InstallProgressListener listener, PrintWriter log) {
353 listener.installProgressUpdate(95, 100, "Installing BSL files");
354 log.println("Installing BSL files");
355
356 HashMap<EBSLInstallType, Vector<Package>> modsToInclude = new HashMap<EBSLInstallType, Vector<Package>>();
357 modsToInclude.put(EBSLInstallType.NORMAL, new Vector<Package>());
358 modsToInclude.put(EBSLInstallType.ADDON, new Vector<Package>());
359
360 for (Package m : mods.descendingSet()) {
361 File bsl = CaseInsensitiveFile.getCaseInsensitiveFile(
362 m.getLocalPath(), "bsl");
363 if (bsl.exists()) {
364 if (m.hasSeparatePlatformDirs()) {
365 File bslCommon = CaseInsensitiveFile
366 .getCaseInsensitiveFile(bsl, "common");
367 File bslMac = CaseInsensitiveFile.getCaseInsensitiveFile(
368 bsl, "mac_only");
369 File bslWin = CaseInsensitiveFile.getCaseInsensitiveFile(
370 bsl, "win_only");
371 if ((Settings.getPlatform() == Platform.MACOS && bslMac
372 .exists())
373 || ((Settings.getPlatform() == Platform.WIN || Settings
374 .getPlatform() == Platform.LINUX) && bslWin
375 .exists()) || bslCommon.exists()) {
376 modsToInclude.get(m.getBSLInstallType()).add(m);
377 }
378 } else {
379 modsToInclude.get(m.getBSLInstallType()).add(m);
380 }
381 }
382 }
383
384 for (Package m : modsToInclude.get(EBSLInstallType.NORMAL)) {
385 copyBSL(m, false);
386 }
387 Vector<Package> addons = modsToInclude.get(EBSLInstallType.ADDON);
388 for (int i = addons.size() - 1; i >= 0; i--) {
389 copyBSL(addons.get(i), true);
390 }
391 }
392
393 private static void copyBSL(Package sourceMod, boolean addon) {
394 File targetBaseFolder = new File(Paths.getEditionGDF(), "IGMD");
395 if (!targetBaseFolder.exists())
396 targetBaseFolder.mkdir();
397
398 Vector<File> sources = new Vector<File>();
399 File bsl = CaseInsensitiveFile.getCaseInsensitiveFile(
400 sourceMod.getLocalPath(), "bsl");
401 if (sourceMod.hasSeparatePlatformDirs()) {
402 File bslCommon = CaseInsensitiveFile.getCaseInsensitiveFile(bsl,
403 "common");
404 File bslMac = CaseInsensitiveFile.getCaseInsensitiveFile(bsl,
405 "mac_only");
406 File bslWin = CaseInsensitiveFile.getCaseInsensitiveFile(bsl,
407 "win_only");
408 if (Settings.getPlatform() == Platform.MACOS && bslMac.exists()) {
409 for (File f : bslMac.listFiles(dirFileFilter)) {
410 File targetBSL = new File(targetBaseFolder, f.getName());
411 if (addon || !targetBSL.exists())
412 sources.add(f);
413 }
414 }
415 if ((Settings.getPlatform() == Platform.WIN || Settings
416 .getPlatform() == Platform.LINUX) && bslWin.exists()) {
417 for (File f : bslWin.listFiles(dirFileFilter)) {
418 File targetBSL = new File(targetBaseFolder, f.getName());
419 if (addon || !targetBSL.exists())
420 sources.add(f);
421 }
422 }
423 if (bslCommon.exists()) {
424 for (File f : bslCommon.listFiles(dirFileFilter)) {
425 File targetBSL = new File(targetBaseFolder, f.getName());
426 if (addon || !targetBSL.exists())
427 sources.add(f);
428 }
429 }
430 } else {
431 for (File f : bsl.listFiles(dirFileFilter)) {
432 File targetBSL = new File(targetBaseFolder, f.getName());
433 if (addon || !targetBSL.exists())
434 sources.add(f);
435 }
436 }
437
438 System.out.println("For mod: " + sourceMod.getName()
439 + " install BSL folders: " + sources.toString());
440 for (File f : sources) {
441 File targetPath = new File(targetBaseFolder, f.getName());
442 if (!targetPath.exists())
443 targetPath.mkdir();
444 if (!(CaseInsensitiveFile.getCaseInsensitiveFile(targetPath,
445 "ignore.txt").exists())) {
446 for (File fbsl : f.listFiles()) {
447 if (fbsl.getName().toLowerCase().endsWith(".bsl")) {
448 File targetFile = new File(targetPath, fbsl.getName());
449 if (addon || !targetFile.exists()) {
450 try {
451 FileUtils.copyFile(fbsl, targetFile);
452 } catch (IOException e) {
453 e.printStackTrace();
454 }
455 }
456 }
457 }
458 }
459 }
460 }
461
462 private static void applyPatches(
463 TreeMap<String, Vector<File>> oniLevelFolders,
464 List<File> patchFolders, InstallProgressListener listener,
465 PrintWriter log) {
466 log.println();
467 log.println("Applying XML patches");
468 listener.installProgressUpdate(0, 1, "Applying XML patches");
469
470 // TODO: REMOVE
471 long startMS = new Date().getTime();
472
473 String tmpFolderName = "installrun_temp-"
474 + new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss")
475 .format(new Date());
476 File tmpFolder = new File(Paths.getTempPath(), tmpFolderName);
477 tmpFolder.mkdir();
478
479 HashMap<String, Vector<File>> patches = new HashMap<String, Vector<File>>();
480 for (File patchFolder : patchFolders) {
481 for (File levelFolder : patchFolder.listFiles(dirFileFilter)) {
482 String lvlName = levelFolder.getName().toLowerCase();
483 for (File f : FileUtils.listFiles(levelFolder,
484 new String[] { "oni-patch" }, true)) {
485 if (!patches.containsKey(lvlName))
486 patches.put(lvlName, new Vector<File>());
487 patches.get(lvlName).add(f);
488 }
489 }
490 }
491
492 for (String level : patches.keySet()) {
493 File levelFolder = new File(tmpFolder, level);
494 levelFolder.mkdir();
495
496 log.println("\t\tPatches for " + level);
497
498 Vector<String> exportPatterns = new Vector<String>();
499 // Get files to be patched from vanilla.dat
500 for (File patch : patches.get(level)) {
501 String patternWildcard = patch.getName();
502 patternWildcard = patternWildcard.substring(0,
503 patternWildcard.indexOf(".oni-patch"));
504 patternWildcard = patternWildcard.replace('-', '*');
505 exportPatterns.add(patternWildcard);
506 }
507 for (File srcFolder : oniLevelFolders.get(level)) {
508 if (srcFolder.isFile()) {
509 if (srcFolder.getPath().toLowerCase().contains("vanilla")) {
510 // Extract from .dat
511 AppExecutionResult res = OniSplit.export(levelFolder,
512 srcFolder, exportPatterns);
513 logAppOutput(res, log);
514 }
515 }
516 }
517
518 // Get files to be patched from packages
519 for (File patch : patches.get(level)) {
520 String patternWildcard = patch.getName();
521 patternWildcard = patternWildcard.substring(0,
522 patternWildcard.indexOf(".oni-patch"));
523 patternWildcard = patternWildcard.replace('-', '*');
524 patternWildcard = patternWildcard + ".oni";
525 Vector<String> patterns = new Vector<String>();
526 patterns.add(patternWildcard);
527 final Pattern patternRegex = Pattern.compile(
528 patternWildcard.replaceAll("\\*", ".\\*"),
529 Pattern.CASE_INSENSITIVE);
530
531 for (File srcFolder : oniLevelFolders.get(level)) {
532 if (srcFolder.isFile()) {
533 if (!srcFolder.getPath().toLowerCase()
534 .contains("vanilla")) {
535 // Extract from .dat
536 AppExecutionResult res = OniSplit.export(
537 levelFolder, srcFolder, patterns);
538 logAppOutput(res, log);
539 }
540 } else {
541 // Copy from folder with overwrite
542 for (File f : FileUtils.listFiles(srcFolder,
543 new RegexFileFilter(patternRegex),
544 TrueFileFilter.TRUE)) {
545 try {
546 FileUtils.copyFileToDirectory(f, levelFolder);
547 } catch (IOException e) {
548 e.printStackTrace();
549 }
550 }
551 }
552 }
553 }
554
555 // Extract files to XML
556 File levelFolderXML = new File(levelFolder, "xml");
557 Vector<File> files = new Vector<File>();
558 files.add(new File(levelFolder, "*.oni"));
559 AppExecutionResult res = OniSplit.convertOniToXML(levelFolderXML,
560 files);
561 logAppOutput(res, log);
562
563 // Apply patches in levelFolderXML
564 for (File patch : patches.get(level)) {
565 String patternWildcard = patch.getName();
566 patternWildcard = patternWildcard.substring(0,
567 patternWildcard.indexOf(".oni-patch"));
568 patternWildcard = patternWildcard + ".xml";
569 patternWildcard = patternWildcard.replace('-', '*');
570
571 res = XMLTools.patch(patch, new File(levelFolderXML,
572 patternWildcard));
573 logAppOutput(res, log);
574 }
575
576 // Create .oni files from XML
577 files.clear();
578 files.add(new File(levelFolderXML, "*.xml"));
579 res = OniSplit.convertXMLtoOni(levelFolder, files);
580 logAppOutput(res, log);
581
582 // Remove XML folder as import will only require .oni's
583 // try {
584 // FileUtils.deleteDirectory(levelFolderXML);
585 // } catch (IOException e) {
586 // e.printStackTrace();
587 // }
588
589 oniLevelFolders.get(level).add(levelFolder);
590
591 log.println();
592 }
593
594 System.out.println("Took: " + (new Date().getTime() - startMS)
595 + " msec");
596 }
597
598 private static void combineBinaryFiles(
599 TreeMap<String, Vector<File>> oniLevelFolders,
600 InstallProgressListener listener, PrintWriter log) {
601 int totalSteps = 0;
602 int stepsDone = 0;
603
604 for (@SuppressWarnings("unused")
605 String s : oniLevelFolders.keySet())
606 totalSteps++;
607 totalSteps++;
608
609 log.println();
610 log.println("Importing levels");
611 for (String l : oniLevelFolders.keySet()) {
612 log.println("\tLevel " + l);
613 listener.installProgressUpdate(stepsDone, totalSteps,
614 "Installing level " + l);
615
616 AppExecutionResult res = OniSplit.packLevel(oniLevelFolders.get(l),
617 new File(Paths.getEditionGDF(), sanitizeLevelName(l)
618 + ".dat"));
619 logAppOutput(res, log);
620
621 log.println();
622 stepsDone++;
623 }
624 }
625
626 private static void copyVideos(PrintWriter log) {
627 if (Settings.getInstance().get("copyintro", false)) {
628 File src = new File(Paths.getVanillaGDF(), "intro.bik");
629 log.println("Copying intro");
630 if (src.exists()) {
631 try {
632 FileUtils.copyFileToDirectory(src, Paths.getEditionGDF());
633 } catch (IOException e) {
634 e.printStackTrace();
635 }
636 }
637 } else {
638 log.println("NOT copying intro");
639 }
640 if (Settings.getInstance().get("copyoutro", true)) {
641 File src = new File(Paths.getVanillaGDF(), "outro.bik");
642 log.println("Copying outro");
643 if (src.exists()) {
644 try {
645 FileUtils.copyFileToDirectory(src, Paths.getEditionGDF());
646 } catch (IOException e) {
647 e.printStackTrace();
648 }
649 }
650 } else {
651 log.println("NOT copying outro");
652 }
653 }
654
655 private static void unlockLevels(TreeSet<Integer> unlockLevels,
656 PrintWriter log) {
657 File dat = new File(Paths.getEditionBasePath(), "persist.dat");
658 log.println("Unlocking levels: " + unlockLevels.toString());
659 if (!dat.exists()) {
660 InputStream is = AEInstaller2.class
661 .getResourceAsStream("/net/oni2/aeinstaller/resources/persist.dat");
662 try {
663 FileUtils.copyInputStreamToFile(is, dat);
664 } catch (IOException e) {
665 e.printStackTrace();
666 }
667 }
668 PersistDat save = new PersistDat(dat);
669 HashSet<Integer> currentlyUnlocked = save.getUnlockedLevels();
670 currentlyUnlocked.addAll(unlockLevels);
671 save.setUnlockedLevels(currentlyUnlocked);
672 save.close();
673 }
674
675 /**
676 * Initializes the Edition core
677 *
678 * @param listener
679 * Listener for status updates
680 */
681 public static void initializeEdition(InstallProgressListener listener) {
682 File init = new File(Paths.getTempPath(), "init");
683
684 int totalSteps = 0;
685 int stepsDone = 0;
686
687 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
688
689 for (@SuppressWarnings("unused")
690 File f : Paths.getVanillaGDF().listFiles(new FilenameFilter() {
691 @Override
692 public boolean accept(File dir, String name) {
693 return name.endsWith(".dat");
694 }
695 })) {
696 totalSteps++;
697 }
698 totalSteps = totalSteps * 2 + 2;
699
700 try {
701 File logFile = new File(Paths.getInstallerPath(),
702 "Initialization.log");
703 PrintWriter log = new PrintWriter(logFile);
704
705 Date start = new Date();
706 log.println("Initialization of Edition core started at "
707 + sdf.format(start));
708 log.println("Cleaning directories");
709
710 listener.installProgressUpdate(stepsDone, totalSteps,
711 "Cleaning up directories");
712 createEmptyPath(Paths.getVanillaOnisPath());
713 createEmptyPath(init);
714 File level0Folder = new File(init, "level0_Final");
715 createEmptyPath(level0Folder);
716
717 stepsDone++;
718
719 log.println("Exporting levels and moving files to level0");
720
721 for (File f : Paths.getVanillaGDF().listFiles(new FilenameFilter() {
722 @Override
723 public boolean accept(File dir, String name) {
724 return name.endsWith(".dat");
725 }
726 })) {
727 String levelName = f.getName().substring(0,
728 f.getName().indexOf('.'));
729 Scanner fi = new Scanner(levelName);
730 int levelNumber = Integer.parseInt(fi.findInLine("[0-9]+"));
731
732 log.println("\t" + levelName + ":");
733 log.println("\t\tExporting");
734 listener.installProgressUpdate(stepsDone, totalSteps,
735 "Exporting vanilla level " + levelNumber);
736
737 // Edition/GameDataFolder/level*_Final/
738 File tempLevelFolder = new File(init, levelName);
739
740 // Export Vanilla-Level-Dat -> Temp/Level
741 AppExecutionResult res = OniSplit.export(tempLevelFolder, f);
742 logAppOutput(res, log);
743
744 log.println("\t\tMoving files");
745 handleFileGlobalisation(tempLevelFolder, level0Folder,
746 levelNumber);
747 stepsDone++;
748 log.println();
749 }
750
751 log.println("Reimporting levels");
752
753 for (File f : init.listFiles()) {
754 String levelName = f.getName();
755
756 log.println("\t" + levelName);
757 listener.installProgressUpdate(stepsDone, totalSteps,
758 "Creating globalized " + levelName);
759
760 Vector<File> folders = new Vector<File>();
761 folders.add(f);
762
763 AppExecutionResult res = OniSplit
764 .importLevel(folders,
765 new File(Paths.getVanillaOnisPath(), levelName
766 + ".dat"));
767 logAppOutput(res, log);
768
769 log.println();
770 stepsDone++;
771 }
772
773 listener.installProgressUpdate(stepsDone, totalSteps,
774 "Copying basic files");
775 // Copy Oni-configs
776 File persistVanilla = new File(Paths.getOniBasePath(),
777 "persist.dat");
778 File persistEdition = new File(Paths.getEditionBasePath(),
779 "persist.dat");
780 File keyConfVanilla = new File(Paths.getOniBasePath(),
781 "key_config.txt");
782 File keyConfEdition = new File(Paths.getEditionBasePath(),
783 "key_config.txt");
784 if (persistVanilla.exists() && !persistEdition.exists())
785 FileUtils.copyFile(persistVanilla, persistEdition);
786 if (keyConfVanilla.exists() && !keyConfEdition.exists())
787 FileUtils.copyFile(keyConfVanilla, keyConfEdition);
788
789 FileUtils.deleteDirectory(init);
790
791 Date end = new Date();
792 log.println("Initialization ended at " + sdf.format(end));
793 log.println("Process took "
794 + ((end.getTime() - start.getTime()) / 1000) + " seconds");
795 log.close();
796 } catch (IOException e) {
797 e.printStackTrace();
798 }
799 }
800
801 private static void moveFileToTargetOrDelete(File source, File target) {
802 if (source.equals(target))
803 return;
804 if (!target.exists()) {
805 if (!source.renameTo(target)) {
806 System.err.println("File " + source.getPath() + " not moved!");
807 }
808 } else if (!source.delete()) {
809 System.err.println("File " + source.getPath() + " not deleted!");
810 }
811 }
812
813 private static void handleFileGlobalisation(File tempFolder,
814 File level0Folder, int levelNumber) {
815 // Move AKEV and related files to subfolder so they're not globalized:
816 if (levelNumber != 0) {
817 File akevFolder = new File(tempFolder, "AKEV");
818 akevFolder.mkdir();
819 OniSplit.move(akevFolder, tempFolder.getPath() + "/AKEV*.oni",
820 "overwrite");
821 }
822
823 for (File f : tempFolder.listFiles(new FileFilter() {
824 @Override
825 public boolean accept(File pathname) {
826 return pathname.isFile();
827 }
828 })) {
829 // Move matching files to subfolder NoGlobal:
830 if (f.getName().startsWith("TXMPfail")
831 || f.getName().startsWith("TXMPlevel")
832 || (f.getName().startsWith("TXMP") && f.getName().contains(
833 "intro"))
834 || f.getName().startsWith("TXMB")
835 || f.getName().equals("M3GMpowerup_lsi.oni")
836 || f.getName().equals("TXMPlsi_icon.oni")
837 || (f.getName().startsWith("TXMB") && f.getName().contains(
838 "splash_screen.oni"))) {
839 File noGlobal = new File(tempFolder, "NoGlobal");
840 noGlobal.mkdir();
841 File noGlobalFile = new File(noGlobal, f.getName());
842 moveFileToTargetOrDelete(f, noGlobalFile);
843 }
844 // Move matching files to level0_Animations/level0_TRAC
845 else if (f.getName().startsWith("TRAC")) {
846 File level0File = new File(level0Folder, f.getName());
847 moveFileToTargetOrDelete(f, level0File);
848 }
849 // Move matching files to level0_Animations/level0_TRAM
850 else if (f.getName().startsWith("TRAM")) {
851 File level0File = new File(level0Folder, f.getName());
852 moveFileToTargetOrDelete(f, level0File);
853 }
854 // Move matching files to level0_Textures
855 else if (f.getName().startsWith("ONSK")
856 || f.getName().startsWith("TXMP")) {
857 File level0File = new File(level0Folder, f.getName());
858 moveFileToTargetOrDelete(f, level0File);
859 }
860 // Move matching files to *VANILLA*/level0_Characters
861 else if (f.getName().startsWith("ONCC")
862 || f.getName().startsWith("TRBS")
863 || f.getName().startsWith("ONCV")
864 || f.getName().startsWith("ONVL")
865 || f.getName().startsWith("TRMA")
866 || f.getName().startsWith("TRSC")
867 || f.getName().startsWith("TRAS")) {
868 File level0File = new File(level0Folder, f.getName());
869 moveFileToTargetOrDelete(f, level0File);
870 }
871 // Move matching files to level0_Sounds
872 else if (f.getName().startsWith("OSBD")
873 || f.getName().startsWith("SNDD")) {
874 File level0File = new File(level0Folder, f.getName());
875 moveFileToTargetOrDelete(f, level0File);
876 }
877 // Move matching files to level0_Particles
878 else if (f.getName().startsWith("BINA3")
879 || f.getName().startsWith("M3GMdebris")
880 || f.getName().equals("M3GMtoxic_bubble.oni")
881 || f.getName().startsWith("M3GMelec")
882 || f.getName().startsWith("M3GMrat")
883 || f.getName().startsWith("M3GMjet")
884 || f.getName().startsWith("M3GMbomb_")
885 || f.getName().equals("M3GMbarab_swave.oni")
886 || f.getName().equals("M3GMbloodyfoot.oni")) {
887 File level0File = new File(level0Folder, f.getName());
888 moveFileToTargetOrDelete(f, level0File);
889 }
890 // Move matching files to Archive (aka delete them)
891 else if (f.getName().startsWith("AGDB")
892 || f.getName().startsWith("TRCM")) {
893 f.delete();
894 }
895 // Move matching files to /level0_Final/
896 else if (f.getName().startsWith("ONWC")) {
897 File level0File = new File(level0Folder, f.getName());
898 moveFileToTargetOrDelete(f, level0File);
899 }
900 }
901 }
902
903 private static String sanitizeLevelName(String ln) {
904 int ind = ln.indexOf("_");
905 String res = ln.substring(0, ind + 1);
906 res += ln.substring(ind + 1, ind + 2).toUpperCase();
907 res += ln.substring(ind + 2);
908 return res;
909 }
910
911 /**
912 * Verify that the Edition is within a subfolder to vanilla Oni
913 * (..../Oni/Edition/AEInstaller)
914 *
915 * @return true if GDF can be found in the parent's parent-path
916 */
917 public static boolean verifyRunningDirectory() {
918 return Paths.getVanillaGDF().exists()
919 && Paths.getVanillaGDF().isDirectory();
920 }
921
922 private static void logAppOutput(AppExecutionResult result, PrintWriter log) {
923 if (result != null) {
924 log.println("\t\t\tCalled:");
925 for (String s : result.cmdLine)
926 log.println("\t\t\t\t" + s);
927 log.println("\t\t\tReturned: " + result.errorCode);
928 for (String s : result.output)
929 log.println("\t\t\t\t" + s);
930 log.println();
931 }
932 }
933 }