aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/io/github/moulberry/notenoughupdates/infopanes/HTMLInfoPane.java
blob: c03b98fb92463d66633842a18da1720fb9ac5378 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package io.github.moulberry.notenoughupdates.infopanes;

import info.bliki.htmlcleaner.TagNode;
import info.bliki.wiki.filter.Encoder;
import info.bliki.wiki.model.Configuration;
import info.bliki.wiki.model.ImageFormat;
import info.bliki.wiki.model.WikiModel;
import info.bliki.wiki.tags.HTMLBlockTag;
import info.bliki.wiki.tags.HTMLTag;
import info.bliki.wiki.tags.IgnoreTag;
import io.github.moulberry.notenoughupdates.AllowEmptyHTMLTag;
import io.github.moulberry.notenoughupdates.NEUManager;
import io.github.moulberry.notenoughupdates.NEUOverlay;
import io.github.moulberry.notenoughupdates.util.Utils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class HTMLInfoPane extends TextInfoPane {

    private static WikiModel wikiModel;

    private final int ZOOM_FACTOR = 2;
    private final int IMAGE_WIDTH = 400;
    private final int EXT_WIDTH = 100;

    private ResourceLocation imageTexture = null;
    private BufferedImage imageTemp = null;
    private int imageHeight = 0;
    private int imageWidth = 0;

    /**
     * Creates a wiki model and sets the configuration to work with hypixel-skyblock wikia.
     */
    static {
        Configuration conf = new Configuration();
        conf.addTokenTag("img", new HTMLTag("img"));
        conf.addTokenTag("code", new HTMLTag("code"));
        conf.addTokenTag("span", new AllowEmptyHTMLTag("span"));
        conf.addTokenTag("table", new HTMLBlockTag("table", Configuration.SPECIAL_BLOCK_TAGS+"span|"));
        conf.addTokenTag("infobox", new IgnoreTag("infobox"));
        conf.addTokenTag("tabber", new IgnoreTag("tabber"));
        conf.addTokenTag("kbd", new HTMLTag("kbd"));
        wikiModel = new WikiModel(conf,"https://hypixel-skyblock.fandom.com/wiki/Special:Filepath/${image}",
                "https://hypixel-skyblock.fandom.com/wiki/${title}") {
            {
                TagNode.addAllowedAttribute("style");
                TagNode.addAllowedAttribute("src");
            }

            protected String createImageName(ImageFormat imageFormat) {
                String imageName = imageFormat.getFilename();
                if (imageName.endsWith(".svg")) {
                    imageName += ".png";
                }
                imageName = Encoder.encodeUrl(imageName);
                if (replaceColon()) {
                    imageName = imageName.replace(':', '/');
                }
                return imageName;
            }

            public void parseInternalImageLink(String imageNamespace, String rawImageLink) {
                rawImageLink = rawImageLink.replaceFirst("\\|x([0-9]+)px", "\\|$1x$1px");
                if(!rawImageLink.split("\\|")[0].toLowerCase().endsWith(".jpg")) {
                    super.parseInternalImageLink(imageNamespace, rawImageLink);
                }
            }
        };
    }

    /**
     * Takes a wiki url, uses NEUManager#getWebFile to download the web file and passed that in to #createFromWiki
     */
    public static HTMLInfoPane createFromWikiUrl(NEUOverlay overlay, NEUManager manager, String name,
                                                 String wikiUrl) {
        File f = manager.getWebFile(wikiUrl);
        if(f == null) {
            return new HTMLInfoPane(overlay, manager, "error", "error","Failed to load wiki url: "+ wikiUrl);
        };

        StringBuilder sb = new StringBuilder();
        try(BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream(f), StandardCharsets.UTF_8))) {
            String l;
            while((l = br.readLine()) != null){
                sb.append(l).append("\n");
            }
        } catch(IOException e) {
            return new HTMLInfoPane(overlay, manager, "error", "error","Failed to load wiki url: "+ wikiUrl);
        }
        return createFromWiki(overlay, manager, name, f.getName(), sb.toString());
    }

    /**
     * Takes raw wikia code and uses Bliki to generate HTML. Lot's of shennanigans to get it to render appropriately.
     * Honestly, I could have just downloaded the raw HTML of the wiki page and displayed that but I wanted
     * a more permanent solution that can be abstracted to work with arbitrary wiki codes (eg. moulberry.github.io/
     * files/neu_help.html).
     */
    public static HTMLInfoPane createFromWiki(NEUOverlay overlay, NEUManager manager, String name, String filename,
                                              String wiki) {
        String[] split = wiki.split("</infobox>");
        wiki = split[split.length - 1]; //Remove everything before infobox
        wiki = wiki.split("<span class=\"navbox-vde\">")[0]; //Remove navbox
        wiki = wiki.split("<table class=\"navbox mw-collapsible\"")[0];
        wiki = "__NOTOC__\n" + wiki; //Remove TOC
        try (PrintWriter out = new PrintWriter(new File(manager.configLocation, "debug/parsed.txt"))) {
            out.println(wiki);
        } catch (IOException e) {
        }
        String html;
        try {
            html = wikiModel.render(wiki);
        } catch(IOException e) {
            return new HTMLInfoPane(overlay, manager, "error", "error", "Could not render wiki.");
        }
        try (PrintWriter out = new PrintWriter(new File(manager.configLocation, "debug/html.txt"))) {
            out.println(html);
        } catch (IOException e) {
        }
        return new HTMLInfoPane(overlay, manager, name, filename, html);
    }

    private String spaceEscape(String str) {
        return str.replace(" ", "\\ ");
    }

    /**
     * Uses the wkhtmltoimage command-line tool to generate an image from the HTML code. This
     * generation is done asynchronously as sometimes it can take up to 10 seconds for more
     * complex webpages.
     */
    public HTMLInfoPane(NEUOverlay overlay, NEUManager manager, String name, String filename, String html) {
        super(overlay, manager, name, "");
        this.title = name;

        File cssFile = new File(manager.configLocation, "wikia.css");
        File wkHtmlToImage = new File(manager.configLocation, "wkhtmltox/bin/wkhtmltoimage");
        File input = new File(manager.configLocation, "tmp/input.html");
        String outputFileName = filename.replaceAll("(?i)\\u00A7.", "")
                .replaceAll("[^a-zA-Z0-9_\\-]", "_");
        File output = new File(manager.configLocation, "tmp/"+
                outputFileName+".png");
        File outputExt = new File(manager.configLocation, "tmp/"+
                outputFileName+"_ext.png");

        input.deleteOnExit();
        output.deleteOnExit();

        File tmp = new File(manager.configLocation, "tmp");
        if(!tmp.exists()) {
            tmp.mkdir();
        }

        if(output.exists()) {
            try {
                imageTemp = ImageIO.read(output);
                text = EnumChatFormatting.RED+"Creating dynamic texture.";
            } catch(IOException e) {
                e.printStackTrace();
                text = EnumChatFormatting.RED+"Failed to read image.";
                return;
            }
        } else {
            html = "<div id=\"mw-content-text\" lang=\"en\" dir=\"ltr\" class=\"mw-content-ltr mw-content-text\">"+html+"</div>";
            html = "<div id=\"WikiaArticle\" class=\"WikiaArticle\">"+html+"</div>";
            html = "<link rel=\"stylesheet\" href=\"file:///"+cssFile.getAbsolutePath()+"\">\n"+html;

            try(PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(input), StandardCharsets.UTF_8)), false)) {

                out.println(encodeNonAscii(html));
            } catch(IOException e) {}


            ExecutorService ste = Executors.newSingleThreadExecutor();
            try {
                text = EnumChatFormatting.GRAY+"Rendering webpage (" + name + EnumChatFormatting