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

wurstscript / WurstScript / 228

29 Nov 2023 05:00PM UTC coverage: 62.48% (-0.09%) from 62.574%
228

push

circleci

web-flow
Show dialog for choosing game path, cleanup (#1083)

* show dialog for choosing game path

* cleanup code

* remove logs and refactor

* remove confusing mpq error, make some mpq loads readonly

17295 of 27681 relevant lines covered (62.48%)

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
        WLogger.info("received runMap command: map=" + map + ", wc3dir=" + wc3Path + ", args=" + compileArgs);
×
74
        WurstGui gui = new WurstGuiImpl(getWorkspaceAbsolute());
×
75
        try {
76
            if (map.isPresent() && !map.get().exists()) {
×
77
                throw new RequestFailedException(MessageType.Error, map.get().getAbsolutePath() + " does not exist.");
×
78
            }
79

80
            gui.sendProgress("Copying map");
×
81

82
            // first we copy in same location to ensure validity
83
            File buildDir = getBuildDir();
×
84
            Optional<File> testMap = map.map($ -> new File(buildDir, "WurstRunMap.w3x"));
×
85
            CompilationResult result = compileScript(modelManager, gui, testMap, projectConfig, buildDir, false);
×
86

87
            if (runArgs.isHotReload()) {
×
88
                // call jhcr update
89
                gui.sendProgress("Calling JHCR update");
×
90
                callJhcrUpdate(result.script);
×
91

92
                // if we are just reloading the mapscript with JHCR, we are done here
93
                gui.sendProgress("update complete");
×
94
                return "ok";
×
95
            }
96

97

98
            if (testMap.isPresent()) {
×
99

100
                injectMapData(gui, testMap, result);
×
101

102
                File mapCopy = copyToWarcraftMapDir(testMap.get());
×
103

104
                gui.sendProgress("Starting Warcraft 3...");
×
105
                WLogger.info("Starting wc3 ... ");
×
106
                String path = "";
×
107
                if (customTarget != null) {
×
108
                    path = new File(customTarget, testMap.get().getName()).getAbsolutePath();
×
109
                } else if (mapCopy != null) {
×
110
                    path = mapCopy.getAbsolutePath();
×
111
                }
112

113

114
                if (!path.isEmpty()) {
×
115
                    // now start the map
116
                    File gameExe = w3data.getGameExe().get();
×
117
                    if (!w3data.getWc3PatchVersion().isPresent()) {
×
118
                        throw new RequestFailedException(MessageType.Error, wc3Path + " does not exist.");
×
119
                    }
120
                    List<String> cmd = Lists.newArrayList(gameExe.getAbsolutePath());
×
121
                    Optional<String> wc3RunArgs = langServer.getConfigProvider().getWc3RunArgs();
×
122
                    if (!wc3RunArgs.isPresent() || StringUtils.isBlank(wc3RunArgs.get())) {
×
123
                        if (w3data.getWc3PatchVersion().get().compareTo(VERSION_1_32) >= 0) {
×
124
                            cmd.add("-launch");
×
125
                        }
126
                            if (w3data.getWc3PatchVersion().get().compareTo(VERSION_1_31) < 0) {
×
127
                                cmd.add("-window");
×
128
                            } else {
129
                                cmd.add("-windowmode");
×
130
                                cmd.add("windowed");
×
131
                            }
132
                    } else {
133
                            cmd.addAll(Arrays.asList(wc3RunArgs.get().split("\\s+")));
×
134
                    }
135
                    cmd.add("-loadfile");
×
136
                    cmd.add(path);
×
137

138
                    if (Orient.isLinuxSystem()) {
×
139
                        // run with wine
140
                        cmd.add(0, "wine");
×
141
                    }
142

143
                    gui.sendProgress("running " + cmd);
×
144
                    Runtime.getRuntime().exec(cmd.toArray(new String[0]));
×
145
                    timeTaker.endPhase();
×
146
                    timeTaker.printReport();
×
147
                }
148
            }
149
        } catch (CompileError e) {
×
150
            WLogger.info(e);
×
151
            throw new RequestFailedException(MessageType.Error, "A compilation error occurred when running the map:\n" + e);
×
152
        } catch (Exception e) {
×
153
            WLogger.warning("Exception occurred", e);
×
154
            throw new RequestFailedException(MessageType.Error, "An exception was thrown when running the map:\n" + e);
×
155
        } finally {
156
            if (gui.getErrorCount() == 0) {
×
157
                gui.sendFinished();
×
158
            }
159
        }
160
        return "ok"; // TODO
×
161
    }
162

163

