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

wurstscript / WurstScript / 251

23 Feb 2025 05:04PM UTC coverage: 62.277% (-0.002%) from 62.279%
251

push

circleci

Frotty
New binaries by @Cokemonkey11

17278 of 27744 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
        if (map.isPresent()) {
×
102
            mapLastModified = map.get().lastModified();
×
103
            mapPath = map.get().getAbsolutePath();
×
104
        }
105
        Optional<File> testMap = map.map($ -> new File(buildDir, "WurstRunMap.w3x"));
×
106
        CompilationResult result = compileScript(modelManager, gui, testMap, projectConfig, buildDir, false);
×
107

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

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

118

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

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

128
        File mapCopy = copyToWarcraftMapDir(testMap.get());
×
129

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

139

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

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

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

176

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

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

189
        Path customMapDataPath = getCustomMapDataPath();
×
190

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

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

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

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

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

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

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

275
            }
276

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

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

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

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

316

317
}
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