• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

wurstscript / WurstScript / 249

03 Mar 2024 01:51PM UTC coverage: 62.279% (-0.03%) from 62.309%
249

push

circleci

Frotty
fix map script caching

17278 of 27743 relevant lines covered (62.28%)

0.62 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/requests/RunMap.java
1
package de.peeeq.wurstio.languageserver.requests;
2

3
import com.google.common.collect.Lists;
4
import com.google.common.io.Files;
5
import config.WurstProjectConfig;
6
import config.WurstProjectConfigData;
7
import de.peeeq.wurstio.gui.WurstGuiImpl;
8
import de.peeeq.wurstio.languageserver.ModelManager;
9
import de.peeeq.wurstio.languageserver.WFile;
10
import de.peeeq.wurstio.languageserver.WurstLanguageServer;
11
import de.peeeq.wurstscript.WLogger;
12
import de.peeeq.wurstscript.attributes.CompileError;
13
import de.peeeq.wurstscript.gui.WurstGui;
14
import de.peeeq.wurstscript.utils.Utils;
15
import net.moonlightflower.wc3libs.port.GameVersion;
16
import net.moonlightflower.wc3libs.port.Orient;
17
import org.apache.commons.lang.RandomStringUtils;
18
import org.apache.commons.lang.StringUtils;
19
import org.eclipse.lsp4j.MessageType;
20
import org.jetbrains.annotations.NotNull;
21
import org.jetbrains.annotations.Nullable;
22

23
import javax.swing.*;
24
import javax.swing.filechooser.FileSystemView;
25
import java.io.File;
26
import java.io.FileNotFoundException;
27
import java.io.IOException;
28
import java.nio.file.Path;
29
import java.nio.file.Paths;
30
import java.time.Duration;
31
import java.util.Arrays;
32
import java.util.List;
33
import java.util.Optional;
34

35
import static de.peeeq.wurstio.languageserver.ProjectConfigBuilder.FILE_NAME;
36
import static net.moonlightflower.wc3libs.port.GameVersion.VERSION_1_31;
37
import static net.moonlightflower.wc3libs.port.GameVersion.VERSION_1_32;
38

39
/**
40
 * Created by peter on 16.05.16.
41
 */
