source: java/installer2/src/net/oni2/aeinstaller/backend/oni/Installer.java@ 744

Last change on this file since 744 was 744, checked in by alloc, 12 years ago

AEI2 0.99w:

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