164
    private void callJhcrUpdate(File mapScript) throws IOException, InterruptedException {
165
        File mapScriptFolder = mapScript.getParentFile();
×
166
        File commonJ = new File(mapScriptFolder, "common.j");
×
167
        File blizzardJ = new File(mapScriptFolder, "blizzard.j");
×
168
        if (!commonJ.exists()) {
×
169
            throw new IOException("Could not find file " + commonJ.getAbsolutePath());
×
170
        }
171

172
        if (!blizzardJ.exists()) {
×
173
            throw new IOException("Could not find file " + blizzardJ.getAbsolutePath());
×
174
        }
175

176
        Path customMapDataPath = getCustomMapDataPath();
×
177

178
        ProcessBuilder pb = new ProcessBuilder(langServer.getConfigProvider().getJhcrExe(), "update", mapScript.getName(), "--asm",
×
179
            "--preload-path", customMapDataPath.toAbsolutePath().toString());
×
180
        pb.directory(mapScriptFolder);
×
181
        Utils.ExecResult $ = Utils.exec(pb, Duration.ofSeconds(30), System.err::println);
×
182
    }
×
183

184
    /**
185
     * Tries to find the path where the wc3 CustomMapData is stored.
186
     * For example this could be in:
187
     * C:\\Users\\Peter\\Documents\\Warcraft III\\CustomMapData
188
     */
189
    private Path getCustomMapDataPath() {
190
        String customMapDataPath = langServer.getConfigProvider().getConfig("customMapDataPath", "");
×
191
        if (!customMapDataPath.isEmpty()) {
×
192
            return Paths.get(customMapDataPath);
×
193
        }
194

195
        Path documents;
196
        try {
197
            documents = FileSystemView.getFileSystemView().getDefaultDirectory().toPath();
×
198
        } catch (Throwable t) {
×
199
            WLogger.info(t);
×
200
            Path homeFolder = Paths.get(System.getProperty("user.home"));
×
201
            documents = homeFolder.resolve("Documents");
×
202
        }
×
203
        return documents.resolve(Paths.get("Warcraft III", "CustomMapData"));
×
204
    }
205

206
    @NotNull
207
    private String getWorkspaceAbsolute() {
208
        try {
209
            return workspaceRoot.getFile().getAbsolutePath();
×
210
        } catch (FileNotFoundException e) {
×
211
            throw new RequestFailedException(MessageType.Error, "Could not open workspace root: ", e);
×
212
        }
213
    }
214

215
    /**
216
     * Copies the map to the wc3 map directory
217
     * <p>
218
     * This directory depends on warcraft version and whether we are on windows or wine is used.
219
     */
220
    private File copyToWarcraftMapDir(File testMap) throws IOException {
221
        String testMapName = "WurstTestMap.w3x";
×
222
        for (String arg : compileArgs) {
×
223
            if (arg.startsWith("-runmapTarget")) {
×
224
                String path = arg.substring(arg.indexOf(" ") + 1);
×
225
                // copy the map to the specified directory
226
                customTarget = new File(path);
×
227
                if (customTarget.exists() && customTarget.isDirectory()) {
×
228
                    File testMap2 = new File(customTarget, testMapName);
×
229
                    Files.copy(testMap, testMap2);
×
230
                    return testMap2;
×
231
                } else {
232
                    WLogger.severe("Directory specified via -runmapTarget does not exists or is not a directory");
×
233
                }
234
            }
235
        }
×
236

237
        File myDocumentsFolder = FileSystemView.getFileSystemView().getDefaultDirectory();
×
238
        Optional<String> documentPath = findMapDocumentPath(testMapName, myDocumentsFolder);
×
239

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

262
            }
263

264
            return testMap2;
×
265
        } else {
266
            WLogger.severe("Could not create Test folder");
×
267
        }
268
        return null;
×
269
    }
270

271
    private Optional<String> findMapDocumentPath(String testMapName, File myDocumentsFolder) {
272
        Optional<String> documentPath = Optional.of(
×
273
            langServer.getConfigProvider().getMapDocumentPath().orElseGet(
×
274
                () -> myDocumentsFolder.getAbsolutePath() + File.separator + "Warcraft III"));
×
275

276
        if (!new File(documentPath.get()).exists()) {
×
277
            WLogger.info("Warcraft folder " + documentPath + " does not exist.");
×
278
            // Try wine default:
279
            documentPath = Optional.of(System.getProperty("user.home")
×
280
                + "/.wine/drive_c/users/" + System.getProperty("user.name") + "/My Documents/Warcraft III");
×
281
            if (!new File(documentPath.get()).exists()) {
×
282
                WLogger.severe("Severe: Wine Warcraft folder " + documentPath + " does not exist.");
×
283
            }
284
        }
285

286
        if (w3data.getWc3PatchVersion().get().compareTo(new GameVersion("1.27.9")) <= 0) {
×
287
            // 1.27 and lower compat
288
            WLogger.info("Version 1.27 or lower detected, changing file location");
×
289
            documentPath = wc3Path;
×
290
        } else {
291
            // For 1.28+ the wc3/maps/test folder must not contain a map of the same name
292
            Optional<File> oldFile = wc3Path.map(
×
293
                w3p -> new File(w3p, "Maps" + File.separator + "Test" + File.separator + testMapName));
×
294
            if (oldFile.isPresent() && oldFile.get().exists()) {
×
295
                if (!oldFile.get().delete()) {
×
296
                    WLogger.severe("Cannot delete old Wurst Test Map");
×
297
                }
298
            }
299
        }
300
        return documentPath;
×
301
    }
302

303

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

© 2026 Coveralls, Inc