42
public class RunMap extends MapRequest {
43

44
    private @Nullable File customTarget = null;
×
45

46

47
    public RunMap(WurstLanguageServer langServer, WFile workspaceRoot, Optional<String> wc3Path, Optional<File> map,
48
                  List<String> compileArgs) {
49
        super(langServer, map, compileArgs, workspaceRoot, wc3Path);
×
50
        safeCompilation = SafetyLevel.QuickAndDirty;
×
51
    }
×
52

53
    @Override
54
    public Object execute(ModelManager modelManager) throws IOException {
55
        WLogger.info("Execute RunMap, \nwc3Path =" + wc3Path
×
56
            + ",\n map = " + map
57
            + ",\n compileArgs = " + compileArgs
58
            + ",\n workspaceRoot = " + workspaceRoot
59
            + ",\n runArgs = " + compileArgs
60
        );
61

62
        if (modelManager.hasErrors()) {
×
63
            throw new RequestFailedException(MessageType.Error, "Fix errors in your code before running.\n" + modelManager.getFirstErrorDescription());
×
64
        }
65

66
        WurstProjectConfigData projectConfig = WurstProjectConfig.INSTANCE.loadProject(workspaceRoot.getFile().toPath().resolve(FILE_NAME));
×
67
        if (projectConfig == null) {
×
68
            throw new RequestFailedException(MessageType.Error, FILE_NAME + " file doesn't exist or is invalid. " +
×
69
                "Please install your project using grill or the wurst setup tool.");
70
        }
71

72
        // TODO use normal compiler for this, avoid code duplication
73
        WurstGui gui = new WurstGuiImpl(getWorkspaceAbsolute());
×
74
        try {
75
            String ok = compileMap(modelManager, gui, projectConfig);
×
76
            if (ok != null) return ok;
×
77
        } catch (CompileError e) {
×
78
            WLogger.info(e);
×
79
            throw new RequestFailedException(MessageType.Error, "A compilation error occurred when running the map:\n" + e);
×
80
        } catch (Exception e) {
×
81
            WLogger.warning("Exception occurred", e);
×
82
            throw new RequestFailedException(MessageType.Error, "An exception was thrown when running the map:\n" + e);
×
83
        } finally {
84
            if (gui.getErrorCount() == 0) {
×
85
                gui.sendFinished();
×
86
            }
87
        }
88
        return "ok"; // TODO
×
89
    }
90

91
    @Nullable
92
    private String compileMap(ModelManager modelManager, WurstGui gui, WurstProjectConfigData projectConfig) throws Exception {
93
        if (map.isPresent() && !map.get().exists()) {
×
94
            throw new RequestFailedException(MessageType.Error, map.get().getAbsolutePath() + " does not exist.");
×
95
        }
96

97
        gui.sendProgress("Copying map");
×
98

99
        // first we copy in same location to ensure validity
100
        File buildDir = getBuildDir();
×
101
        mapLastModified = map.get().lastModified();
×
102
        mapPath = map.get().getAbsolutePath();
×
103
        Optional<File> testMap = map.map($ -> new File(buildDir, "WurstRunMap.w3x"));
×
104
        CompilationResult result = compileScript(modelManager, gui, testMap, projectConfig, buildDir, false);
×
105

106
        if (runArgs.isHotReload()) {
×
107
            // call jhcr update
108
            gui.sendProgress("Calling JHCR update");
×
109
            callJhcrUpdate(result.script);
×
110

111
            // if we are just reloading the mapscript with JHCR, we are done here
112
            gui.sendProgress("update complete");
×
113
            return "ok";
×
114
        }
115

116

117
        if (testMap.isPresent()) {
×
118
            startGame(gui, testMap, result);
×
119
        }
120
        return null;
×
121
    }
122

123
    private void startGame(WurstGui gui, Optional<File> testMap, CompilationResult result) throws Exception {
124
        injectMapData(gui, testMap, result);
×
125

126
        File mapCopy = copyToWarcraftMapDir(testMap.get());
×
127

128
        gui.sendProgress("Starting Warcraft 3...");
×
129
        WLogger.info("Starting wc3 ... ");
×
130
        String path = "";
×
131
        if (customTarget != null) {
×
132
            path = new File(customTarget, testMap.get().getName()).getAbsolutePath();
×
133
        } else if (mapCopy != null) {
×
134
            path = mapCopy.getAbsolutePath();
×
135
        }
136

137

138
        if (!path.isEmpty()) {
×
139
            // now start the map
140
            File gameExe = w3data.getGameExe().get();
×
141
            if (!w3data.getWc3PatchVersion().isPresent()) {
×
142
                throw new RequestFailedException(MessageType.Error, wc3Path + " does not exist.");
×
143
            }
144
            List<String> cmd = Lists.newArrayList(gameExe.getAbsolutePath());
×
145
            Optional<String> wc3RunArgs = langServer.getConfigProvider().getWc3RunArgs();
×
146
            if (!wc3RunArgs.isPresent() || StringUtils.isBlank(wc3RunArgs.get())) {
×
147
                if (w3data.getWc3PatchVersion().get().compareTo(VERSION_1_32) >= 0) {
×
148
                    cmd.add("-launch");
×
149
                }
150
                if (w3data.getWc3PatchVersion().get().compareTo(VERSION_1_31) < 0) {
×
151
                    cmd.add("-window");
×
152
                } else {
153
                    cmd.add("-windowmode");
×
154
                    cmd.add("windowed");
×
155
                }
156
            } else {
157
                cmd.addAll(Arrays.asList(wc3RunArgs.get().split("\\s+")));
×
158
            }
159
            cmd.add("-loadfile");
×
160
            cmd.add(path);
×
161

162
            if (Orient.isLinuxSystem()) {
×
163
                // run with wine
164
                cmd.add(0, "wine");
×
165
            }
166

167
            gui.sendProgress("running " + cmd);
×
168
            Runtime.getRuntime().exec(cmd.toArray(new String[0]));
×
169
            timeTaker.endPhase();
×
170
            timeTaker.printReport();
×
171
        }
172
    }
×
173

174

175
    private void callJhcrUpdate(File mapScript) throws IOException, InterruptedException {
176
        File mapScriptFolder = mapScript.getParentFile();
×
177
        File commonJ = new File(mapScriptFolder, "common.j");
×
178
        File blizzardJ = new File(mapScriptFolder, "blizzard.j");
×
179
        if (!commonJ.exists()) {
×
180
            throw new IOException("Could not find file " + commonJ.getAbsolutePath());
×
181
        }
182

183
        if (!blizzardJ.exists()) {
×
184
            throw new IOException("Could not find file " + blizzardJ.getAbsolutePath());
×
185
        }
186

187
        Path customMapDataPath = getCustomMapDataPath();
×
188

189
        ProcessBuilder pb = new ProcessBuilder(langServer.getConfigProvider().getJhcrExe(), "update", mapScript.getName(), "--asm",
×
190
            "--preload-path", customMapDataPath.toAbsolutePath().toString());
×
191
        pb.directory(mapScriptFolder);
×
192
        Utils.ExecResult $ = Utils.exec(pb, Duration.ofSeconds(30), System.err::println);
×
193
    }
×
194

195
    /**
196
     * Tries to find the path where the wc3 CustomMapData is stored.
197
     * For example this could be in:
198
     * C:\\Users\\Peter\\Documents\\Warcraft III\\CustomMapData
199
     */
200
    private Path getCustomMapDataPath() {
201
        String customMapDataPath = langServer.getConfigProvider().getConfig("customMapDataPath", "");
×
202
        if (!customMapDataPath.isEmpty()) {
×
203
            return Paths.get(customMapDataPath);
×
204
        }
205

206
        Path documents;
207
        try {
208
            documents = FileSystemView.getFileSystemView().getDefaultDirectory().toPath();
×
209
        } catch (Throwable t) {
×
210
            WLogger.info(t);
×
211
            Path homeFolder = Paths.get(System.getProperty("user.home"));
×
212
            documents = homeFolder.resolve("Documents");
×
213
        }
×
214
        return documents.resolve(Paths.get("Warcraft III", "CustomMapData"));
×
215
    }
216

217
    @NotNull
218
    private String getWorkspaceAbsolute() {
219
        try {
220
            return workspaceRoot.getFile().getAbsolutePath();
×
221
        } catch (FileNotFoundException e) {
×
222
            throw new RequestFailedException(MessageType.Error, "Could not open workspace root: ", e);
×
223
        }
224
    }
225

226
    /**
227
     * Copies the map to the wc3 map directory
228
     * <p>
229
     * This directory depends on warcraft version and whether we are on windows or wine is used.
230
     */
231
    private File copyToWarcraftMapDir(File testMap) throws IOException {
232
        String testMapName = "WurstTestMap.w3x";
×
233
        for (String arg : compileArgs) {
×
234
            if (arg.startsWith("-runmapTarget")) {
×
235
                String path = arg.substring(arg.indexOf(" ") + 1);
×
236
                // copy the map to the specified directory
237
                customTarget = new File(path);
×
238
                if (customTarget.exists() && customTarget.isDirectory()) {
×
239
                    File testMap2 = new File(customTarget, testMapName);
×
240
                    Files.copy(testMap, testMap2);
×
241
                    return testMap2;
×
242
                } else {
243
                    WLogger.severe("Directory specified via -runmapTarget does not exists or is not a directory");
×
244
                }
245
            }
246
        }
×
247

248
        File myDocumentsFolder = FileSystemView.getFileSystemView().getDefaultDirectory();
×
249
        Optional<String> documentPath = findMapDocumentPath(testMapName, myDocumentsFolder);
×
250

251
        // copy the map to the appropriate directory
252
        Optional<File> testFolder = documentPath.map(path -> new File(path, "Maps" + File.separator + "Test"));
×
253
        if (testFolder.isPresent() && (testFolder.get().mkdirs() || testFolder.get().exists())) {
×
254
            File testMap2 = new File(testFolder.get(), testMapName);
×
255
            while (true) {
256
                try {
257
                    Files.copy(testMap, testMap2);
×
258
                    break;
×
259
                } catch (IOException ex) {
×
260
                    JFrame jf = new JFrame();
×
261
                    jf.setAlwaysOnTop(true);
×
262
                    Object[] options = { "Retry", "Rename", "Cancel" };
×
263
                    int result = JOptionPane.showOptionDialog(jf, "Can't write to target map file, it's probably in use.",
×
264
                        "Run Map", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
265
                        null, options, null);
266
                    if (result == JOptionPane.CANCEL_OPTION) {
×
267
                        return null;
×
268
                    } else if(result == JOptionPane.NO_OPTION) {
×
269
                        testMap2 = new File(testFolder.get(), testMapName + RandomStringUtils.randomNumeric(3));
×
270
                    }
271
                }
×
272

273
            }
274

275
            return testMap2;
×
276
        } else {
277
            WLogger.severe("Could not create Test folder");
×
278
        }
279
        return null;
×
280
    }
281

282
    private Optional<String> findMapDocumentPath(String testMapName, File myDocumentsFolder) {
283
        Optional<String> documentPath = Optional.of(
×
284
            langServer.getConfigProvider().getMapDocumentPath().orElseGet(
×
285
                () -> myDocumentsFolder.getAbsolutePath() + File.separator + "Warcraft III"));
×
286

287
        if (!new File(documentPath.get()).exists()) {
×
288
            WLogger.info("Warcraft folder " + documentPath + " does not exist.");
×
289
            // Try wine default:
290
            documentPath = Optional.of(System.getProperty("user.home")
×
291
                + "/.wine/drive_c/users/" + System.getProperty("user.name") + "/My Documents/Warcraft III");
×
292
            if (!new File(documentPath.get()).exists()) {
×
293
                WLogger.severe("Severe: Wine Warcraft folder " + documentPath + " does not exist.");
×
294
            }
295
        }
296

297
        if (w3data.getWc3PatchVersion().get().compareTo(new GameVersion("1.27.9")) <= 0) {
×
298
            // 1.27 and lower compat
299
            WLogger.info("Version 1.27 or lower detected, changing file location");
×
300
            documentPath = wc3Path;
×
301
        } else {
302
            // For 1.28+ the wc3/maps/test folder must not contain a map of the same name
303
            Optional<File> oldFile = wc3Path.map(
×
304
                w3p -> new File(w3p, "Maps" + File.separator + "Test" + File.separator + testMapName));
×
305
            if (oldFile.isPresent() && oldFile.get().exists()) {
×
306
                if (!oldFile.get().delete()) {
×
307
                    WLogger.severe("Cannot delete old Wurst Test Map");
×
308
                }
309
            }
310
        }
311
        return documentPath;
×
312
    }
313

314

315
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc