├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ └── java │ │ └── com │ │ └── github │ │ └── i │ │ ├── fuzzybanksearch │ │ ├── matcher │ │ │ ├── MatchResult.java │ │ │ ├── fzf │ │ │ │ ├── NOTE │ │ │ │ ├── OrderBy.java │ │ │ │ ├── LICENCE │ │ │ │ ├── ResultComparator.java │ │ │ │ ├── Normalizer.java │ │ │ │ ├── Result.java │ │ │ │ └── FuzzyMatcherV1.java │ │ │ ├── Matcher.java │ │ │ ├── FZFMatcher.java │ │ │ └── JaroWinklerMatcher.java │ │ ├── FuzzyBankSearchConfig.java │ │ └── FuzzyBankSearchPlugin.java │ │ └── platz │ │ ├── PlatzConfig.java │ │ └── PlatzPlugin.java └── test │ └── java │ └── com │ └── github │ └── i │ ├── platz │ ├── PlatzPluginTest.java │ └── AbbreviationTest.java │ ├── fuzzybanksearch │ └── FuzzyBankSearchPluginTest.java │ └── master │ └── MasterPluginTest.java ├── .gitignore ├── runelite-plugin.properties ├── README.md ├── LICENSE ├── gradlew.bat └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'example' 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/i/rl-plugins/master/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/MatchResult.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch.matcher; 2 | 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build 3 | .idea/ 4 | .project 5 | .settings/ 6 | .classpath 7 | nbactions.xml 8 | nb-configuration.xml 9 | nbproject/ -------------------------------------------------------------------------------- /runelite-plugin.properties: -------------------------------------------------------------------------------- 1 | displayName=fillmein 2 | author=fillmein 3 | support=github.com/i/rl-plugins 4 | description=fillmein 5 | tags=fillmein 6 | plugins=fillmein 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/fzf/NOTE: -------------------------------------------------------------------------------- 1 | The code in this directory was largely copied from: 2 | https://github.com/gesundkrank/fzf4j with permission by license. -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/fzf/OrderBy.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch.matcher.fzf; 2 | 3 | public enum OrderBy { 4 | SCORE, LENGTH 5 | } 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Plugins 2 | 3 | - [Fuzzy bank search](https://github.com/i/rl-plugins/tree/fuzzy-bank-search) - Allows fuzzy searching your bank (e.g. type dwh to find dragon warhammer) 4 | - [Platz](https://github.com/i/rl-plugins/tree/platz) - Replaces the "lots" text with the actual value when trades are worth more than max cash 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionSha256Sum=cd5c2958a107ee7f0722004a12d0f8559b4564c34daad7df06cffd4d12a426d0 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/Matcher.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch.matcher; 2 | 3 | import java.util.Collection; 4 | import java.util.Map; 5 | import java.util.Set; 6 | 7 | public abstract class Matcher { 8 | protected Map itemIdsToNames = null; 9 | 10 | public abstract Set match(String query, int limit); 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/com/github/i/platz/PlatzPluginTest.java: -------------------------------------------------------------------------------- 1 | package com.github.i.platz; 2 | 3 | import net.runelite.client.RuneLite; 4 | import net.runelite.client.externalplugins.ExternalPluginManager; 5 | 6 | public class PlatzPluginTest { 7 | public static void main(String[] args) throws Exception { 8 | ExternalPluginManager.loadBuiltin(PlatzPlugin.class); 9 | RuneLite.main(args); 10 | } 11 | } -------------------------------------------------------------------------------- /src/test/java/com/github/i/fuzzybanksearch/FuzzyBankSearchPluginTest.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch; 2 | 3 | import net.runelite.client.RuneLite; 4 | import net.runelite.client.externalplugins.ExternalPluginManager; 5 | 6 | public class FuzzyBankSearchPluginTest { 7 | public static void main(String[] args) throws Exception { 8 | 9 | 10 | ExternalPluginManager.loadBuiltin(FuzzyBankSearchPlugin.class); 11 | RuneLite.main(args); 12 | } 13 | } -------------------------------------------------------------------------------- /src/test/java/com/github/i/master/MasterPluginTest.java: -------------------------------------------------------------------------------- 1 | package com.github.i.master; 2 | 3 | import com.github.i.fuzzybanksearch.FuzzyBankSearchPlugin; 4 | import com.github.i.platz.PlatzPlugin; 5 | import net.runelite.client.RuneLite; 6 | import net.runelite.client.externalplugins.ExternalPluginManager; 7 | 8 | public class MasterPluginTest { 9 | public static void main(String[] args) throws Exception { 10 | ExternalPluginManager.loadBuiltin( 11 | FuzzyBankSearchPlugin.class, 12 | PlatzPlugin.class); 13 | RuneLite.main(args); 14 | } 15 | } -------------------------------------------------------------------------------- /src/main/java/com/github/i/platz/PlatzConfig.java: -------------------------------------------------------------------------------- 1 | package com.github.i.platz; 2 | 3 | import net.runelite.client.config.Config; 4 | import net.runelite.client.config.ConfigGroup; 5 | import net.runelite.client.config.ConfigItem; 6 | 7 | @ConfigGroup("platz") 8 | public interface PlatzConfig extends Config 9 | { 10 | @ConfigItem( 11 | keyName = "abbreviate", 12 | name = "Abbreviate large numbers values", 13 | description = "Abbreviate values (e.g. 2,147,483,647 is shown as 2.147B)" 14 | ) 15 | default boolean abbreviate() { return false; } 16 | 17 | @ConfigItem( 18 | keyName = "largeNumberCutoff", 19 | name = "Large number cutoff", 20 | description = "Determines the cutoff for large numbers" 21 | ) 22 | default long largeNumberCutoff() { return 100_000_000L; } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/FZFMatcher.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch.matcher; 2 | 3 | import com.github.i.fuzzybanksearch.matcher.fzf.FuzzyMatcherV1; 4 | import com.github.i.fuzzybanksearch.matcher.fzf.OrderBy; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | import java.util.Set; 9 | import java.util.stream.Collectors; 10 | 11 | public class FZFMatcher extends Matcher { 12 | private final FuzzyMatcherV1 matcher; 13 | 14 | public FZFMatcher(Collection dictionary) { 15 | this.matcher = new FuzzyMatcherV1( 16 | new ArrayList<>(dictionary), 17 | OrderBy.SCORE, 18 | true, 19 | false); 20 | } 21 | 22 | @Override 23 | public Set match(String query, int limit) { 24 | return this.matcher.match(query) 25 | .stream() 26 | .limit(limit) 27 | .collect(Collectors.toSet()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/FuzzyBankSearchConfig.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch; 2 | 3 | import net.runelite.client.config.Config; 4 | import net.runelite.client.config.ConfigGroup; 5 | import net.runelite.client.config.ConfigItem; 6 | import net.runelite.client.config.Keybind; 7 | 8 | import java.awt.event.InputEvent; 9 | import java.awt.event.KeyEvent; 10 | 11 | @ConfigGroup("fuzzybanksearch") 12 | public interface FuzzyBankSearchConfig extends Config 13 | { 14 | @ConfigItem( 15 | keyName = "hotkey", 16 | name = "Hot Key", 17 | description = "Hot key to enable fuzzy searching" 18 | ) 19 | default Keybind hotkey() { return new Keybind(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK); 20 | } 21 | 22 | @ConfigItem( 23 | keyName = "limit", 24 | name = "Limit", 25 | description = "Number of results to return" 26 | ) 27 | default int limit() { return 10; } 28 | 29 | @ConfigItem( 30 | keyName = "useFzf", 31 | name = "Use FZF", 32 | description = "Uses fzf when enabled, jaro winker if disabled" 33 | ) 34 | default boolean useFzf() { return true; } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/fzf/LICENCE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Jan Graßegger 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/test/java/com/github/i/platz/AbbreviationTest.java: -------------------------------------------------------------------------------- 1 | package com.github.i.platz; 2 | 3 | import net.runelite.client.RuneLite; 4 | import net.runelite.client.externalplugins.ExternalPluginManager; 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | 8 | public class AbbreviationTest { 9 | @Test 10 | public void testAbbreviations() { 11 | Assert.assertEquals("1", PlatzPlugin.abbreviateBigNumber(1L)); 12 | Assert.assertEquals("12", PlatzPlugin.abbreviateBigNumber(12L)); 13 | Assert.assertEquals("123", PlatzPlugin.abbreviateBigNumber(123L)); 14 | Assert.assertEquals("1.23K", PlatzPlugin.abbreviateBigNumber(1_234L)); 15 | Assert.assertEquals("12.3K", PlatzPlugin.abbreviateBigNumber(12_345L)); 16 | Assert.assertEquals("123K", PlatzPlugin.abbreviateBigNumber(123_456L)); 17 | Assert.assertEquals("1.23M", PlatzPlugin.abbreviateBigNumber(1_234_567L)); 18 | Assert.assertEquals("12.3M", PlatzPlugin.abbreviateBigNumber(12_345_678L)); 19 | Assert.assertEquals("123M", PlatzPlugin.abbreviateBigNumber(123_456_789L)); 20 | Assert.assertEquals("1.23B", PlatzPlugin.abbreviateBigNumber(1_234_567_891L)); 21 | Assert.assertEquals("12.3B", PlatzPlugin.abbreviateBigNumber(12_345_678_912L)); 22 | Assert.assertEquals("123B", PlatzPlugin.abbreviateBigNumber(123_456_789_123L)); 23 | } 24 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2023, Ian Lozinski 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | 2. Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 19 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 20 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 21 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 22 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 23 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/fzf/ResultComparator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020 Jan Graßegger 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package com.github.i.fuzzybanksearch.matcher.fzf; 24 | 25 | 26 | 27 | import java.util.Comparator; 28 | 29 | public class ResultComparator implements Comparator { 30 | 31 | private final OrderBy orderBy; 32 | 33 | public ResultComparator(final OrderBy orderBy) { 34 | 35 | this.orderBy = orderBy; 36 | } 37 | 38 | @Override 39 | public int compare(Result r1, Result r2) { 40 | if (orderBy == OrderBy.SCORE) { 41 | return Integer.compare(r2.getScore(), r1.getScore()); 42 | } 43 | return Integer.compare(r1.getText().trim().length(), r2.getText().trim().length()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/fzf/Normalizer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020 Jan Graßegger 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package com.github.i.fuzzybanksearch.matcher.fzf; 24 | 25 | import java.util.List; 26 | import java.util.regex.Pattern; 27 | import java.util.stream.Collectors; 28 | 29 | public class Normalizer { 30 | 31 | private static final Pattern diacriticalMarksPattern = Pattern 32 | .compile("\\p{Block=CombiningDiacriticalMarks}+"); 33 | 34 | /** 35 | * Normalizes a string by applying NFKD normalization and removing all diacritical marks 36 | * afterwards. 37 | * 38 | * @param string to be normalized 39 | * @return normalized string 40 | */ 41 | public static String normalize(final String string) { 42 | final var normalizedString = java.text.Normalizer.normalize( 43 | string, java.text.Normalizer.Form.NFKD); 44 | return diacriticalMarksPattern.matcher(normalizedString).replaceAll(""); 45 | } 46 | 47 | public static List normalize(final List strings) { 48 | return strings.parallelStream().map(Normalizer::normalize).collect(Collectors.toList()); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/JaroWinklerMatcher.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch.matcher; 2 | 3 | import org.apache.commons.text.similarity.JaroWinklerDistance; 4 | import org.apache.commons.text.similarity.SimilarityScore; 5 | 6 | import java.util.Collection; 7 | import java.util.Comparator; 8 | import java.util.Set; 9 | import java.util.stream.Collectors; 10 | 11 | public class JaroWinklerMatcher extends Matcher { 12 | private final SimilarityScore baseAlgorithm = new JaroWinklerDistance(); 13 | private final Collection dictionary; 14 | 15 | public JaroWinklerMatcher( Collection dictionary) { 16 | this.dictionary = dictionary; 17 | } 18 | 19 | public Set match(String query, int limit) { 20 | return this.dictionary 21 | .stream() 22 | .map(term -> new MatchResult(term, this.score(query, term))) 23 | .sorted(Comparator.comparingDouble(res -> (-res.getScore()))) 24 | .map(MatchResult::getTerm) 25 | .limit(limit) 26 | .collect(Collectors.toSet()); 27 | } 28 | 29 | private Double score(String query, String itemName) { 30 | query = query.toLowerCase().replace('-', ' '); 31 | itemName = itemName.toLowerCase().replace('-', ' '); 32 | 33 | // we raise the score for items that share a prefix with the query 34 | int prefixLen = 0; 35 | int maxLen = Math.min(query.length(), itemName.length()); 36 | while (prefixLen < maxLen && query.charAt(prefixLen) == itemName.charAt(prefixLen)) 37 | { 38 | prefixLen++; 39 | } 40 | double prefixScore = ((double) prefixLen) / query.length() - 0.25; 41 | 42 | // and also raise the score for string "closeness" 43 | double proximityScore = baseAlgorithm.apply(query, itemName) - 0.25; 44 | return prefixScore + proximityScore; 45 | } 46 | 47 | private static class MatchResult { 48 | private final String term; 49 | private final double score; 50 | 51 | public MatchResult(String term, double score) { 52 | this.term = term; 53 | this.score = score; 54 | } 55 | 56 | public double getScore() { 57 | return this.score; 58 | } 59 | 60 | public String getTerm() { 61 | return this.term; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/fzf/Result.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2020 Jan Graßegger 3 | * 4 | * Permission is hereby granted, free of charge, to any person obtaining a copy 5 | * of this software and associated documentation files (the "Software"), to deal 6 | * in the Software without restriction, including without limitation the rights 7 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | * copies of the Software, and to permit persons to whom the Software is 9 | * furnished to do so, subject to the following conditions: 10 | * 11 | * The above copyright notice and this permission notice shall be included in all 12 | * copies or substantial portions of the Software. 13 | * 14 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | * SOFTWARE. 21 | */ 22 | 23 | package com.github.i.fuzzybanksearch.matcher.fzf; 24 | 25 | import java.util.Arrays; 26 | 27 | public class Result { 28 | 29 | public static Result empty(final String text, int itemIndex) { 30 | return new Result(text, 0, 0, 0, null, itemIndex); 31 | } 32 | 33 | public static Result noMatch(final String text, int itemIndex) { 34 | return new Result(text, -1, -1, 0, null, itemIndex); 35 | } 36 | 37 | private final String text; 38 | private final int start; 39 | private final int end; 40 | private final int score; 41 | private final int[] positions; 42 | private final int itemIndex; 43 | 44 | public Result(String text, int start, int end, int score, int[] positions, int itemIndex) { 45 | this.text = text; 46 | this.start = start; 47 | this.end = end; 48 | this.score = score; 49 | this.positions = positions; 50 | this.itemIndex = itemIndex; 51 | } 52 | 53 | public String getText() { 54 | return text; 55 | } 56 | 57 | public int getStart() { 58 | return start; 59 | } 60 | 61 | public int getEnd() { 62 | return end; 63 | } 64 | 65 | public int getScore() { 66 | return score; 67 | } 68 | 69 | public int[] getPositions() { 70 | return positions; 71 | } 72 | 73 | public boolean isMatch() { 74 | return start != -1 && end != -1; 75 | } 76 | 77 | public int getItemIndex() { 78 | return itemIndex; 79 | } 80 | 81 | @Override 82 | public String toString() { 83 | return "Result{" 84 | + "text='" + text + '\'' 85 | + ", start=" + start 86 | + ", end=" + end 87 | + ", score=" + score 88 | + ", positions=" + Arrays.toString(positions) 89 | + ", itemIndex=" + itemIndex 90 | + '}'; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/platz/PlatzPlugin.java: -------------------------------------------------------------------------------- 1 | package com.github.i.platz; 2 | 3 | import com.google.common.annotations.VisibleForTesting; 4 | import com.google.inject.Provides; 5 | import lombok.extern.slf4j.Slf4j; 6 | import net.runelite.api.Client; 7 | import net.runelite.api.InventoryID; 8 | import net.runelite.api.Item; 9 | import net.runelite.api.events.ItemContainerChanged; 10 | import net.runelite.client.config.ConfigManager; 11 | import net.runelite.client.eventbus.Subscribe; 12 | import net.runelite.client.game.ItemManager; 13 | import net.runelite.client.plugins.Plugin; 14 | import net.runelite.client.plugins.PluginDescriptor; 15 | 16 | import javax.inject.Inject; 17 | import java.text.DecimalFormat; 18 | 19 | @Slf4j 20 | @PluginDescriptor(name = "platz") 21 | public class PlatzPlugin extends Plugin { 22 | @Inject 23 | private Client client; 24 | 25 | @Inject 26 | private ItemManager itemManager; 27 | 28 | 29 | @Override 30 | protected void startUp() { 31 | } 32 | 33 | @Override 34 | protected void shutDown() { 35 | } 36 | 37 | @Inject 38 | PlatzConfig config; 39 | 40 | @Provides 41 | PlatzConfig provideConfig(ConfigManager configManager) { 42 | return configManager.getConfig(PlatzConfig.class); 43 | } 44 | 45 | private static final int MY_TRADE_VALUE_WIDGET_ID = 21954584; 46 | private static final int OTHER_TRADE_VALUE_WIDGET_ID = 21954587; 47 | 48 | 49 | @Subscribe 50 | public void onItemContainerChanged(ItemContainerChanged event) { 51 | var inventoryId = event.getContainerId(); 52 | int widgetIdToUpdate; 53 | 54 | if (inventoryId == InventoryID.TRADEOTHER.getId()) { 55 | widgetIdToUpdate = OTHER_TRADE_VALUE_WIDGET_ID; 56 | } else if (inventoryId == InventoryID.TRADE.getId()) { 57 | widgetIdToUpdate = MY_TRADE_VALUE_WIDGET_ID; 58 | } else { 59 | return; 60 | } 61 | 62 | var total = 0L; 63 | for (Item item : client.getItemContainer(inventoryId).getItems()) { 64 | total += (long) this.itemManager.getItemPrice(item.getId()) * (long) item.getQuantity(); 65 | } 66 | 67 | setTradeValueText(widgetIdToUpdate, total); 68 | } 69 | 70 | 71 | private void setTradeValueText(int widgetId, long value) { 72 | var formattedNumber = (this.config.abbreviate() && value > this.config.largeNumberCutoff()) 73 | ? abbreviateBigNumber(value) 74 | : String.format("%,d", value); 75 | 76 | var msg = String.format( 77 | "%s offer:
(Value: %s coins)", 78 | widgetId == MY_TRADE_VALUE_WIDGET_ID ? "Your" : "Their", 79 | formattedNumber); 80 | client.getWidget(widgetId).setText(msg); 81 | } 82 | 83 | 84 | 85 | private static String[] suffix = new String[]{"","K", "M", "B", "T"}; 86 | private static final int MAX_SHORT_LENGTH = 10; 87 | 88 | @VisibleForTesting 89 | public static String abbreviateBigNumber(long number) { 90 | String r = new DecimalFormat("##0E0").format(number); 91 | r = r.replaceAll("E[0-9]", suffix[Character.getNumericValue(r.charAt(r.length() - 1)) / 3]); 92 | while (r.length() > MAX_SHORT_LENGTH || r.matches("[0-9]+\\.[a-z]")) { 93 | r = r.substring(0, r.length() - 2) + r.substring(r.length() - 1); 94 | } 95 | return r; 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/FuzzyBankSearchPlugin.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch; 2 | 3 | import com.github.i.fuzzybanksearch.matcher.FZFMatcher; 4 | import com.github.i.fuzzybanksearch.matcher.JaroWinklerMatcher; 5 | import com.github.i.fuzzybanksearch.matcher.Matcher; 6 | import com.github.i.fuzzybanksearch.matcher.fzf.FuzzyMatcherV1; 7 | import com.github.i.fuzzybanksearch.matcher.fzf.OrderBy; 8 | import com.google.inject.Provides; 9 | import lombok.extern.slf4j.Slf4j; 10 | import net.runelite.api.Client; 11 | import net.runelite.api.InventoryID; 12 | import net.runelite.api.ItemComposition; 13 | import net.runelite.api.ItemContainer; 14 | import net.runelite.api.events.ItemContainerChanged; 15 | import net.runelite.api.events.ScriptCallbackEvent; 16 | import net.runelite.api.widgets.Widget; 17 | import net.runelite.api.widgets.WidgetInfo; 18 | import net.runelite.client.config.ConfigManager; 19 | import net.runelite.client.eventbus.Subscribe; 20 | import net.runelite.client.game.ItemManager; 21 | import net.runelite.client.input.KeyListener; 22 | import net.runelite.client.input.KeyManager; 23 | import net.runelite.client.plugins.Plugin; 24 | import net.runelite.client.plugins.PluginDescriptor; 25 | import net.runelite.client.plugins.bank.BankSearch; 26 | 27 | import javax.inject.Inject; 28 | import java.awt.event.KeyEvent; 29 | import java.util.ArrayList; 30 | import java.util.Arrays; 31 | import java.util.Map; 32 | import java.util.Set; 33 | import java.util.stream.Collectors; 34 | 35 | @Slf4j 36 | @PluginDescriptor(name = "Fuzzy Bank Search") 37 | public class FuzzyBankSearchPlugin extends Plugin { 38 | @Inject 39 | private Client client; 40 | 41 | @Inject 42 | private FuzzyBankSearchConfig config; 43 | 44 | @Inject 45 | private KeyManager keyManager; 46 | 47 | @Inject 48 | BankSearch bankSearch; 49 | 50 | @Inject 51 | ItemManager itemManager; 52 | 53 | @Override 54 | protected void startUp() { 55 | keyManager.registerKeyListener(searchHotkeyListener); 56 | } 57 | 58 | @Override 59 | protected void shutDown() { 60 | keyManager.unregisterKeyListener(searchHotkeyListener); 61 | } 62 | 63 | @Provides 64 | FuzzyBankSearchConfig provideConfig(ConfigManager configManager) { 65 | return configManager.getConfig(FuzzyBankSearchConfig.class); 66 | } 67 | 68 | private final static String BANK_SEARCH_FILTER_EVENT = "bankSearchFilter"; 69 | 70 | // these two fields are used to cache results 71 | String oldQuery = ""; 72 | Set cachedResults = null; 73 | 74 | private Matcher fzfMatcher = null; 75 | private Matcher jaroWinklerMatcher = null; 76 | 77 | @Subscribe 78 | public void onItemContainerChanged(ItemContainerChanged event) { 79 | // reindex every time the bank is opened 80 | if (event.getContainerId() == InventoryID.BANK.getId()) { 81 | this.itemIdsToNames = Arrays.stream(client.getItemContainer(InventoryID.BANK).getItems()) 82 | .map(item -> this.itemManager.getItemComposition(item.getId())) 83 | .collect(Collectors.toMap( 84 | ItemComposition::getId, 85 | ItemComposition::getName, 86 | (x, __) -> x)); 87 | 88 | this.fzfMatcher = new FZFMatcher(this.itemIdsToNames.values()); 89 | this.jaroWinklerMatcher = new JaroWinklerMatcher(this.itemIdsToNames.values()); 90 | } 91 | } 92 | 93 | private Map itemIdsToNames = null; 94 | 95 | 96 | public boolean filterBankSearch(final int itemId, final String query) { 97 | if (query.equals("")) { 98 | return true; 99 | } 100 | 101 | // previous results are cached until in text input changes. 102 | // the client will try to update every 40ms 103 | if (!oldQuery.equals(query) || cachedResults == null) { 104 | Matcher matcher; 105 | if (config.useFzf()) { 106 | matcher = fzfMatcher; 107 | } else { 108 | matcher = jaroWinklerMatcher; 109 | } 110 | 111 | this.cachedResults = matcher.match(query, config.limit()); 112 | oldQuery = query; 113 | } 114 | 115 | return cachedResults.contains(itemIdsToNames.get(itemId)); 116 | } 117 | 118 | private final KeyListener searchHotkeyListener = new KeyListener() { 119 | @Override 120 | public void keyPressed(KeyEvent e) { 121 | if (config.hotkey().matches(e)) { 122 | Widget bankContainer = client.getWidget(WidgetInfo.BANK_ITEM_CONTAINER); 123 | if (bankContainer != null && !bankContainer.isSelfHidden()) 124 | { 125 | bankSearch.initSearch(); 126 | e.consume(); 127 | } 128 | } 129 | } 130 | 131 | @Override 132 | public void keyTyped(KeyEvent e) { } 133 | 134 | @Override 135 | public void keyReleased(KeyEvent e) { } 136 | }; 137 | 138 | 139 | @Subscribe 140 | public void onScriptCallbackEvent(ScriptCallbackEvent event) { 141 | int[] intStack = client.getIntStack(); 142 | String[] stringStack = client.getStringStack(); 143 | int intStackSize = client.getIntStackSize(); 144 | int stringStackSize = client.getStringStackSize(); 145 | 146 | if (event.getEventName().equals(BANK_SEARCH_FILTER_EVENT)) { 147 | int itemId = intStack[intStackSize - 1]; 148 | String query = stringStack[stringStackSize - 1]; 149 | intStack[intStackSize - 2] = filterBankSearch(itemId, query) ? 1 : 0; 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /src/main/java/com/github/i/fuzzybanksearch/matcher/fzf/FuzzyMatcherV1.java: -------------------------------------------------------------------------------- 1 | package com.github.i.fuzzybanksearch.matcher.fzf; 2 | 3 | /* 4 | * Copyright (c) 2020 Jan Graßegger 5 | * 6 | * Permission is hereby granted, free of charge, to any person obtaining a copy 7 | * of this software and associated documentation files (the "Software"), to deal 8 | * in the Software without restriction, including without limitation the rights 9 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | * copies of the Software, and to permit persons to whom the Software is 11 | * furnished to do so, subject to the following conditions: 12 | * 13 | * The above copyright notice and this permission notice shall be included in all 14 | * copies or substantial portions of the Software. 15 | * 16 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | * SOFTWARE. 23 | */ 24 | 25 | 26 | 27 | import java.util.List; 28 | import java.util.stream.Collectors; 29 | import java.util.stream.IntStream; 30 | 31 | 32 | /** 33 | * Class to filter and rank and items 34 | * Based on: https://github.com/junegunn/fzf/blob/master/src/algo/algo.go 35 | */ 36 | public class FuzzyMatcherV1 { 37 | 38 | static final int SCORE_MATCH = 16; 39 | static final int SCORE_GAP_START = -3; 40 | static final int SCORE_GAP_EXTENSION = -1; 41 | 42 | static final int BONUS_BOUNDARY = SCORE_MATCH / 2; 43 | static final int BONUS_NON_WORD = SCORE_MATCH / 2; 44 | static final int BONUS_CAMEL_123 = BONUS_BOUNDARY + SCORE_GAP_EXTENSION; 45 | static final int BONUS_CONSECUTIVE = -(SCORE_GAP_START + SCORE_GAP_EXTENSION); 46 | static final int BONUS_FIRST_CHAR_MULTIPLIER = 2; 47 | 48 | private final List items; 49 | private final OrderBy orderBy; 50 | private final boolean normalize; 51 | private final List normalizedItems; 52 | private final boolean caseSensitive; 53 | 54 | public FuzzyMatcherV1( 55 | final List items, 56 | final OrderBy orderBy, 57 | final boolean normalize, 58 | final boolean caseSensitive 59 | ) { 60 | this.items = items; 61 | this.orderBy = orderBy; 62 | this.normalize = normalize; 63 | this.normalizedItems = normalize ? Normalizer.normalize(items) : items; 64 | this.caseSensitive = caseSensitive; 65 | } 66 | 67 | public List match(final String pattern) { 68 | if (pattern.isEmpty()) { 69 | return items; 70 | } 71 | 72 | final var lowercasePattern = caseSensitive ? pattern : pattern.toLowerCase(); 73 | final var normalizedPattern = normalize ? Normalizer.normalize(lowercasePattern) 74 | : lowercasePattern; 75 | 76 | return IntStream.range(0, items.size()).parallel() 77 | .mapToObj(i -> match(items.get(i), normalizedItems.get(i), normalizedPattern, i)) 78 | .filter(Result::isMatch) 79 | .sorted(new ResultComparator(orderBy)) 80 | .map(Result::getText) 81 | .collect(Collectors.toList()); 82 | } 83 | 84 | private Result match( 85 | final String text, 86 | final String normalizedText, 87 | final String pattern, 88 | final int itemIndex 89 | ) { 90 | var queryIndex = 0; 91 | var startIndex = -1; 92 | var endIndex = -1; 93 | 94 | for (int textIndex = 0; textIndex < normalizedText.length(); textIndex++) { 95 | var textChar = normalizedText.charAt(textIndex); 96 | final char queryChar = pattern.charAt(queryIndex); 97 | 98 | final var charClass = CharClass.forChar(textChar); 99 | 100 | if (!caseSensitive && charClass == CharClass.UPPER) { 101 | textChar = Character.toLowerCase(textChar); 102 | } 103 | 104 | if (textChar == queryChar) { 105 | 106 | if (startIndex == -1) { 107 | startIndex = textIndex; 108 | } 109 | 110 | if (queryIndex == pattern.length() - 1) { 111 | endIndex = textIndex + 1; 112 | break; 113 | } 114 | 115 | queryIndex++; 116 | } 117 | } 118 | 119 | if (startIndex != -1 && endIndex != -1) { 120 | for (int textIndex = endIndex - 1; textIndex > startIndex; textIndex--) { 121 | final var textChar = normalizedText.charAt(textIndex); 122 | final var queryChar = pattern.charAt(queryIndex); 123 | 124 | if (textChar == queryChar) { 125 | if (queryIndex == 0) { 126 | startIndex = textIndex; 127 | break; 128 | } 129 | 130 | queryIndex--; 131 | } 132 | } 133 | 134 | return calculateScore(text, normalizedText, pattern, startIndex, endIndex, itemIndex); 135 | } 136 | 137 | return Result.noMatch(text, itemIndex); 138 | } 139 | 140 | private Result calculateScore( 141 | final String text, 142 | final String normalizedText, 143 | final String pattern, 144 | final int startIndex, 145 | final int endIndex, 146 | final int itemIndex 147 | ) { 148 | var patternIndex = 0; 149 | var score = 0; 150 | var consecutive = 0; 151 | var firstBonus = 0; 152 | var inGap = false; 153 | var pos = new int[pattern.length()]; 154 | 155 | var prevClass = startIndex > 0 ? CharClass.forChar(normalizedText.charAt(startIndex - 1)) 156 | : CharClass.NON_WORD; 157 | 158 | for (var i = startIndex; i < endIndex; i++) { 159 | var c = normalizedText.charAt(i); 160 | final var charClass = CharClass.forChar(c); 161 | 162 | if (!caseSensitive && charClass == CharClass.UPPER) { 163 | c = Character.toLowerCase(c); 164 | } 165 | 166 | if (c == pattern.charAt(patternIndex)) { 167 | pos[patternIndex] = i; 168 | 169 | score += SCORE_MATCH; 170 | var bonus = bonusFor(prevClass, charClass); 171 | 172 | if (consecutive == 0) { 173 | firstBonus += bonus; 174 | } else { 175 | // Break consecutive chunk 176 | if (bonus == BONUS_BOUNDARY) { 177 | firstBonus = bonus; 178 | } 179 | bonus = Math.max(Math.max(bonus, firstBonus), BONUS_CONSECUTIVE); 180 | } 181 | 182 | if (patternIndex == 0) { 183 | score += bonus * BONUS_FIRST_CHAR_MULTIPLIER; 184 | } else { 185 | score += bonus; 186 | } 187 | inGap = false; 188 | consecutive++; 189 | patternIndex++; 190 | } else { 191 | if (inGap) { 192 | score += SCORE_GAP_EXTENSION; 193 | } else { 194 | score += SCORE_GAP_START; 195 | } 196 | 197 | inGap = true; 198 | consecutive = 0; 199 | firstBonus = 0; 200 | } 201 | prevClass = charClass; 202 | } 203 | 204 | return new Result(text, startIndex, endIndex, score, pos, itemIndex); 205 | } 206 | 207 | private int bonusFor(CharClass prevClass, CharClass charClass) { 208 | if (prevClass == CharClass.NON_WORD && charClass != CharClass.NON_WORD) { 209 | return BONUS_BOUNDARY; 210 | } else if (prevClass == CharClass.LOWER && charClass == CharClass.UPPER 211 | || prevClass != CharClass.NUMBER && charClass == CharClass.NUMBER) { 212 | // camelCase letter123 213 | return BONUS_CAMEL_123; 214 | } else if (charClass == CharClass.NON_WORD) { 215 | return BONUS_NON_WORD; 216 | } 217 | return 0; 218 | } 219 | 220 | private enum CharClass { 221 | LOWER, UPPER, LETTER, NUMBER, NON_WORD; 222 | 223 | public static CharClass forChar(char c) { 224 | if (Character.isLowerCase(c)) { 225 | return LOWER; 226 | } else if (Character.isUpperCase(c)) { 227 | return UPPER; 228 | } else if (Character.isDigit(c)) { 229 | return NUMBER; 230 | } else if (Character.isLetter(c)) { 231 | return LETTER; 232 | } 233 | return NON_WORD; 234 | } 235 | } 236 | } --------------------------------------------------------------------------------