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

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

AEI2 0.99w:

  • Correct ordering when processing levels when initializing / installing
File size: 29.2 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>>(new NaturalOrderComparator());
317 for (File path : foldersOni) {
318 for (File levelF : path.listFiles()) {
319 String fn = levelF.getName().toLowerCase();
320 String levelN = null;
321 if (levelF.isDirectory()) {
322 levelN = fn;
323 } else if (fn.endsWith(".dat")) {
324 levelN = fn.substring(0, fn.lastIndexOf('.')).toLowerCase();
325 }
326 if (levelN != null) {
327 if (!levels.containsKey(levelN))
328 levels.put(levelN, new Vector<File>());
329 levels.get(levelN).add(levelF);
330 }
331 }
332 }
333
334 applyPatches(levels, foldersPatches, listener, log);
335
336 combineBinaryFiles(levels, listener, log);
337 combineBSLFolders(mods, listener, log);
338
339 copyVideos(log);
340
341 if (unlockLevels.size() > 0) {
342 unlockLevels(unlockLevels, log);
343 }
344
345 log.println();
346 Date end = new Date();
347 log.println("Initialization ended at " + sdf.format(end));
348 log.println("Process took "
349 + ((end.getTime() - start.getTime()) / 1000) + " seconds");
350 log.close();
351 }
352
353 private static void combineBSLFolders(TreeSet<Package> mods,
354 InstallProgressListener listener, PrintWriter log) {
355 listener.installProgressUpdate(95, 100, "Installing BSL files");
356 log.println("Installing BSL files");
357
358 HashMap<EBSLInstallType, Vector<Package>> modsToInclude = new HashMap<EBSLInstallType, Vector<Package>>();
359 modsToInclude.put(EBSLInstallType.NORMAL, new Vector<Package>());
360 modsToInclude.put(EBSLInstallType.ADDON, new Vector<Package>());
361
362 for (Package m : mods.descendingSet()) {
363 File bsl = CaseInsensitiveFile.getCaseInsensitiveFile(
364 m.getLocalPath(), "bsl");
365 if (bsl.exists()) {
366 if (m.hasSeparatePlatformDirs()) {
367 File bslCommon = CaseInsensitiveFile
368 .getCaseInsensitiveFile(bsl, "common");
369 File bslMac = CaseInsensitiveFile.getCaseInsensitiveFile(
370 bsl, "mac_only");
371 File bslWin = CaseInsensitiveFile.getCaseInsensitiveFile(
372 bsl, "win_only");
373 if ((PlatformInformation.getPlatform() == Platform.MACOS && bslMac
374 .exists())
375 || ((PlatformInformation.getPlatform() == Platform.WIN || PlatformInformation
376 .getPlatform() == Platform.LINUX) && bslWin
377 .exists()) || bslCommon.exists()) {
378 modsToInclude.get(m.getBSLInstallType()).add(m);
379 }
380 } else {
381 modsToInclude.get(m.getBSLInstallType()).add(m);
382 }
383 }
384 }
385
386 for (Package m : modsToInclude.get(EBSLInstallType.NORMAL)) {
387 copyBSL(m, false);
388 }
389 Vector<Package> addons = modsToInclude.get(EBSLInstallType.ADDON);
390 for (int i = addons.size() - 1; i >= 0; i--) {
391 copyBSL(addons.get(i), true);
392 }
393 }
394
395 private static void copyBSL(Package sourceMod, boolean addon) {
396 File targetBaseFolder = new File(Paths.getEditionGDF(), "IGMD");
397 if (!targetBaseFolder.exists())
398 targetBaseFolder.mkdir();
399
400 Vector<File> sources = new Vector<File>();
401 File bsl = CaseInsensitiveFile.getCaseInsensitiveFile(
402 sourceMod.getLocalPath(), "bsl");
403 if (sourceMod.hasSeparatePlatformDirs()) {
404 File bslCommon = CaseInsensitiveFile.getCaseInsensitiveFile(bsl,
405 "common");
406 File bslMac = CaseInsensitiveFile.getCaseInsensitiveFile(bsl,
407 "mac_only");
408 File bslWin = CaseInsensitiveFile.getCaseInsensitiveFile(bsl,
409 "win_only");
410 if (PlatformInformation.getPlatform() == Platform.MACOS
411 && bslMac.exists()) {
412 for (File f : bslMac.listFiles(dirFileFilter)) {
413 File targetBSL = new File(targetBaseFolder, f.getName());
414 if (addon || !targetBSL.exists())
415 sources.add(f);
416 }
417 }
418 if ((PlatformInformation.getPlatform() == Platform.WIN || PlatformInformation
419 .getPlatform() == Platform.LINUX) && bslWin.exists()) {
420 for (File f : bslWin.listFiles(dirFileFilter)) {
421 File targetBSL = new File(targetBaseFolder, f.getName());
422 if (addon || !targetBSL.exists())
423 sources.add(f);
424 }
425 }
426 if (bslCommon.exists()) {
427 for (File f : bslCommon.listFiles(dirFileFilter)) {
428 File targetBSL = new File(targetBaseFolder, f.getName());
429 if (addon || !targetBSL.exists())
430 sources.add(f);
431 }
432 }
433 } else {
434 for (File f : bsl.listFiles(dirFileFilter)) {
435 File targetBSL = new File(targetBaseFolder, f.getName());
436 if (addon || !targetBSL.exists())
437 sources.add(f);
438 }
439 }
440
441 System.out.println("For mod: " + sourceMod.getName()
442 + " install BSL folders: " + sources.toString());
443 for (File f : sources) {
444 File targetPath = new File(targetBaseFolder, f.getName());
445 if (!targetPath.exists())
446 targetPath.mkdir();
447 if (!(CaseInsensitiveFile.getCaseInsensitiveFile(targetPath,
448 "ignore.txt").exists())) {
449 for (File fbsl : f.listFiles()) {
450 if (fbsl.getName().toLowerCase().endsWith(".bsl")) {
451 File targetFile = new File(targetPath, fbsl.getName());
452 if (addon || !targetFile.exists()) {
453 try {
454 FileUtils.copyFile(fbsl, targetFile);
455 } catch (IOException e) {
456 e.printStackTrace();
457 }
458 }
459 }
460 }
461 }
462 }
463 }
464
465 private static void applyPatches(
466 TreeMap<String, Vector<File>> oniLevelFolders,
467 List<File> patchFolders, InstallProgressListener listener,
468 PrintWriter log) {
469 log.println();
470 log.println("Applying XML patches");
471 listener.installProgressUpdate(0, 1, "Applying XML patches");
472
473 long startMS = new Date().getTime();
474
475 String tmpFolderName = "installrun_temp-"
476 + new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss")
477 .format(new Date());
478 File tmpFolder = new File(Paths.getTempPath(), tmpFolderName);
479 tmpFolder.mkdir();
480
481 TreeMap<String, Vector<File>> patches = new TreeMap<String, Vector<File>>(new NaturalOrderComparator());
482 for (File patchFolder : patchFolders) {
483 for (File levelFolder : patchFolder.listFiles(dirFileFilter)) {
484 String lvlName = levelFolder.getName().toLowerCase();
485 for (File f : FileUtils.listFiles(levelFolder,
486 new String[] { "oni-patch" }, true)) {
487 if (!patches.containsKey(lvlName))
488 patches.put(lvlName, new Vector<File>());
489 patches.get(lvlName).add(f);
490 }
491 }
492 }
493
494 for (String level : patches.keySet()) {
495 File levelFolder = new File(tmpFolder, level);
496 levelFolder.mkdir();
497
498 log.println("\t\tPatches for " + level);
499
500 Vector<String> exportPatterns = new Vector<String>();
501 // Get files to be patched from vanilla.dat
502 for (File patch : patches.get(level)) {
503 String patternWildcard = patch.getName();
504 patternWildcard = patternWildcard.substring(0,
505 patternWildcard.indexOf(".oni-patch"));
506 patternWildcard = patternWildcard.replace('-', '*');
507 exportPatterns.add(patternWildcard);
508 }
509 for (File srcFolder : oniLevelFolders.get(level)) {
510 if (srcFolder.isFile()) {
511 if (srcFolder.getPath().toLowerCase().contains("vanilla")) {
512 // Extract from .dat
513 ApplicationInvocationResult res = OniSplit.export(
514 levelFolder, srcFolder, exportPatterns);
515 logAppOutput(res, log);
516 }
517 }
518 }
519
520 // Get files to be patched from packages
521 for (File patch : patches.get(level)) {
522 String patternWildcard = patch.getName();
523 patternWildcard = patternWildcard.substring(0,
524 patternWildcard.indexOf(".oni-patch"));
525 patternWildcard = patternWildcard.replace('-', '*');
526 patternWildcard = patternWildcard + ".oni";
527 Vector<String> patterns = new Vector<String>();
528 patterns.add(patternWildcard);
529 final Pattern patternRegex = Pattern.compile(
530 patternWildcard.replaceAll("\\*", ".\\*"),
531 Pattern.CASE_INSENSITIVE);
532
533 for (File srcFolder : oniLevelFolders.get(level)) {
534 if (srcFolder.isFile()) {
535 if (!srcFolder.getPath().toLowerCase()
536 .contains("vanilla")) {
537 // Extract from .dat
538 ApplicationInvocationResult res = OniSplit.export(
539 levelFolder, srcFolder, patterns);
540 logAppOutput(res, log);
541 }
542 } else {
543 // Copy from folder with overwrite
544 for (File f : FileUtils.listFiles(srcFolder,
545 new RegexFileFilter(patternRegex),
546 TrueFileFilter.TRUE)) {
547 try {
548 FileUtils.copyFileToDirectory(f, levelFolder);
549 } catch (IOException e) {
550 e.printStackTrace();
551 }
552 }
553 }
554 }
555 }
556
557 // Extract files to XML
558 File levelFolderXML = new File(levelFolder, "xml");
559 Vector<File> files = new Vector<File>();
560 files.add(new File(levelFolder, "*.oni"));
561 ApplicationInvocationResult res = OniSplit.convertOniToXML(
562 levelFolderXML, files);
563 logAppOutput(res, log);
564
565 // Apply patches in levelFolderXML
566 for (File patch : patches.get(level)) {
567 String patternWildcard = patch.getName();
568 patternWildcard = patternWildcard.substring(0,
569 patternWildcard.indexOf(".oni-patch"));
570 patternWildcard = patternWildcard + ".xml";
571 patternWildcard = patternWildcard.replace('-', '*');
572
573 res = XMLTools.patch(patch, new File(levelFolderXML,
574 patternWildcard));
575 logAppOutput(res, log);
576 }
577
578 // Create .oni files from XML
579 files.clear();
580 files.add(new File(levelFolderXML, "*.xml"));
581 res = OniSplit.convertXMLtoOni(levelFolder, files);
582 logAppOutput(res, log);
583
584 // Remove XML folder as import will only require .oni's
585 // try {
586 // FileUtils.deleteDirectory(levelFolderXML);
587 // } catch (IOException e) {
588 // e.printStackTrace();
589 // }
590
591 oniLevelFolders.get(level).add(levelFolder);
592 }
593
594 log.println("Applying XML patches took "
595 + (new Date().getTime() - startMS) + " ms");
596 }
597
598 private static void combineBinaryFiles(
599 TreeMap<String, Vector<File>> oniLevelFolders,
600 InstallProgressListener listener, PrintWriter log) {
601 long startMS = new Date().getTime();
602
603 int totalSteps = oniLevelFolders.size() + 1;
604 int stepsDone = 0;
605
606 log.println();
607 log.println("Importing levels");
608 for (String l : oniLevelFolders.keySet()) {
609 log.println("\tLevel " + l);
610 listener.installProgressUpdate(stepsDone, totalSteps,
611 "Installing level " + l);
612
613 ApplicationInvocationResult res = OniSplit.packLevel(
614 oniLevelFolders.get(l), new File(Paths.getEditionGDF(),
615 sanitizeLevelName(l) + ".dat"));
616 logAppOutput(res, log);
617
618 stepsDone++;
619 }
620
621 log.println("Importing levels took " + (new Date().getTime() - startMS)
622 + " ms");
623 log.println();
624 }
625
626 private static void copyVideos(PrintWriter log) {
627 if (SettingsManager.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 (SettingsManager.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 TreeSet<File> levelFiles = new TreeSet<File>(
690 new NaturalOrderComparator());
691
692 for (File f : Paths.getVanillaGDF().listFiles(new FilenameFilter() {
693 @Override
694 public boolean accept(File dir, String name) {
695 return name.endsWith(".dat");
696 }
697 })) {
698 totalSteps++;
699 levelFiles.add(f);
700 }
701 totalSteps = totalSteps * 2 + 2;
702
703 try {
704 File logFile = new File(Paths.getInstallerPath(),
705 "Initialization.log");
706 PrintWriter log = new PrintWriter(logFile);
707
708 Date start = new Date();
709 log.println("Initialization of Edition core started at "
710 + sdf.format(start));
711 log.println("Cleaning directories");
712
713 listener.installProgressUpdate(stepsDone, totalSteps,
714 "Cleaning up directories");
715 createEmptyPath(Paths.getVanillaOnisPath());
716 createEmptyPath(init);
717 File level0Folder = new File(init, "level0_Final");
718 createEmptyPath(level0Folder);
719
720 stepsDone++;
721
722 log.println("Exporting levels and moving files to level0");
723
724 for (File f : levelFiles) {
725 String levelName = f.getName().substring(0,
726 f.getName().indexOf('.'));
727 Scanner fi = new Scanner(levelName);
728 int levelNumber = Integer.parseInt(fi.findInLine("[0-9]+"));
729
730 log.println("\t" + levelName + ":");
731 log.println("\t\tExporting");
732 listener.installProgressUpdate(stepsDone, totalSteps,
733 "Exporting vanilla level " + levelNumber);
734
735 // Edition/GameDataFolder/level*_Final/
736 File tempLevelFolder = new File(init, levelName);
737
738 // Export Vanilla-Level-Dat -> Temp/Level
739 ApplicationInvocationResult res = OniSplit.export(
740 tempLevelFolder, f);
741 logAppOutput(res, log);
742
743 log.println("\t\tMoving files");
744 handleFileGlobalisation(tempLevelFolder, level0Folder,
745 levelNumber);
746 stepsDone++;
747 log.println();
748 }
749
750 log.println("Reimporting levels");
751 TreeSet<File> initFolders = new TreeSet<File>(new NaturalOrderComparator());
752 for (File f : init.listFiles()) {
753 initFolders.add(f);
754 }
755
756 for (File f : initFolders) {
757 String levelName = f.getName();
758
759 log.println("\t" + levelName);
760 listener.installProgressUpdate(stepsDone, totalSteps,
761 "Creating globalized " + levelName);
762
763 Vector<File> folders = new Vector<File>();
764 folders.add(f);
765
766 ApplicationInvocationResult res = OniSplit
767 .importLevel(folders,
768 new File(Paths.getVanillaOnisPath(), levelName
769 + ".dat"));
770 logAppOutput(res, log);
771
772 log.println();
773 stepsDone++;
774 }
775
776 listener.installProgressUpdate(stepsDone, totalSteps,
777 "Copying basic files");
778 // Copy Oni-configs
779 File persistVanilla = new File(Paths.getOniBasePath(),
780 "persist.dat");
781 File persistEdition = new File(Paths.getEditionBasePath(),
782 "persist.dat");
783 File keyConfVanilla = new File(Paths.getOniBasePath(),
784 "key_config.txt");
785 File keyConfEdition = new File(Paths.getEditionBasePath(),
786 "key_config.txt");
787 if (persistVanilla.exists() && !persistEdition.exists())
788 FileUtils.copyFile(persistVanilla, persistEdition);
789 if (keyConfVanilla.exists() && !keyConfEdition.exists())
790 FileUtils.copyFile(keyConfVanilla, keyConfEdition);
791
792 FileUtils.deleteDirectory(init);
793
794 Date end = new Date();
795 log.println("Initialization ended at " + sdf.format(end));
796 log.println("Process took "
797 + ((end.getTime() - start.getTime()) / 1000) + " seconds");
798 log.close();
799 } catch (IOException e) {
800 e.printStackTrace();
801 }
802 }
803
804 private static void moveFileToTargetOrDelete(File source, File target) {
805 if (source.equals(target))
806 return;
807 if (!target.exists()) {
808 if (!source.renameTo(target)) {
809 System.err.println("File " + source.getPath() + " not moved!");
810 }
811 } else if (!source.delete()) {
812 System.err.println("File " + source.getPath() + " not deleted!");
813 }
814 }
815
816 private static void handleFileGlobalisation(File tempFolder,
817 File level0Folder, int levelNumber) {
818 // Move AKEV and related files to subfolder so they're not globalized:
819 if (levelNumber != 0) {
820 File akevFolder = new File(tempFolder, "AKEV");
821 akevFolder.mkdir();
822 OniSplit.move(akevFolder, tempFolder.getPath() + "/AKEV*.oni",
823 "overwrite");
824 }
825
826 for (File f : tempFolder.listFiles(new FileFilter() {
827 @Override
828 public boolean accept(File pathname) {
829 return pathname.isFile();
830 }
831 })) {
832 // Move matching files to subfolder NoGlobal:
833 if (f.getName().startsWith("TXMPfail")
834 || f.getName().startsWith("TXMPlevel")
835 || (f.getName().startsWith("TXMP") && f.getName().contains(
836 "intro"))
837 || f.getName().startsWith("TXMB")
838 || f.getName().equals("M3GMpowerup_lsi.oni")
839 || f.getName().equals("TXMPlsi_icon.oni")
840 || (f.getName().startsWith("TXMB") && f.getName().contains(
841 "splash_screen.oni"))) {
842 File noGlobal = new File(tempFolder, "NoGlobal");
843 noGlobal.mkdir();
844 File noGlobalFile = new File(noGlobal, f.getName());
845 moveFileToTargetOrDelete(f, noGlobalFile);
846 }
847 // Move matching files to level0_Animations/level0_TRAC
848 else if (f.getName().startsWith("TRAC")) {
849 File level0File = new File(level0Folder, f.getName());
850 moveFileToTargetOrDelete(f, level0File);
851 }
852 // Move matching files to level0_Animations/level0_TRAM
853 else if (f.getName().startsWith("TRAM")) {
854 File level0File = new File(level0Folder, f.getName());
855 moveFileToTargetOrDelete(f, level0File);
856 }
857 // Move matching files to level0_Textures
858 else if (f.getName().startsWith("ONSK")
859 || f.getName().startsWith("TXMP")) {
860 File level0File = new File(level0Folder, f.getName());
861 moveFileToTargetOrDelete(f, level0File);
862 }
863 // Move matching files to *VANILLA*/level0_Characters
864 else if (f.getName().startsWith("ONCC")
865 || f.getName().startsWith("TRBS")
866 || f.getName().startsWith("ONCV")
867 || f.getName().startsWith("ONVL")
868 || f.getName().startsWith("TRMA")
869 || f.getName().startsWith("TRSC")
870 || f.getName().startsWith("TRAS")) {
871 File level0File = new File(level0Folder, f.getName());
872 moveFileToTargetOrDelete(f, level0File);
873 }
874 // Move matching files to level0_Sounds
875 else if (f.getName().startsWith("OSBD")
876 || f.getName().startsWith("SNDD")) {
877 File level0File = new File(level0Folder, f.getName());
878 moveFileToTargetOrDelete(f, level0File);
879 }
880 // Move matching files to level0_Particles
881 else if (f.getName().startsWith("BINA3")
882 || f.getName().startsWith("M3GMdebris")
883 || f.getName().equals("M3GMtoxic_bubble.oni")
884 || f.getName().startsWith("M3GMelec")
885 || f.getName().startsWith("M3GMrat")
886 || f.getName().startsWith("M3GMjet")
887 || f.getName().startsWith("M3GMbomb_")
888 || f.getName().equals("M3GMbarab_swave.oni")
889 || f.getName().equals("M3GMbloodyfoot.oni")) {
890 File level0File = new File(level0Folder, f.getName());
891 moveFileToTargetOrDelete(f, level0File);
892 }
893 // Move matching files to Archive (aka delete them)
894 else if (f.getName().startsWith("AGDB")
895 || f.getName().startsWith("TRCM")) {
896 f.delete();
897 }
898 // Move matching files to /level0_Final/
899 else if (f.getName().startsWith("ONWC")) {
900 File level0File = new File(level0Folder, f.getName());
901 moveFileToTargetOrDelete(f, level0File);
902 }
903 }
904 }
905
906 private static String sanitizeLevelName(String ln) {
907 int ind = ln.indexOf("_");
908 String res = ln.substring(0, ind + 1);
909 res += ln.substring(ind + 1, ind + 2).toUpperCase();
910 res += ln.substring(ind + 2);
911 return res;
912 }
913
914 /**
915 * Verify that the Edition is within a subfolder to vanilla Oni
916 * (..../Oni/Edition/AEInstaller)
917 *
918 * @return true if GDF can be found in the parent's parent-path
919 */
920 public static boolean verifyRunningDirectory() {
921 return Paths.getVanillaGDF().exists()
922 && Paths.getVanillaGDF().isDirectory();
923 }
924
925 private static void logAppOutput(ApplicationInvocationResult result,
926 PrintWriter log) {
927 if (result != null) {
928 log.println("\t\t\tCalled:");
929 for (String s : result.cmdLine)
930 log.println("\t\t\t\t" + s);
931 log.println("\t\t\tReturned: " + result.errorCode);
932 for (String s : result.output)
933 log.println("\t\t\t\t" + s);
934 log.println("\t\t\tDuration: " + result.time + " ms");
935 log.println();
936 }
937 }
938}
Note: See TracBrowser for help on using the repository browser.