Add Wiki plugin

This has the side affect of making the click mask around the run orb correct in fixed mode
This commit is contained in:
Max Weber
2018-11-26 19:33:30 -07:00
committed by Adam
parent e287a34a57
commit 35e6e341bb
15 changed files with 802 additions and 2 deletions

View File

@@ -183,6 +183,9 @@ public class WidgetInfoTableModel extends AbstractTableModel
out.add(new WidgetField<>("ScrollHeight", Widget::getScrollHeight, Widget::setScrollHeight, Integer.class));
out.add(new WidgetField<>("DragDeadZone", Widget::getDragDeadZone, Widget::setDragDeadZone, Integer.class));
out.add(new WidgetField<>("DragDeadTime", Widget::getDragDeadTime, Widget::setDragDeadTime, Integer.class));
out.add(new WidgetField<>("NoClickThrough", Widget::getNoClickThrough, Widget::setNoClickThrough, Boolean.class));
out.add(new WidgetField<>("NoScrollThrough", Widget::getNoScrollThrough, Widget::setNoScrollThrough, Boolean.class));
out.add(new WidgetField<>("TargetVerb", Widget::getTargetVerb, Widget::setTargetVerb, String.class));
return out;
}

View File

@@ -0,0 +1,289 @@
/*
* Copyright (c) 2018 Abex
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.wiki;
import com.google.common.primitives.Ints;
import java.net.URLEncoder;
import java.util.Arrays;
import javax.inject.Inject;
import javax.inject.Provider;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.MenuAction;
import net.runelite.api.MenuEntry;
import net.runelite.api.NPC;
import net.runelite.api.NPCComposition;
import net.runelite.api.events.MenuEntryAdded;
import net.runelite.api.events.MenuOptionClicked;
import net.runelite.api.events.WidgetLoaded;
import net.runelite.api.widgets.JavaScriptCallback;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetConfig;
import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo;
import net.runelite.api.widgets.WidgetPositionMode;
import net.runelite.api.widgets.WidgetType;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.ItemManager;
import net.runelite.client.game.SpriteManager;
import net.runelite.client.game.chatbox.ChatboxPanelManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.util.LinkBrowser;
import net.runelite.client.util.Text;
import okhttp3.HttpUrl;
@Slf4j
@PluginDescriptor(
name = "Wiki",
description = "Adds a Wiki button that takes you to the OSRS Wiki"
)
public class WikiPlugin extends Plugin
{
private static final int[] QUESTLIST_WIDGET_IDS = new int[]
{
WidgetInfo.QUESTLIST_FREE_CONTAINER.getId(),
WidgetInfo.QUESTLIST_MEMBERS_CONTAINER.getId(),
WidgetInfo.QUESTLIST_MINIQUEST_CONTAINER.getId(),
};
static final String WIKI_BASE = "https://oldschool.runescape.wiki";
static final HttpUrl WIKI_RSLOOKUP = HttpUrl.parse(WIKI_BASE + "/w/Special:Lookup");
static final HttpUrl WIKI_API = HttpUrl.parse(WIKI_BASE + "/api.php");
static final String UTM_SORUCE_KEY = "utm_source";
static final String UTM_SORUCE_VALUE = "runelite";
static final String UTM_PARAMS = UTM_SORUCE_KEY + "=" + UTM_SORUCE_VALUE;
private static final String MENUOP_GUIDE = "Guide";
private static final String MENUOP_QUICKGUIDE = "Quick Guide";
@Inject
private SpriteManager spriteManager;
@Inject
private ClientThread clientThread;
@Inject
private Client client;
@Inject
private ChatboxPanelManager chatboxPanelManager;
@Inject
private ItemManager itemManager;
@Inject
private Provider<WikiSearchChatboxTextInput> wikiSearchChatboxTextInputProvider;
private Widget icon;
private boolean wikiSelected = false;
@Override
public void startUp()
{
spriteManager.addSpriteOverrides(WikiSprite.values());
clientThread.invokeLater(this::addWidgets);
}
@Override
public void shutDown()
{
spriteManager.removeSpriteOverrides(WikiSprite.values());
clientThread.invokeLater(() ->
{
Widget minimapOrbs = client.getWidget(WidgetInfo.MINIMAP_ORBS);
if (minimapOrbs == null)
{
return;
}
Widget[] children = minimapOrbs.getChildren();
if (children == null || children.length < 1)
{
return;
}
children[0] = null;
});
}
@Subscribe
private void onWidgetLoaded(WidgetLoaded l)
{
if (l.getGroupId() == WidgetID.MINIMAP_GROUP_ID)
{
addWidgets();
}
}
private void addWidgets()
{
Widget minimapOrbs = client.getWidget(WidgetInfo.MINIMAP_ORBS);
if (minimapOrbs == null)
{
return;
}
icon = minimapOrbs.createChild(0, WidgetType.GRAPHIC);
icon.setSpriteId(WikiSprite.WIKI_ICON.getSpriteId());
icon.setOriginalX(0);
icon.setOriginalY(2);
icon.setXPositionMode(WidgetPositionMode.ABSOLUTE_RIGHT);
icon.setYPositionMode(WidgetPositionMode.ABSOLUTE_BOTTOM);
icon.setOriginalWidth(42);
icon.setOriginalHeight(16);
icon.setTargetVerb("Lookup");
icon.setName("Wiki");
icon.setClickMask(WidgetConfig.USE_GROUND_ITEM | WidgetConfig.USE_ITEM | WidgetConfig.USE_NPC);
icon.setNoClickThrough(true);
icon.setOnTargetEnterListener((JavaScriptCallback) ev ->
{
wikiSelected = true;
icon.setSpriteId(WikiSprite.WIKI_SELECTED_ICON.getSpriteId());
});
icon.setAction(5, "Search"); // Start at option 5 so the target op is ontop
icon.setOnOpListener((JavaScriptCallback) ev ->
{
switch (ev.getOp())
{
case 6:
openSearchInput();
break;
}
});
// This doesn't always run because we cancel the menuop
icon.setOnTargetLeaveListener((JavaScriptCallback) ev -> onDeselect());
icon.revalidate();
}
private void onDeselect()
{
wikiSelected = false;
icon.setSpriteId(WikiSprite.WIKI_ICON.getSpriteId());
}
@Subscribe
private void onMenuOptionClicked(MenuOptionClicked ev)
{
if (wikiSelected)
{
onDeselect();
client.setSpellSelected(false);
ev.consume();
String type;
int id;
String name;
switch (ev.getMenuAction())
{
case CANCEL:
return;
case ITEM_USE_ON_WIDGET:
case SPELL_CAST_ON_GROUND_ITEM:
{
type = "item";
id = itemManager.canonicalize(ev.getId());
name = itemManager.getItemComposition(id).getName();
break;
}
case SPELL_CAST_ON_NPC:
{
type = "npc";
NPC npc = client.getCachedNPCs()[ev.getId()];
NPCComposition nc = npc.getTransformedComposition();
id = nc.getId();
name = nc.getName();
break;
}
default:
log.info("Unknown menu option: {} {} {}", ev, ev.getMenuAction(), ev.getMenuAction() == MenuAction.CANCEL);
return;
}
HttpUrl url = WIKI_RSLOOKUP.newBuilder()
.addQueryParameter("type", type)
.addQueryParameter("id", "" + id)
.addQueryParameter("name", name)
.addQueryParameter(UTM_SORUCE_KEY, UTM_SORUCE_VALUE)
.build();
LinkBrowser.browse(url.toString());
return;
}
if (ev.getMenuAction() == MenuAction.RUNELITE)
{
String quickguide = "";
switch (ev.getMenuOption())
{
case MENUOP_QUICKGUIDE:
quickguide = "/Quick_guide";
//fallthrough;
case MENUOP_GUIDE:
ev.consume();
String quest = Text.removeTags(ev.getMenuTarget());
LinkBrowser.browse(WIKI_BASE + "/w/" + URLEncoder.encode(quest.replace(' ', '_')) + quickguide + "?" + UTM_PARAMS);
break;
}
}
}
private void openSearchInput()
{
wikiSearchChatboxTextInputProvider.get()
.build();
}
@Subscribe
public void onMenuEntryAdded(MenuEntryAdded event)
{
int widgetIndex = event.getActionParam0();
int widgetID = event.getActionParam1();
if (!Ints.contains(QUESTLIST_WIDGET_IDS, widgetID) || !"Read Journal:".equals(event.getOption()))
{
return;
}
MenuEntry[] menuEntries = client.getMenuEntries();
menuEntries = Arrays.copyOf(menuEntries, menuEntries.length + 2);
MenuEntry menuEntry = menuEntries[menuEntries.length - 1] = new MenuEntry();
menuEntry.setTarget(event.getTarget());
menuEntry.setOption(MENUOP_GUIDE);
menuEntry.setParam0(widgetIndex);
menuEntry.setParam1(widgetID);
menuEntry.setType(MenuAction.RUNELITE.getId());
menuEntry = menuEntries[menuEntries.length - 2] = new MenuEntry();
menuEntry.setTarget(event.getTarget());
menuEntry.setOption(MENUOP_QUICKGUIDE);
menuEntry.setParam0(widgetIndex);
menuEntry.setParam1(widgetID);
menuEntry.setType(MenuAction.RUNELITE.getId());
client.setMenuEntries(menuEntries);
}
}

View File

@@ -0,0 +1,302 @@
/*
* Copyright (c) 2018 Abex
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.wiki;
import com.google.common.collect.ImmutableList;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.inject.Inject;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.inject.Named;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.widgets.JavaScriptCallback;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetPositionMode;
import net.runelite.api.widgets.WidgetSizeMode;
import net.runelite.api.widgets.WidgetTextAlignment;
import net.runelite.api.widgets.WidgetType;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.game.chatbox.ChatboxPanelManager;
import net.runelite.client.game.chatbox.ChatboxTextInput;
import net.runelite.client.util.LinkBrowser;
import net.runelite.http.api.RuneLiteAPI;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;
@Slf4j
public class WikiSearchChatboxTextInput extends ChatboxTextInput
{
private static final int LINE_HEIGHT = 20;
private static final int CHATBOX_HEIGHT = 120;
private static final int MAX_NUM_PREDICTIONS = (CHATBOX_HEIGHT / LINE_HEIGHT) - 2; // 1 title, 1 edit
private static final int PREDICTION_DEBOUNCE_DELAY_MS = 200;
private final ChatboxPanelManager chatboxPanelManager;
private final Gson gson = new Gson();
private Future<?> runningRequest = null;
private List<String> predictions = ImmutableList.of();
private int selectedPrediction = -1;
private String offPrediction = null;
@Inject
public WikiSearchChatboxTextInput(ChatboxPanelManager chatboxPanelManager, ClientThread clientThread,
ScheduledExecutorService scheduledExecutorService, @Named("developerMode") final boolean developerMode)
{
super(chatboxPanelManager, clientThread);
this.chatboxPanelManager = chatboxPanelManager;
prompt("OSRS Wiki Search");
onDone(string ->
{
if (string != null && string.length() > 0)
{
search(string);
}
});
onChanged(searchString ->
{
selectedPrediction = -1;
Future<?> rr = runningRequest;
if (rr != null)
{
rr.cancel(false);
}
if (searchString.length() <= 1)
{
runningRequest = null;
clientThread.invokeLater(() ->
{
predictions = ImmutableList.of();
update();
});
return;
}
runningRequest = scheduledExecutorService.schedule(() ->
{
HttpUrl url = WikiPlugin.WIKI_API.newBuilder()
.addQueryParameter("action", "opensearch")
.addQueryParameter("search", searchString)
.addQueryParameter("redirects", "resolve")
.addQueryParameter("format", "json")
.addQueryParameter("warningsaserror", Boolean.toString(developerMode))
.build();
Request req = new Request.Builder()
.url(url)
.build();
RuneLiteAPI.CLIENT.newCall(req).enqueue(new Callback()
{
@Override
public void onFailure(Call call, IOException e)
{
log.warn("error searching wiki", e);
}
@Override
public void onResponse(Call call, Response response) throws IOException
{
String body = response.body().string();
try
{
JsonArray jar = new JsonParser().parse(body).getAsJsonArray();
List<String> apredictions = gson.fromJson(jar.get(1), new TypeToken<List<String>>()
{
}.getType());
if (apredictions.size() > MAX_NUM_PREDICTIONS)
{
apredictions = apredictions.subList(0, MAX_NUM_PREDICTIONS);
}
final List<String> bpredictions = apredictions;
clientThread.invokeLater(() ->
{
predictions = bpredictions;
update();
});
}
catch (JsonParseException | IllegalStateException | IndexOutOfBoundsException e)
{
log.warn("error parsing wiki response {}", body, e);
}
finally
{
response.close();
}
}
});
runningRequest = null;
}, PREDICTION_DEBOUNCE_DELAY_MS, TimeUnit.MILLISECONDS);
});
}
@Override
protected void update()
{
Widget container = chatboxPanelManager.getContainerWidget();
container.deleteAllChildren();
Widget promptWidget = container.createChild(-1, WidgetType.TEXT);
promptWidget.setText(getPrompt());
promptWidget.setTextColor(0x800000);
promptWidget.setFontId(getFontID());
promptWidget.setXPositionMode(WidgetPositionMode.ABSOLUTE_CENTER);
promptWidget.setOriginalX(0);
promptWidget.setYPositionMode(WidgetPositionMode.ABSOLUTE_TOP);
promptWidget.setOriginalY(5);
promptWidget.setOriginalHeight(LINE_HEIGHT);
promptWidget.setXTextAlignment(WidgetTextAlignment.CENTER);
promptWidget.setYTextAlignment(WidgetTextAlignment.CENTER);
promptWidget.setWidthMode(WidgetSizeMode.MINUS);
promptWidget.revalidate();
buildEdit(0, 5 + LINE_HEIGHT, container.getWidth(), LINE_HEIGHT);
Widget separator = container.createChild(-1, WidgetType.LINE);
separator.setXPositionMode(WidgetPositionMode.ABSOLUTE_CENTER);
separator.setOriginalX(0);
separator.setYPositionMode(WidgetPositionMode.ABSOLUTE_TOP);
separator.setOriginalY(4 + (LINE_HEIGHT * 2));
separator.setOriginalHeight(0);
separator.setOriginalWidth(16);
separator.setWidthMode(WidgetSizeMode.MINUS);
separator.revalidate();
for (int i = 0; i < predictions.size(); i++)
{
String pred = predictions.get(i);
int y = 6 + (LINE_HEIGHT * (2 + i));
Widget bg = container.createChild(-1, WidgetType.RECTANGLE);
bg.setTextColor(0x4444DD);
bg.setFilled(true);
bg.setXPositionMode(WidgetPositionMode.ABSOLUTE_CENTER);
bg.setOriginalX(1);
bg.setYPositionMode(WidgetPositionMode.ABSOLUTE_TOP);
bg.setOriginalY(y);
bg.setOriginalHeight(LINE_HEIGHT);
bg.setOriginalWidth(16);
bg.setWidthMode(WidgetSizeMode.MINUS);
bg.revalidate();
bg.setName("<col=ff9040>" + pred);
bg.setAction(0, "Open");
bg.setHasListener(true);
bg.setOnOpListener((JavaScriptCallback) ev -> search(pred));
Widget text = container.createChild(-1, WidgetType.TEXT);
text.setText(pred);
text.setFontId(getFontID());
text.setXPositionMode(WidgetPositionMode.ABSOLUTE_CENTER);
text.setOriginalX(0);
text.setYPositionMode(WidgetPositionMode.ABSOLUTE_TOP);
text.setOriginalY(y);
text.setOriginalHeight(LINE_HEIGHT);
text.setXTextAlignment(WidgetTextAlignment.CENTER);
text.setYTextAlignment(WidgetTextAlignment.CENTER);
text.setWidthMode(WidgetSizeMode.MINUS);
text.revalidate();
if (i == selectedPrediction)
{
text.setTextColor(0xFFFFFF);
}
else
{
bg.setOpacity(255);
text.setTextColor(0x000000);
bg.setOnMouseRepeatListener((JavaScriptCallback) ev -> text.setTextColor(0xFFFFFF));
bg.setOnMouseLeaveListener((JavaScriptCallback) ev -> text.setTextColor(0x000000));
}
}
}
@Override
public void keyPressed(KeyEvent ev)
{
switch (ev.getKeyCode())
{
case KeyEvent.VK_UP:
ev.consume();
if (selectedPrediction > -1)
{
selectedPrediction--;
if (selectedPrediction == -1)
{
value(offPrediction);
}
else
{
value(predictions.get(selectedPrediction));
}
}
break;
case KeyEvent.VK_DOWN:
ev.consume();
if (selectedPrediction == -1)
{
offPrediction = getValue();
}
selectedPrediction++;
if (selectedPrediction >= predictions.size())
{
selectedPrediction = predictions.size() - 1;
}
if (selectedPrediction != -1)
{
value(predictions.get(selectedPrediction));
}
break;
default:
super.keyPressed(ev);
}
}
private void search(String search)
{
LinkBrowser.browse(WikiPlugin.WIKI_BASE + "?search=" + URLEncoder.encode(search) + "&" + WikiPlugin.UTM_PARAMS);
chatboxPanelManager.close();
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) 2018 Abex
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.wiki;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import net.runelite.api.SpriteID;
import net.runelite.client.game.SpriteOverride;
@RequiredArgsConstructor
public enum WikiSprite implements SpriteOverride
{
WIKI_ICON(-300, "wiki.png"),
WIKI_SELECTED_ICON(-301, "wiki_selected.png"),
FIXED_MODE_MINIMAP_CLICKMASK(SpriteID.MINIMAP_CLICK_MASK, "fixed_mode_minimap_clickmask.png");
@Getter
private final int spriteId;
@Getter
private final String fileName;
}