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

wurstscript / WurstScript / 209

25 Oct 2023 11:42AM UTC coverage: 63.746% (-0.01%) from 63.756%
209

Pull #1081

circleci

Frotty
WIP
Pull Request #1081: More performance improvements

17267 of 27087 relevant lines covered (63.75%)

0.64 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.TimeTaker;
8
import de.peeeq.wurstio.gui.WurstGuiImpl;
9
import de.peeeq.wurstio.languageserver.ConfigProvider;
10
import de.peeeq.wurstio.languageserver.ModelManager;
11
import de.peeeq.wurstio.languageserver.ProjectConfigBuilder;
12
import de.peeeq.wurstio.languageserver.WFile;
13
import de.peeeq.wurstio.mpq.MpqEditor;
14
import de.peeeq.wurstio.mpq.MpqEditorFactory;
15
import de.peeeq.wurstscript.WLogger;
16
import de.peeeq.wurstscript.attributes.CompileError;
17
import de.peeeq.wurstscript.gui.WurstGui;
18
import de.peeeq.wurstscript.utils.Utils;
19
import net.moonlightflower.wc3libs.bin.app.W3I;
20
import net.moonlightflower.wc3libs.port.GameVersion;
21
import net.moonlightflower.wc3libs.port.Orient;
22
import org.apache.commons.lang.RandomStringUtils;
23
import org.apache.commons.lang.StringUtils;
24
import org.eclipse.lsp4j.MessageType;
25
import org.jetbrains.annotations.NotNull;
26
import org.jetbrains.annotations.Nullable;
27

28
import javax.swing.*;
29
import javax.swing.filechooser.FileSystemView;
30
import java.io.File;
31
import java.io.FileNotFoundException;
32
import java.io.IOException;
33
import java.nio.file.Path;
34
import java.nio.file.Paths;
35
import java.time.Duration;
36
import java.util.List;
37
import java.util.Optional;
38
import java.util.Arrays;
39

40
import static de.peeeq.wurstio.languageserver.ProjectConfigBuilder.FILE_NAME;
41
import static net.moonlightflower.wc3libs.port.GameVersion.*;
42

43
/**
44
 * Created by peter on 16.05.16.
45
 */
46
public class RunMap extends MapRequest {
47

48
    private @Nullable File customTarget = null;
×
49

50

51
    public RunMap(ConfigProvider configProvider, WFile workspaceRoot, Optional<String> wc3Path, Optional<File> map,
52
            List<String> compileArgs) {
53
        super(configProvider, map, compileArgs, workspaceRoot, wc3Path);
×
54
        safeCompilation = SafetyLevel.QuickAndDirty;
×
55
    }
×
56

57
    @Override
58
    public Object execute(ModelManager modelManager) throws IOException {
59
        timeTaker.beginPhase("Running Map");
×
60
        WLogger.info("Execute RunMap, \nwc3Path =" + wc3Path
×
61
            + ",\n map = " + map
62
            + ",\n compileArgs = " + compileArgs
63
            + ",\n workspaceRoot = " + workspaceRoot
64
            + ",\n runArgs = " + compileArgs
65
        );
66

67
        if (modelManager.hasErrors()) {
×
68
            throw new RequestFailedException(MessageType.Error, "Fix errors in your code before running.\n" + modelManager.getFirstErrorDescription());
×
69
        }
70

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

77
        // TODO use normal compiler for this, avoid code duplication
78
        WLogger.info("received runMap command: map=" + map + ", wc3dir=" + wc3Path + ", args=" + compileArgs);
×
79
        WurstGui gui = new WurstGuiImpl(getWorkspaceAbsolute());
×
80
        try {
81
            if (map.isPresent() && !map.get().exists()) {
×
82
                throw new RequestFailedException(MessageType.Error, map.get().getAbsolutePath() + " does not exist.");
×
83
            }
84

85
            gui.sendProgress("Copying map");
×
86

87
            // first we copy in same location to ensure validity
88
            File buildDir = getBuildDir();
×
89
            Optional<File> testMap = map.map($ -> new File(buildDir, "WurstRunMap.w3x"));
×
90
            CompilationResult result = compileScript(modelManager, gui, testMap, projectConfig, buildDir, false);
×
91

92
            if (runArgs.isHotReload()) {
×
93
                // call jhcr update
94
                gui.sendProgress("Calling JHCR update");
×
95
                callJhcrUpdate(result.script);
×
96

97
                // if we are just reloading the mapscript with JHCR, we are done here
98
                gui.sendProgress("update complete");
×
99
                return "ok";
×
100
            }
101

102

103
            if (testMap.isPresent()) {
×
104

105
                injectMapData(gui, testMap, result);
×
106

107
                File mapCopy = copyToWarcraftMapDir(testMap.get());
×
108

109
                gui.sendProgress("Starting Warcraft 3...");
×
110
                WLogger.info("Starting wc3 ... ");
×
111
                String path = "";
×
112
                if (customTarget != null) {
×
113
                    path = new File(customTarget, testMap.get().getName()).getAbsolutePath();
×
114
                } else if (mapCopy != null) {
×
115
                    path = mapCopy.getAbsolutePath();
×
116
                }
117

118

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

143
                    if (Orient.isLinuxSystem()) {
×
144
                        // run with wine
145
                        cmd.add(0, "wine");
×
146
                    }
147

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

168

169
    private void callJhcrUpdate(File mapScript) throws IOException, InterruptedException {
170
        File mapScriptFolder = mapScript.getParentFile();
×
171
        File commonJ = new File(mapScriptFolder, "common.j");
×
172
        File blizzardJ = new File(mapScriptFolder, "blizzard.j");
×
173
        if (!commonJ.exists()) {
×
174
            throw new IOException("Could not find file " + commonJ.getAbsolutePath());
×
175
        }
176

177
        if (!blizzardJ.exists()) {
×
178
            throw new IOException("Could not find file " + blizzardJ.getAbsolutePath());
×
179
        }
180

181
        Path customMapDataPath = getCustomMapDataPath();
×
182

183
        ProcessBuilder pb = new ProcessBuilder(configProvider.getJhcrExe(), "update", mapScript.getName(), "--asm",
×
184
            "--preload-path", customMapDataPath.toAbsolutePath().toString());
×
185
        pb.directory(mapScriptFolder);
×
186
        Utils.ExecResult $ = Utils.exec(pb, Duration.ofSeconds(30), System.err::println);
×
187
    }
×
188

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

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

211
    @NotNull
212
    private String getWorkspaceAbsolute() {
213
        try {
214
            return workspaceRoot.getFile().getAbsolutePath();
×
215
        } catch (FileNotFoundException e) {
×
216
            throw new RequestFailedException(MessageType.Error, "Could not open workspace root: ", e);
×
217
        }
218
    }
219

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

242
        File myDocumentsFolder = FileSystemView.getFileSystemView().getDefaultDirectory();
×
243
        Optional<String> documentPath = findMapDocumentPath(testMapName, myDocumentsFolder);
×
244

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

267
            }
268

269
            return testMap2;
×
270
        } else {
271
            WLogger.severe("Could not create Test folder");
×
272
        }
273
        return null;
×
274
    }
275

276
    private Optional<String> findMapDocumentPath(String testMapName, File myDocumentsFolder) {
277
        Optional<String> documentPath = Optional.of(
×
278
            configProvider.getMapDocumentPath().orElseGet(
×
279
                () -> myDocumentsFolder.getAbsolutePath() + File.separator + "Warcraft III"));
×
280

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

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

308

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