repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/events/types/JadxGuiEventsImpl.java
jadx-gui/src/main/java/jadx/gui/events/types/JadxGuiEventsImpl.java
package jadx.gui.events.types; import java.util.function.Consumer; import jadx.api.plugins.events.IJadxEvent; import jadx.api.plugins.events.IJadxEvents; import jadx.api.plugins.events.JadxEventType; import jadx.core.plugins.events.JadxEventsImpl; /** * Special events implementation to operate on both: global UI and project events. * Project events hold listeners only while a project opened and reset them on close. */ public class JadxGuiEventsImpl implements IJadxEvents { private final IJadxEvents global = new JadxEventsImpl(); private final IJadxEvents project = new JadxEventsImpl(); public IJadxEvents global() { return global; } @Override public void send(IJadxEvent event) { global.send(event); project.send(event); } @Override public <E extends IJadxEvent> void addListener(JadxEventType<E> eventType, Consumer<E> listener) { project.addListener(eventType, listener); } @Override public <E extends IJadxEvent> void removeListener(JadxEventType<E> eventType, Consumer<E> listener) { project.removeListener(eventType, listener); } @Override public void reset() { project.reset(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/report/ExceptionDialog.java
jadx-gui/src/main/java/jadx/gui/report/ExceptionDialog.java
package jadx.gui.report; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JadxDecompiler; import jadx.cli.config.JadxConfigAdapter; import jadx.commons.app.JadxSystemInfo; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.JadxSettingsData; import jadx.gui.ui.MainWindow; import jadx.gui.utils.LafManager; import jadx.gui.utils.Link; import jadx.gui.utils.TextStandardActions; public class ExceptionDialog extends JDialog { private static final Logger LOG = LoggerFactory.getLogger(ExceptionDialog.class); private static final String FMT_DETAIL_LENGTH = "-13"; ExceptionDialog(MainWindow mainWindow, ExceptionData data) { super(mainWindow, "Jadx Error"); this.getContentPane().setLayout(new BorderLayout()); JPanel titlePanel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.CENTER; c.gridx = 0; c.weightx = 1.0; c.insets = new Insets(2, 5, 5, 5); JLabel titleLabel = new JLabel("<html><h1>An error occurred</h1><p>Jadx encountered an unexpected error.</p></html>"); Map<String, String> details = new LinkedHashMap<>(); details.put("Jadx version", JadxDecompiler.getVersion()); details.put("Java version", JadxSystemInfo.JAVA_VER); details.put("Java VM", String.format("%s %s", System.getProperty("java.vm.vendor", "?"), System.getProperty("java.vm.name", "?"))); details.put("Platform", String.format("%s (%s %s)", JadxSystemInfo.OS_NAME, JadxSystemInfo.OS_VERSION, JadxSystemInfo.OS_ARCH)); Runtime runtime = Runtime.getRuntime(); details.put("Max heap size", String.format("%d MB", runtime.maxMemory() / (1024 * 1024))); try { // TODO: Use ProcessHandle.current().info().commandLine() once min Java is 9+ List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments(); details.put("Program args", String.join(" ", args)); } catch (Throwable t) { LOG.error("failed to get program arguments", t); } Throwable ex = data.getException(); StringWriter stackTraceWriter = new StringWriter(1024); ex.printStackTrace(new PrintWriter(stackTraceWriter)); final String stackTrace = stackTraceWriter.toString(); String issueTitle; try { issueTitle = URLEncoder.encode(ex.toString(), StandardCharsets.UTF_8); } catch (Exception e) { LOG.error("URL encoding of title failed", e); issueTitle = ex.getClass().getSimpleName(); } String message = "Please describe what you did before the error occurred.\n\n"; message += "**IMPORTANT!** If the error occurs with a specific APK file please attach or provide link to apk file!\n\n"; StringBuilder detailsIssueBuilder = new StringBuilder(); details.forEach((key, value) -> detailsIssueBuilder.append(String.format("* %s: %s\n", key, value))); String body = String.format("%s%s\n```\n%s\n```", message, detailsIssueBuilder, stackTrace); String issueBody; try { issueBody = URLEncoder.encode(body, StandardCharsets.UTF_8); } catch (Exception e) { LOG.error("URL encoding of body failed", e); issueBody = "Please copy the displayed text in the Jadx error dialog and paste it here"; } c.gridy = 0; titlePanel.add(titleLabel, c); String project = data.getGithubProject(); if (!project.isEmpty()) { String url = String.format("https://github.com/%s/issues/new?labels=bug&title=%s&body=%s", project, issueTitle, issueBody); Link issueLink = new Link("<html><u><b>Create a new issue at GitHub</b></u></html>", url); c.gridy = 1; titlePanel.add(issueLink, c); } JTextArea messageArea = new JTextArea(); TextStandardActions.attach(messageArea); messageArea.setEditable(false); messageArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); messageArea.setForeground(Color.BLACK); messageArea.setBackground(Color.WHITE); StringBuilder detailsTextBuilder = new StringBuilder(); details.forEach((key, value) -> detailsTextBuilder.append(String.format("%" + FMT_DETAIL_LENGTH + "s: %s\n", key, value))); messageArea.setText(detailsTextBuilder + "\n" + stackTrace); JPanel buttonPanel = new JPanel(); JButton exitButton = new JButton("Terminate Jadx"); exitButton.addActionListener(event -> System.exit(1)); buttonPanel.add(exitButton); JButton closeButton = new JButton("Go back to Jadx"); closeButton.addActionListener(event -> setVisible(false)); buttonPanel.add(closeButton); JScrollPane messageAreaScroller = new JScrollPane(messageArea); messageAreaScroller.setMinimumSize(new Dimension(600, 400)); messageAreaScroller.setPreferredSize(new Dimension(600, 400)); this.add(titlePanel, BorderLayout.NORTH); this.add(messageAreaScroller, BorderLayout.CENTER); this.add(buttonPanel, BorderLayout.SOUTH); this.pack(); javax.swing.SwingUtilities.invokeLater(() -> messageAreaScroller.getVerticalScrollBar().setValue(0)); final Toolkit toolkit = Toolkit.getDefaultToolkit(); final Dimension screenSize = toolkit.getScreenSize(); final int x = (screenSize.width - getWidth()) / 2; final int y = (screenSize.height - getHeight()) / 2; setLocation(x, y); getRootPane().registerKeyboardAction(event -> setVisible(false), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.setVisible(true); } public static void throwTestException() { try { throw new RuntimeException("Inner exception message"); } catch (Exception e) { throw new JadxRuntimeException("Outer exception message", e); } } public static void showTestExceptionDialog() { try { throwTestException(); } catch (Exception e) { new ExceptionDialog(null, new ExceptionData(e, JadxExceptionHandler.MAIN_PROJECT_STRING)); } } public static void main(String[] args) { JadxConfigAdapter<JadxSettingsData> configAdapter = JadxSettings.buildConfigAdapter(); configAdapter.useConfigRef(""); JadxSettingsData settingsData = configAdapter.load(); if (settingsData != null) { JadxSettings settings = new JadxSettings(configAdapter); settings.loadSettingsData(settingsData); LafManager.init(settings); } showTestExceptionDialog(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/report/ExceptionData.java
jadx-gui/src/main/java/jadx/gui/report/ExceptionData.java
package jadx.gui.report; final class ExceptionData { private final Throwable exception; private final String githubProject; ExceptionData(Throwable exception, String githubProject) { this.exception = exception; this.githubProject = githubProject; } public Throwable getException() { return exception; } public String getGithubProject() { return githubProject; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/report/JadxExceptionHandler.java
jadx-gui/src/main/java/jadx/gui/report/JadxExceptionHandler.java
package jadx.gui.report; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.ui.MainWindow; import jadx.plugins.tools.JadxPluginsTools; import jadx.plugins.tools.data.JadxPluginMetadata; import static jadx.plugins.tools.JadxExternalPluginsLoader.JADX_PLUGIN_CLASSLOADER_PREFIX; public class JadxExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger LOG = LoggerFactory.getLogger(JadxExceptionHandler.class); public static final String MAIN_PROJECT_STRING = "skylot/jadx"; public static void register(MainWindow mainWindow) { Thread.setDefaultUncaughtExceptionHandler(new JadxExceptionHandler(mainWindow)); } private final MainWindow mainWindow; private JadxExceptionHandler(MainWindow mainWindow) { this.mainWindow = mainWindow; } @Override public void uncaughtException(Thread thread, Throwable ex) { LOG.error("Exception was thrown", ex); new ExceptionDialog(mainWindow, buildExceptionData(ex)); } private ExceptionData buildExceptionData(Throwable ex) { for (StackTraceElement stackTraceElement : ex.getStackTrace()) { String classLoaderName = stackTraceElement.getClassLoaderName(); if (classLoaderName != null && classLoaderName.startsWith(JADX_PLUGIN_CLASSLOADER_PREFIX)) { // plugin exception String jarName = classLoaderName.substring(JADX_PLUGIN_CLASSLOADER_PREFIX.length()); String pluginProject = resolvePluginByJarName(jarName); LOG.debug("Report exception in plugin: {}", pluginProject); return new ExceptionData(ex, pluginProject); } } return new ExceptionData(ex, MAIN_PROJECT_STRING); } private String resolvePluginByJarName(String jarName) { for (JadxPluginMetadata jadxPluginMetadata : JadxPluginsTools.getInstance().getInstalled()) { if (jadxPluginMetadata.getJar().equals(jarName)) { String githubProject = getGithubProject(jadxPluginMetadata.getLocationId()); return githubProject != null ? githubProject : ""; } } return ""; } private static @Nullable String getGithubProject(String locationId) { if (locationId.startsWith("github:")) { return locationId.substring("github:".length()).replace(':', '/'); } return null; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/SearchSettings.java
jadx-gui/src/main/java/jadx/gui/search/SearchSettings.java
package jadx.gui.search; import java.util.regex.Pattern; import org.jetbrains.annotations.Nullable; import jadx.api.JadxDecompiler; import jadx.api.JavaClass; import jadx.api.JavaPackage; import jadx.core.dex.nodes.PackageNode; import jadx.core.utils.exceptions.InvalidDataException; import jadx.gui.search.providers.ResourceFilter; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JResource; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; public class SearchSettings { private final String searchString; private boolean useRegex; private boolean ignoreCase; private String searchPkgStr; private String resFilterStr; private int resSizeLimit; // in MB private JClass activeCls; private JResource activeResource; private Pattern regexPattern; private ISearchMethod searchMethod; private JavaPackage searchPackage; private ResourceFilter resourceFilter; public SearchSettings(String searchString) { this.searchString = searchString; } public @Nullable String prepare(MainWindow mainWindow) { if (useRegex) { try { int flags = ignoreCase ? Pattern.CASE_INSENSITIVE : 0; this.regexPattern = Pattern.compile(searchString, flags); } catch (Exception e) { return "Invalid Regex: " + e.getMessage(); } } if (!searchPkgStr.isBlank()) { JadxDecompiler decompiler = mainWindow.getWrapper().getDecompiler(); PackageNode pkg = decompiler.getRoot().resolvePackage(searchPkgStr); if (pkg == null) { return NLS.str("search_dialog.package_not_found"); } searchPackage = pkg.getJavaNode(); } searchMethod = ISearchMethod.build(this); try { resourceFilter = ResourceFilter.parse(resFilterStr); } catch (InvalidDataException e) { return "Invalid resource file filter: " + e.getMessage(); } return null; } public boolean isMatch(String searchArea) { return searchMethod.find(searchArea, this.searchString, 0) != -1; } public boolean isUseRegex() { return this.useRegex; } public void setUseRegex(boolean useRegex) { this.useRegex = useRegex; } public boolean isIgnoreCase() { return this.ignoreCase; } public void setIgnoreCase(boolean ignoreCase) { this.ignoreCase = ignoreCase; } public JavaPackage getSearchPackage() { return this.searchPackage; } public boolean isInSearchPkg(JavaClass cls) { return cls.getJavaPackage().isDescendantOf(searchPackage); } public void setSearchPkgStr(String searchPkgStr) { this.searchPkgStr = searchPkgStr; } public String getSearchString() { return this.searchString; } public Pattern getPattern() { return this.regexPattern; } public JClass getActiveCls() { return activeCls; } public void setActiveCls(JClass activeCls) { this.activeCls = activeCls; } public JResource getActiveResource() { return activeResource; } public void setActiveResource(JResource activeResource) { this.activeResource = activeResource; } public ISearchMethod getSearchMethod() { return searchMethod; } public void setResFilterStr(String resFilterStr) { this.resFilterStr = resFilterStr; } public ResourceFilter getResourceFilter() { return resourceFilter; } public int getResSizeLimit() { return resSizeLimit; } public void setResSizeLimit(int resSizeLimit) { this.resSizeLimit = resSizeLimit; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/SearchJob.java
jadx-gui/src/main/java/jadx/gui/search/SearchJob.java
package jadx.gui.search; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.treemodel.JNode; public class SearchJob implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(SearchJob.class); private final SearchTask searchTask; private final ISearchProvider provider; public SearchJob(SearchTask task, ISearchProvider provider) { this.searchTask = task; this.provider = provider; } @Override public void run() { while (true) { try { JNode result = provider.next(searchTask); if (result == null) { return; } if (searchTask.addResult(result)) { return; } } catch (Exception e) { LOG.warn("Search error, provider: {}", provider.getClass().getSimpleName(), e); return; } } } public ISearchProvider getProvider() { return provider; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/ISearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/ISearchProvider.java
package jadx.gui.search; import org.jetbrains.annotations.Nullable; import jadx.gui.jobs.Cancelable; import jadx.gui.jobs.ITaskProgress; import jadx.gui.treemodel.JNode; public interface ISearchProvider extends ITaskProgress { /** * Return next result or null if search complete */ @Nullable JNode next(Cancelable cancelable); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/SearchTask.java
jadx-gui/src/main/java/jadx/gui/search/SearchTask.java
package jadx.gui.search; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.utils.tasks.ITaskExecutor; import jadx.core.utils.tasks.TaskExecutor; import jadx.gui.jobs.BackgroundExecutor; import jadx.gui.jobs.CancelableBackgroundTask; import jadx.gui.jobs.ITaskInfo; import jadx.gui.jobs.ITaskProgress; import jadx.gui.jobs.TaskProgress; import jadx.gui.jobs.TaskStatus; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; public class SearchTask extends CancelableBackgroundTask { private static final Logger LOG = LoggerFactory.getLogger(SearchTask.class); private final BackgroundExecutor backgroundExecutor; private final Consumer<JNode> resultsListener; private final BiConsumer<ITaskInfo, Boolean> onFinish; private final List<SearchJob> jobs = new ArrayList<>(); private final TaskProgress taskProgress = new TaskProgress(); private final AtomicInteger resultsCount = new AtomicInteger(0); private int resultsLimit; private Future<TaskStatus> future; private Consumer<ITaskProgress> progressListener; public SearchTask(MainWindow mainWindow, Consumer<JNode> results, BiConsumer<ITaskInfo, Boolean> onFinish) { this.backgroundExecutor = mainWindow.getBackgroundExecutor(); this.resultsListener = results; this.onFinish = onFinish; } public void addProviderJob(ISearchProvider provider) { jobs.add(new SearchJob(this, provider)); } public void setResultsLimit(int limit) { this.resultsLimit = limit; } public synchronized void fetchResults() { if (future != null) { throw new IllegalStateException("Previous task not yet finished"); } resetCancel(); resultsCount.set(0); taskProgress.updateTotal(jobs.stream().mapToInt(s -> s.getProvider().total()).sum()); future = backgroundExecutor.executeWithFuture(this); } public synchronized boolean addResult(JNode resultNode) { if (isCanceled()) { // ignore new results after cancel return true; } this.resultsListener.accept(resultNode); if (resultsLimit != 0 && resultsCount.incrementAndGet() >= resultsLimit) { cancel(); return true; } return false; } public synchronized void waitTask() { if (future == null) { return; } try { future.get(200, TimeUnit.MILLISECONDS); } catch (Exception e) { LOG.warn("Search task wait error", e); future.cancel(true); } finally { future = null; } } @Override public String getTitle() { return NLS.str("search_dialog.tip_searching"); } @Override public ITaskExecutor scheduleTasks() { TaskExecutor executor = new TaskExecutor(); executor.addParallelTasks(jobs); return executor; } @Override public void onFinish(ITaskInfo task) { boolean complete = !isCanceled() && task.getStatus() == TaskStatus.COMPLETE && task.getJobsComplete() == task.getJobsCount(); this.onFinish.accept(task, complete); } @Override public boolean checkMemoryUsage() { return true; } @Override public @NotNull ITaskProgress getTaskProgress() { taskProgress.updateProgress(jobs.stream().mapToInt(s -> s.getProvider().progress()).sum()); return taskProgress; } public void setProgressListener(Consumer<ITaskProgress> progressListener) { this.progressListener = progressListener; } @Override public @Nullable Consumer<ITaskProgress> getProgressListener() { return this.progressListener; } @Override public int getCancelTimeoutMS() { return 0; } @Override public int getShutdownTimeoutMS() { return 10; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/ISearchMethod.java
jadx-gui/src/main/java/jadx/gui/search/ISearchMethod.java
package jadx.gui.search; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; public interface ISearchMethod { int find(String input, String subStr, int start); static ISearchMethod build(SearchSettings searchSettings) { if (searchSettings.isUseRegex()) { Pattern pattern = searchSettings.getPattern(); return (input, subStr, start) -> { Matcher matcher = pattern.matcher(input); if (matcher.find(start)) { return matcher.start(); } return -1; }; } if (searchSettings.isIgnoreCase()) { return StringUtils::indexOfIgnoreCase; } return String::indexOf; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/ClassSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/ClassSearchProvider.java
package jadx.gui.search.providers; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.api.JavaClass; import jadx.core.dex.info.ClassInfo; import jadx.gui.jobs.Cancelable; import jadx.gui.search.SearchSettings; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; public final class ClassSearchProvider extends BaseSearchProvider { private int clsNum = 0; public ClassSearchProvider(MainWindow mw, SearchSettings searchSettings, List<JavaClass> classes) { super(mw, searchSettings, classes); } @Override public @Nullable JNode next(Cancelable cancelable) { while (true) { if (cancelable.isCanceled() || clsNum >= classes.size()) { return null; } JavaClass curCls = classes.get(clsNum++); if (checkCls(curCls)) { return convert(curCls); } } } private boolean checkCls(JavaClass cls) { ClassInfo clsInfo = cls.getClassNode().getClassInfo(); return isMatch(clsInfo.getShortName()) || isMatch(clsInfo.getFullName()) || isMatch(clsInfo.getAliasFullName()) || isMatch(clsInfo.getRawName()); } @Override public int progress() { return clsNum; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/FieldSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/FieldSearchProvider.java
package jadx.gui.search.providers; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.api.JavaClass; import jadx.core.dex.info.FieldInfo; import jadx.core.dex.nodes.FieldNode; import jadx.gui.jobs.Cancelable; import jadx.gui.search.SearchSettings; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; public final class FieldSearchProvider extends BaseSearchProvider { private int clsNum = 0; private int fldNum = 0; public FieldSearchProvider(MainWindow mw, SearchSettings searchSettings, List<JavaClass> classes) { super(mw, searchSettings, classes); } @Override public @Nullable JNode next(Cancelable cancelable) { while (true) { if (cancelable.isCanceled()) { return null; } JavaClass cls = classes.get(clsNum); List<FieldNode> fields = cls.getClassNode().getFields(); if (fldNum < fields.size()) { FieldNode fld = fields.get(fldNum++); if (checkField(fld.getFieldInfo())) { return convert(fld); } } else { clsNum++; fldNum = 0; if (clsNum >= classes.size()) { return null; } } } } private boolean checkField(FieldInfo fieldInfo) { return isMatch(fieldInfo.getName()) || isMatch(fieldInfo.getAlias()) || isMatch(fieldInfo.getFullId()); } @Override public int progress() { return clsNum; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/BaseSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/BaseSearchProvider.java
package jadx.gui.search.providers; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import jadx.api.JadxDecompiler; import jadx.api.JavaClass; import jadx.api.JavaNode; import jadx.core.dex.nodes.ICodeNode; import jadx.gui.search.ISearchMethod; import jadx.gui.search.ISearchProvider; import jadx.gui.search.SearchSettings; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.utils.JNodeCache; public abstract class BaseSearchProvider implements ISearchProvider { private final JNodeCache nodeCache; private final JadxDecompiler decompiler; protected final ISearchMethod searchMth; protected final String searchStr; protected final List<JavaClass> classes; protected final SearchSettings searchSettings; public BaseSearchProvider(MainWindow mw, SearchSettings searchSettings, List<JavaClass> classes) { this.nodeCache = mw.getCacheObject().getNodeCache(); this.decompiler = mw.getWrapper().getDecompiler(); this.searchMth = searchSettings.getSearchMethod(); this.searchStr = searchSettings.getSearchString(); if (searchSettings.getSearchPackage() != null) { this.classes = classes .stream() .filter(c -> c.getJavaPackage().isDescendantOf(searchSettings.getSearchPackage())) .collect(Collectors.toList()); } else { this.classes = classes; } this.searchSettings = searchSettings; } protected boolean isMatch(String str) { return searchMth.find(str, searchStr, 0) != -1; } protected JNode convert(JavaNode node) { return nodeCache.makeFrom(node); } protected JClass convert(JavaClass cls) { return nodeCache.makeFrom(cls); } protected JNode convert(ICodeNode codeNode) { JavaNode node = Objects.requireNonNull(decompiler.getJavaNodeByRef(codeNode)); return Objects.requireNonNull(nodeCache.makeFrom(node)); } @Override public int total() { return classes.size(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/CodeSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/CodeSearchProvider.java
package jadx.gui.search.providers; import java.util.List; import java.util.Set; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeCache; import jadx.api.JavaClass; import jadx.api.JavaNode; import jadx.api.metadata.ICodeMetadata; import jadx.api.metadata.ICodeNodeRef; import jadx.api.utils.CodeUtils; import jadx.gui.JadxWrapper; import jadx.gui.jobs.Cancelable; import jadx.gui.search.SearchSettings; import jadx.gui.treemodel.CodeNode; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import static jadx.core.utils.Utils.getOrElse; public final class CodeSearchProvider extends BaseSearchProvider { private static final Logger LOG = LoggerFactory.getLogger(CodeSearchProvider.class); private final ICodeCache codeCache; private final JadxWrapper wrapper; private final @Nullable Set<JavaClass> includedClasses; private @Nullable String code; private int clsNum = 0; private int pos = 0; public CodeSearchProvider(MainWindow mw, SearchSettings searchSettings, List<JavaClass> classes, @Nullable Set<JavaClass> includedClasses) { super(mw, searchSettings, classes); this.codeCache = mw.getWrapper().getArgs().getCodeCache(); this.wrapper = mw.getWrapper(); this.includedClasses = includedClasses; } @Override public @Nullable JNode next(Cancelable cancelable) { Set<JavaClass> inclCls = includedClasses; while (true) { if (cancelable.isCanceled() || clsNum >= classes.size()) { return null; } JavaClass cls = classes.get(clsNum); if (inclCls == null || inclCls.contains(cls)) { String clsCode = code; if (clsCode == null && !cls.isInner() && !cls.isNoCode()) { clsCode = getClassCode(cls, codeCache); } if (clsCode != null) { JNode newResult = searchNext(cls, clsCode); if (newResult != null) { code = clsCode; return newResult; } } } else { // force decompilation for not included classes cls.decompile(); } clsNum++; pos = 0; code = null; } } private @Nullable JNode searchNext(JavaClass javaClass, String clsCode) { int newPos = searchMth.find(clsCode, searchStr, pos); if (newPos == -1) { return null; } int lineStart = 1 + CodeUtils.getNewLinePosBefore(clsCode, newPos); int lineEnd = CodeUtils.getNewLinePosAfter(clsCode, newPos); int end = lineEnd == -1 ? clsCode.length() : lineEnd; String line = clsCode.substring(lineStart, end); this.pos = end; JClass rootCls = convert(javaClass); JNode enclosingNode = getOrElse(getEnclosingNode(javaClass, end), rootCls); return new CodeNode(rootCls, enclosingNode, line.trim(), newPos); } private @Nullable JNode getEnclosingNode(JavaClass javaCls, int pos) { try { ICodeMetadata metadata = javaCls.getCodeInfo().getCodeMetadata(); ICodeNodeRef nodeRef = metadata.getNodeAt(pos); JavaNode encNode = wrapper.getJavaNodeByRef(nodeRef); if (encNode != null) { return convert(encNode); } } catch (Exception e) { LOG.debug("Failed to resolve enclosing node", e); } return null; } private String getClassCode(JavaClass javaClass, ICodeCache codeCache) { try { // quick check for if code already in cache String code = codeCache.getCode(javaClass.getRawName()); if (code != null) { return code; } // start decompilation return javaClass.getCode(); } catch (Exception e) { LOG.warn("Failed to get class code: {}", javaClass, e); return ""; } } @Override public int progress() { return clsNum; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/MergedSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/MergedSearchProvider.java
package jadx.gui.search.providers; import java.util.ArrayList; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.gui.jobs.Cancelable; import jadx.gui.search.ISearchProvider; import jadx.gui.treemodel.JNode; /** * Search provider for sequential execution of nested search providers */ public class MergedSearchProvider implements ISearchProvider { private final List<ISearchProvider> list = new ArrayList<>(); private int current; private int total; public void add(ISearchProvider provider) { list.add(provider); } public boolean isEmpty() { return list.isEmpty(); } public void prepare() { current = list.isEmpty() ? -1 : 0; total = list.stream().mapToInt(ISearchProvider::total).sum(); } @Override public @Nullable JNode next(Cancelable cancelable) { if (current == -1) { return null; } while (true) { JNode next = list.get(current).next(cancelable); if (next != null) { return next; } current++; if (current >= list.size() || cancelable.isCanceled()) { // search complete current = -1; return null; } } } @Override public int progress() { return list.stream().mapToInt(ISearchProvider::progress).sum(); } @Override public int total() { return total; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/ResourceSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/ResourceSearchProvider.java
package jadx.gui.search.providers; import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; import java.util.Enumeration; import javax.swing.tree.TreeNode; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ResourceFile; import jadx.api.ResourceType; import jadx.api.plugins.utils.CommonFileUtils; import jadx.api.resources.ResourceContentType; import jadx.api.utils.CodeUtils; import jadx.gui.jobs.Cancelable; import jadx.gui.search.ISearchProvider; import jadx.gui.search.SearchSettings; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JResSearchNode; import jadx.gui.treemodel.JResource; import jadx.gui.treemodel.JRoot; import jadx.gui.ui.MainWindow; import jadx.gui.ui.dialog.SearchDialog; import jadx.gui.utils.NLS; public class ResourceSearchProvider implements ISearchProvider { private static final Logger LOG = LoggerFactory.getLogger(ResourceSearchProvider.class); private final SearchSettings searchSettings; private final SearchDialog searchDialog; private final ResourceFilter resourceFilter; private final int sizeLimit; /** * Resources queue for process. Using UI nodes to reuse loading cache */ private final Deque<JResource> resQueue; private int pos; private int loadErrors = 0; private int skipBySize = 0; public ResourceSearchProvider(MainWindow mw, SearchSettings searchSettings, SearchDialog searchDialog) { this.searchSettings = searchSettings; this.resourceFilter = searchSettings.getResourceFilter(); this.sizeLimit = searchSettings.getResSizeLimit() * 1024 * 1024; this.searchDialog = searchDialog; JResource activeResource = searchSettings.getActiveResource(); if (activeResource != null) { this.resQueue = new ArrayDeque<>(Collections.singleton(activeResource)); } else { this.resQueue = initResQueue(mw); } } @Override public @Nullable JNode next(Cancelable cancelable) { while (true) { if (cancelable.isCanceled()) { return null; } JResource resNode = getNextResFile(cancelable); if (resNode == null) { return null; } JNode newResult = search(resNode); if (newResult != null) { return newResult; } pos = 0; resQueue.removeLast(); addChildren(resNode); if (resQueue.isEmpty()) { return null; } } } private JNode search(JResource resNode) { String content; try { content = resNode.getCodeInfo().getCodeStr(); } catch (Exception e) { LOG.error("Failed to load resource node content", e); return null; } String searchString = searchSettings.getSearchString(); int newPos = searchSettings.getSearchMethod().find(content, searchString, pos); if (newPos == -1) { return null; } if (resNode.getContentType() == ResourceContentType.CONTENT_TEXT) { int lineStart = 1 + CodeUtils.getNewLinePosBefore(content, newPos); int lineEnd = CodeUtils.getNewLinePosAfter(content, newPos); int end = lineEnd == -1 ? content.length() : lineEnd; String line = content.substring(lineStart, end); this.pos = end; return new JResSearchNode(resNode, line.trim(), newPos); } else { int start = Math.max(0, newPos - 30); int end = Math.min(newPos + 50, content.length()); String line = content.substring(start, end); this.pos = newPos + searchString.length() + 1; return new JResSearchNode(resNode, line, newPos); } } private @Nullable JResource getNextResFile(Cancelable cancelable) { while (true) { JResource node = resQueue.peekLast(); if (node == null || cancelable.isCanceled()) { return null; } if (node.getType() == JResource.JResType.FILE) { if (shouldProcess(node) && loadResNode(node)) { return node; } resQueue.removeLast(); } else { // dir resQueue.removeLast(); loadResNode(node); addChildren(node); } } } private void updateProgressInfo() { StringBuilder sb = new StringBuilder(); if (loadErrors != 0) { sb.append(" ").append(NLS.str("search_dialog.resources_load_errors", loadErrors)); } if (skipBySize != 0) { sb.append(" ").append(NLS.str("search_dialog.resources_skip_by_size", skipBySize)); } if (sb.length() != 0) { sb.append(" ").append(NLS.str("search_dialog.resources_check_logs")); } searchDialog.updateProgressLabel(sb.toString()); } private boolean loadResNode(JResource node) { try { node.loadNode(); return true; } catch (Exception e) { LOG.error("Error load resource node: {}", node, e); loadErrors++; updateProgressInfo(); return false; } } private void addChildren(JResource resNode) { resQueue.addAll(resNode.getSubNodes()); } private static Deque<JResource> initResQueue(MainWindow mw) { JRoot jRoot = mw.getTreeRoot(); Deque<JResource> deque = new ArrayDeque<>(jRoot.getChildCount()); Enumeration<TreeNode> children = jRoot.children(); while (children.hasMoreElements()) { TreeNode node = children.nextElement(); if (node instanceof JResource) { JResource resNode = (JResource) node; deque.add(resNode); } } return deque; } private boolean shouldProcess(JResource resNode) { if (resNode.getResFile().getType() == ResourceType.ARSC) { // don't check the size of generated resource table, it will also skip all subfiles return resourceFilter.isAnyFile() || resourceFilter.getContentTypes().contains(ResourceContentType.CONTENT_TEXT) || resourceFilter.getExtSet().contains("xml"); } if (!isAllowedFileType(resNode)) { return false; } return isAllowedFileSize(resNode); } private boolean isAllowedFileType(JResource resNode) { ResourceFile resFile = resNode.getResFile(); if (resourceFilter.isAnyFile()) { return true; } ResourceContentType resContentType = resNode.getContentType(); if (resourceFilter.getContentTypes().contains(resContentType)) { return true; } String fileExt = CommonFileUtils.getFileExtension(resFile.getOriginalName()); if (fileExt != null && resourceFilter.getExtSet().contains(fileExt)) { return true; } if (resContentType == ResourceContentType.CONTENT_UNKNOWN && resourceFilter.getContentTypes().contains(ResourceContentType.CONTENT_BINARY)) { // treat unknown file type as binary return true; } return false; } private boolean isAllowedFileSize(JResource resNode) { if (sizeLimit <= 0) { return true; } try { int charsCount = resNode.getCodeInfo().getCodeStr().length(); long size = charsCount * 8L; if (size > sizeLimit) { LOG.info("Resource search skipped because of size limit. Resource '{}' size {} bytes, limit: {}", resNode.getName(), size, sizeLimit); skipBySize++; updateProgressInfo(); return false; } return true; } catch (Exception e) { LOG.warn("Resource load error: {}", resNode, e); loadErrors++; updateProgressInfo(); return false; } } @Override public int progress() { return 0; } @Override public int total() { return 0; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/CommentSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/CommentSearchProvider.java
package jadx.gui.search.providers; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import javax.swing.Icon; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.JavaClass; import jadx.api.JavaField; import jadx.api.JavaMethod; import jadx.api.JavaNode; import jadx.api.data.ICodeComment; import jadx.api.data.IJavaCodeRef; import jadx.api.data.IJavaNodeRef; import jadx.api.metadata.annotations.InsnCodeOffset; import jadx.gui.JadxWrapper; import jadx.gui.jobs.Cancelable; import jadx.gui.search.ISearchProvider; import jadx.gui.search.SearchSettings; import jadx.gui.settings.JadxProject; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JMethod; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.utils.CacheObject; import jadx.gui.utils.JNodeCache; import jadx.gui.utils.JumpPosition; public class CommentSearchProvider implements ISearchProvider { private static final Logger LOG = LoggerFactory.getLogger(CommentSearchProvider.class); private final JadxWrapper wrapper; private final CacheObject cacheObject; private final JadxProject project; private final SearchSettings searchSettings; private final Set<JavaClass> searchClsSet; private int progress = 0; public CommentSearchProvider(MainWindow mw, SearchSettings searchSettings, List<JavaClass> searchClasses) { this.wrapper = mw.getWrapper(); this.cacheObject = mw.getCacheObject(); this.project = mw.getProject(); this.searchSettings = searchSettings; this.searchClsSet = new HashSet<>(searchClasses); } @Override public @Nullable JNode next(Cancelable cancelable) { while (!cancelable.isCanceled()) { List<ICodeComment> comments = project.getCodeData().getComments(); if (progress >= comments.size()) { return null; } ICodeComment comment = comments.get(progress++); JNode result = isMatch(searchSettings, comment); if (result != null) { return result; } } return null; } @Nullable private JNode isMatch(SearchSettings searchSettings, ICodeComment comment) { boolean all = searchSettings.getSearchString().isEmpty(); if (all || searchSettings.isMatch(comment.getComment())) { JNode refNode = getRefNode(comment); if (refNode == null) { LOG.warn("Failed to get ref node for comment: {}", comment); return null; } if (searchClsSet.contains(refNode.getRootClass().getCls())) { return getCommentNode(comment, refNode); } } return null; } private @NotNull RefCommentNode getCommentNode(ICodeComment comment, JNode refNode) { IJavaNodeRef nodeRef = comment.getNodeRef(); if (nodeRef.getType() == IJavaNodeRef.RefType.METHOD && comment.getCodeRef() != null) { return new CodeCommentNode((JMethod) refNode, comment); } return new RefCommentNode(refNode, comment.getComment()); } @Nullable private JNode getRefNode(ICodeComment comment) { IJavaNodeRef nodeRef = comment.getNodeRef(); JavaClass javaClass = wrapper.searchJavaClassByOrigClassName(nodeRef.getDeclaringClass()); if (javaClass == null) { return null; } JNodeCache nodeCache = cacheObject.getNodeCache(); switch (nodeRef.getType()) { case CLASS: return nodeCache.makeFrom(javaClass); case FIELD: for (JavaField field : javaClass.getFields()) { if (field.getFieldNode().getFieldInfo().getShortId().equals(nodeRef.getShortId())) { return nodeCache.makeFrom(field); } } break; case METHOD: for (JavaMethod mth : javaClass.getMethods()) { if (mth.getMethodNode().getMethodInfo().getShortId().equals(nodeRef.getShortId())) { return nodeCache.makeFrom(mth); } } break; } return null; } private static final class CodeCommentNode extends RefCommentNode { private static final long serialVersionUID = 6208192811789176886L; private final int offset; private JumpPosition pos; public CodeCommentNode(JMethod node, ICodeComment comment) { super(node, comment.getComment()); IJavaCodeRef codeRef = Objects.requireNonNull(comment.getCodeRef(), "Null comment code ref"); this.offset = codeRef.getIndex(); } @Override public int getPos() { return getCachedPos().getPos(); } private synchronized JumpPosition getCachedPos() { if (pos == null) { pos = getJumpPos(); } return pos; } /** * Lazy decompilation to get comment location if requested */ private JumpPosition getJumpPos() { JavaMethod javaMethod = ((JMethod) node).getJavaMethod(); ICodeInfo codeInfo = javaMethod.getTopParentClass().getCodeInfo(); int methodDefPos = javaMethod.getDefPos(); JumpPosition jump = codeInfo.getCodeMetadata().searchDown(methodDefPos, (pos, ann) -> ann instanceof InsnCodeOffset && ((InsnCodeOffset) ann).getOffset() == offset ? new JumpPosition(node, pos) : null); if (jump != null) { return jump; } return new JumpPosition(node); } } private static class RefCommentNode extends JNode { private static final long serialVersionUID = 3887992236082515752L; protected final JNode node; protected final String comment; public RefCommentNode(JNode node, String comment) { this.node = node; this.comment = comment; } @Override public JClass getRootClass() { return node.getRootClass(); } @Override public JavaNode getJavaNode() { return node.getJavaNode(); } @Override public JClass getJParent() { return node.getJParent(); } @Override public Icon getIcon() { return node.getIcon(); } @Override public String getSyntaxName() { return SyntaxConstants.SYNTAX_STYLE_NONE; // comment is always plain text } @Override public String makeString() { return node.makeString(); } @Override public String makeLongString() { return node.makeLongString(); } @Override public String makeStringHtml() { return node.makeStringHtml(); } @Override public String makeLongStringHtml() { return node.makeLongStringHtml(); } @Override public boolean disableHtml() { return node.disableHtml(); } @Override public int getPos() { return node.getPos(); } @Override public String getTooltip() { return node.getTooltip(); } @Override public String makeDescString() { return comment; } @Override public boolean hasDescString() { return true; } } @Override public int progress() { return progress; } @Override public int total() { return project.getCodeData().getComments().size(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/MethodSearchProvider.java
jadx-gui/src/main/java/jadx/gui/search/providers/MethodSearchProvider.java
package jadx.gui.search.providers; import java.util.List; import org.jetbrains.annotations.Nullable; import jadx.api.JavaClass; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.nodes.MethodNode; import jadx.gui.jobs.Cancelable; import jadx.gui.search.SearchSettings; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; public final class MethodSearchProvider extends BaseSearchProvider { private int clsNum = 0; private int mthNum = 0; public MethodSearchProvider(MainWindow mw, SearchSettings searchSettings, List<JavaClass> classes) { super(mw, searchSettings, classes); } @Override public @Nullable JNode next(Cancelable cancelable) { if (classes.isEmpty()) { return null; } while (true) { if (cancelable.isCanceled()) { return null; } JavaClass cls = classes.get(clsNum); List<MethodNode> methods = cls.getClassNode().getMethods(); if (mthNum < methods.size()) { MethodNode mth = methods.get(mthNum++); if (checkMth(mth.getMethodInfo())) { return convert(mth); } } else { clsNum++; mthNum = 0; if (clsNum >= classes.size()) { return null; } } } } private boolean checkMth(MethodInfo mthInfo) { return isMatch(mthInfo.getShortId()) || isMatch(mthInfo.getAlias()) || isMatch(mthInfo.getFullId()) || isMatch(mthInfo.getAliasFullName()); } @Override public int progress() { return clsNum; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/search/providers/ResourceFilter.java
jadx-gui/src/main/java/jadx/gui/search/providers/ResourceFilter.java
package jadx.gui.search.providers; import java.util.ArrayList; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import jadx.api.resources.ResourceContentType; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.InvalidDataException; import static jadx.api.resources.ResourceContentType.CONTENT_BINARY; import static jadx.api.resources.ResourceContentType.CONTENT_TEXT; public class ResourceFilter { private static final ResourceFilter ANY = new ResourceFilter(Set.of(), Set.of()); private static final String VAR_TEXT = "$TEXT"; private static final String VAR_BIN = "$BIN"; public static final String DEFAULT_STR = VAR_TEXT; public static ResourceFilter parse(String filterStr) { String str = filterStr.trim(); if (str.isEmpty() || str.equals("*")) { return ANY; } Set<ResourceContentType> contentTypes = EnumSet.noneOf(ResourceContentType.class); Set<String> extSet = new LinkedHashSet<>(); String[] parts = filterStr.split("[|, ]"); for (String part : parts) { if (part.isEmpty()) { continue; } if (part.startsWith("$")) { switch (part) { case VAR_TEXT: contentTypes.add(CONTENT_TEXT); break; case VAR_BIN: contentTypes.add(CONTENT_BINARY); break; default: throw new InvalidDataException("Unknown var name: " + part); } } else { extSet.add(part); } } return new ResourceFilter(contentTypes, extSet); } public static String format(ResourceFilter filter) { if (filter.isAnyFile()) { return "*"; } List<String> list = new ArrayList<>(); Set<ResourceContentType> types = filter.getContentTypes(); if (types.contains(CONTENT_TEXT)) { list.add(VAR_TEXT); } if (types.contains(CONTENT_BINARY)) { list.add(VAR_BIN); } list.addAll(filter.getExtSet()); return Utils.listToString(list, "|"); } public static String withContentType(String filterStr, Set<ResourceContentType> contentTypes) { ResourceFilter filter = parse(filterStr); return format(new ResourceFilter(contentTypes, filter.getExtSet())); } private final boolean anyFile; private final Set<ResourceContentType> contentTypes; private final Set<String> extSet; private ResourceFilter(Set<ResourceContentType> contentTypes, Set<String> extSet) { this.anyFile = contentTypes.isEmpty() && extSet.isEmpty(); this.contentTypes = contentTypes.isEmpty() ? Set.of() : contentTypes; this.extSet = extSet.isEmpty() ? Set.of() : extSet; } public boolean isAnyFile() { return anyFile; } public Set<ResourceContentType> getContentTypes() { return contentTypes; } public Set<String> getExtSet() { return extSet; } @Override public String toString() { return format(this); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/MainDropTarget.java
jadx-gui/src/main/java/jadx/gui/ui/MainDropTarget.java
package jadx.gui.ui; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.io.File; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.files.FileUtils; /** * Enables drop support from external applications for the {@link MainWindow} (load dropped APK * file) */ public class MainDropTarget implements DropTargetListener { private static final Logger LOG = LoggerFactory.getLogger(MainDropTarget.class); private final MainWindow mainWindow; public MainDropTarget(MainWindow mainWindow) { this.mainWindow = mainWindow; } protected void processDrag(DropTargetDragEvent dtde) { if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.acceptDrag(DnDConstants.ACTION_COPY); } else { dtde.rejectDrag(); } } @Override public void dragEnter(DropTargetDragEvent dtde) { processDrag(dtde); } @Override public void dragOver(DropTargetDragEvent dtde) { processDrag(dtde); } @Override public void dropActionChanged(DropTargetDragEvent dtde) { } @Override @SuppressWarnings("unchecked") public void drop(DropTargetDropEvent dtde) { if (!dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.rejectDrop(); return; } dtde.acceptDrop(dtde.getDropAction()); try { Transferable transferable = dtde.getTransferable(); List<File> transferData = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor); if (!transferData.isEmpty()) { dtde.dropComplete(true); mainWindow.open(FileUtils.toPaths(transferData)); } } catch (Exception e) { LOG.error("File drop operation failed", e); } } @Override public void dragExit(DropTargetEvent dte) { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/MainWindow.java
jadx-gui/src/main/java/jadx/gui/ui/MainWindow.java
package jadx.gui.ui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Desktop; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.Font; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.io.File; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import java.util.function.Consumer; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.plaf.FontUIResource; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.exbin.bined.swing.section.SectCodeArea; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.formdev.flatlaf.FlatLaf; import com.formdev.flatlaf.extras.FlatInspector; import com.formdev.flatlaf.extras.FlatUIDefaultsInspector; import com.formdev.flatlaf.util.UIScale; import ch.qos.logback.classic.Level; import jadx.api.JadxArgs; import jadx.api.JavaClass; import jadx.api.JavaNode; import jadx.api.ResourceFile; import jadx.api.plugins.events.JadxEvents; import jadx.api.plugins.events.types.ReloadProject; import jadx.api.plugins.events.types.ReloadSettingsWindow; import jadx.api.plugins.utils.CommonFileUtils; import jadx.commons.app.JadxSystemInfo; import jadx.core.Jadx; import jadx.core.dex.nodes.ClassNode; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.nodes.MethodNode; import jadx.core.export.TemplateFile; import jadx.core.utils.ListUtils; import jadx.core.utils.StringUtils; import jadx.core.utils.android.AndroidManifestParser; import jadx.core.utils.android.AppAttribute; import jadx.core.utils.android.ApplicationParams; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.utils.files.FileUtils; import jadx.gui.JadxWrapper; import jadx.gui.cache.manager.CacheManager; import jadx.gui.device.debugger.BreakpointManager; import jadx.gui.events.services.RenameService; import jadx.gui.events.types.JadxGuiEventsImpl; import jadx.gui.jobs.BackgroundExecutor; import jadx.gui.jobs.DecompileTask; import jadx.gui.jobs.ExportTask; import jadx.gui.jobs.IBackgroundTask; import jadx.gui.jobs.TaskStatus; import jadx.gui.jobs.TaskWithExtraOnFinish; import jadx.gui.logs.LogCollector; import jadx.gui.logs.LogOptions; import jadx.gui.logs.LogPanel; import jadx.gui.plugins.context.CommonGuiPluginsContext; import jadx.gui.plugins.context.TreePopupMenuEntry; import jadx.gui.plugins.mappings.RenameMappingsGui; import jadx.gui.plugins.quark.QuarkDialog; import jadx.gui.report.ExceptionDialog; import jadx.gui.report.JadxExceptionHandler; import jadx.gui.settings.JadxProject; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.data.SaveOptionEnum; import jadx.gui.settings.ui.JadxSettingsWindow; import jadx.gui.tree.TreeExpansionService; import jadx.gui.treemodel.ApkSignatureNode; import jadx.gui.treemodel.JLoadableNode; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JPackage; import jadx.gui.treemodel.JResource; import jadx.gui.treemodel.JRoot; import jadx.gui.ui.action.ActionModel; import jadx.gui.ui.action.JadxGuiAction; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.codearea.AbstractCodeContentPanel; import jadx.gui.ui.codearea.EditorViewState; import jadx.gui.ui.codearea.theme.EditorThemeManager; import jadx.gui.ui.dialog.ADBDialog; import jadx.gui.ui.dialog.AboutDialog; import jadx.gui.ui.dialog.CharsetDialog; import jadx.gui.ui.dialog.GotoAddressDialog; import jadx.gui.ui.dialog.LogViewerDialog; import jadx.gui.ui.dialog.SearchDialog; import jadx.gui.ui.export.ExportProjectDialog; import jadx.gui.ui.filedialog.FileDialogWrapper; import jadx.gui.ui.filedialog.FileOpenMode; import jadx.gui.ui.hexviewer.HexInspectorPanel; import jadx.gui.ui.hexviewer.HexPreviewPanel; import jadx.gui.ui.menu.HiddenMenuItem; import jadx.gui.ui.menu.JadxMenu; import jadx.gui.ui.menu.JadxMenuBar; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.panel.IssuesPanel; import jadx.gui.ui.panel.JDebuggerPanel; import jadx.gui.ui.panel.ProgressPanel; import jadx.gui.ui.popupmenu.RecentProjectsMenuListener; import jadx.gui.ui.startpage.StartPageNode; import jadx.gui.ui.tab.EditorSyncManager; import jadx.gui.ui.tab.NavigationController; import jadx.gui.ui.tab.QuickTabsTree; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.ui.tab.TabsController; import jadx.gui.ui.tab.dnd.TabDndController; import jadx.gui.ui.treenodes.SummaryNode; import jadx.gui.ui.treenodes.UndisplayedStringsNode; import jadx.gui.update.JadxUpdate; import jadx.gui.utils.CacheObject; import jadx.gui.utils.DesktopEntryUtils; import jadx.gui.utils.FontUtils; import jadx.gui.utils.ILoadListener; import jadx.gui.utils.Icons; import jadx.gui.utils.LafManager; import jadx.gui.utils.Link; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.dbg.UIWatchDog; import jadx.gui.utils.fileswatcher.LiveReloadWorker; import jadx.gui.utils.shortcut.ShortcutsController; import jadx.gui.utils.ui.ActionHandler; import jadx.gui.utils.ui.FileOpenerHelper; import jadx.gui.utils.ui.NodeLabel; public class MainWindow extends JFrame { private static final Logger LOG = LoggerFactory.getLogger(MainWindow.class); private static final String DEFAULT_TITLE = "jadx-gui"; private static final double BORDER_RATIO = 0.15; private static final double WINDOW_RATIO = 1 - BORDER_RATIO * 2; public static final double SPLIT_PANE_RESIZE_WEIGHT = 0.15; private final transient JadxWrapper wrapper; private final transient JadxSettings settings; private final transient CacheObject cacheObject; private final transient CacheManager cacheManager; private final transient BackgroundExecutor backgroundExecutor; private final transient JadxGuiEventsImpl events = new JadxGuiEventsImpl(); private final transient TreeExpansionService treeExpansionService; private final TabsController tabsController; private final NavigationController navController; private final EditorSyncManager editorSyncManager; private final EditorThemeManager editorThemeManager; private transient @NotNull JadxProject project; private transient JadxGuiAction newProjectAction; private transient JadxGuiAction saveProjectAction; private transient JPanel mainPanel; private transient JSplitPane treeSplitPane; private transient JSplitPane rightSplitPane; private transient JSplitPane bottomSplitPane; private transient JSplitPane quickTabsAndCodeSplitPane; private JTree tree; private DefaultTreeModel treeModel; private JRoot treeRoot; private TabbedPane tabbedPane; private HeapUsageBar heapUsageBar; private transient boolean treeReloading; private boolean isFlattenPackage; private JToggleButton flatPkgButton; private JCheckBoxMenuItem flatPkgMenuItem; private JToggleButton deobfToggleBtn; private JCheckBoxMenuItem deobfMenuItem; private JCheckBoxMenuItem liveReloadMenuItem; private final LiveReloadWorker liveReloadWorker; private transient Link updateLink; private transient ProgressPanel progressPane; private transient IssuesPanel issuesPanel; private transient @Nullable LogPanel logPanel; private transient @Nullable JDebuggerPanel debuggerPanel; private transient @Nullable QuickTabsTree quickTabsTree; private final List<ILoadListener> loadListeners = new ArrayList<>(); private final List<Consumer<JRoot>> treeUpdateListener = new ArrayList<>(); private boolean loaded; private boolean settingsOpen = false; private boolean showUndisplayedCharsDialog; private final ShortcutsController shortcutsController; private JadxMenuBar menuBar; private JMenu pluginsMenu; public JMenu hexViewerMenu; private final transient RenameMappingsGui renameMappings; public MainWindow(JadxSettings settings) { this.settings = settings; this.project = new JadxProject(this); this.wrapper = new JadxWrapper(this); this.cacheObject = new CacheObject(wrapper); this.liveReloadWorker = new LiveReloadWorker(this); this.renameMappings = new RenameMappingsGui(this); this.cacheManager = new CacheManager(settings); this.shortcutsController = new ShortcutsController(settings); this.tabsController = new TabsController(this); this.navController = new NavigationController(this); this.editorThemeManager = new EditorThemeManager(settings); JadxEventQueue.register(); JadxExceptionHandler.register(this); resetCache(); initUI(); this.editorSyncManager = new EditorSyncManager(this, tabbedPane); this.backgroundExecutor = new BackgroundExecutor(settings, progressPane); this.treeExpansionService = new TreeExpansionService(this, tree); initMenuAndToolbar(); UiUtils.setWindowIcons(this); this.shortcutsController.registerMouseEventListener(this); loadSettings(); initEvents(); update(); checkForUpdate(); } public void init() { pack(); setLocationAndPosition(); treeSplitPane.setDividerLocation(settings.getTreeWidth()); heapUsageBar.setVisible(settings.isShowHeapUsageBar()); setVisible(true); processCommandLineArgs(); } private void processCommandLineArgs() { if (settings.getFiles().isEmpty()) { tabsController.selectTab(new StartPageNode()); } else { open(FileUtils.fileNamesToPaths(settings.getFiles()), this::handleSelectClassOption); } } private void handleSelectClassOption() { if (settings.getCmdSelectClass() != null) { JavaNode javaNode = wrapper.searchJavaClassByFullAlias(settings.getCmdSelectClass()); if (javaNode == null) { javaNode = wrapper.searchJavaClassByOrigClassName(settings.getCmdSelectClass()); } if (javaNode == null) { JOptionPane.showMessageDialog(this, NLS.str("msg.cmd_select_class_error", settings.getCmdSelectClass()), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); return; } tabsController.codeJump(cacheObject.getNodeCache().makeFrom(javaNode)); } } private void checkForUpdate() { if (!settings.isCheckForUpdates()) { return; } new JadxUpdate().check(settings.getJadxUpdateChannel(), release -> SwingUtilities.invokeLater(() -> { switch (settings.getJadxUpdateChannel()) { case STABLE: updateLink.setUrl(JadxUpdate.JADX_RELEASES_URL); break; case UNSTABLE: updateLink.setUrl(JadxUpdate.JADX_ARTIFACTS_URL); break; } updateLink.setText(NLS.str("menu.update_label", release.getName())); updateLink.setVisible(true); })); } public void openFileDialog() { showOpenDialog(FileOpenMode.OPEN); } public void openProjectDialog() { showOpenDialog(FileOpenMode.OPEN_PROJECT); } private void showOpenDialog(FileOpenMode mode) { saveAll(); if (!ensureProjectIsSaved()) { return; } FileDialogWrapper fileDialog = new FileDialogWrapper(this, mode); List<Path> openPaths = fileDialog.show(); if (!openPaths.isEmpty()) { settings.setLastOpenFilePath(fileDialog.getCurrentDir()); open(openPaths); } } public void addFiles() { FileDialogWrapper fileDialog = new FileDialogWrapper(this, FileOpenMode.ADD); List<Path> addPaths = fileDialog.show(); if (!addPaths.isEmpty()) { addFiles(addPaths); } } public void addFiles(List<Path> addPaths) { project.setFilePaths(ListUtils.distinctMergeSortedLists(addPaths, project.getFilePaths())); reopen(); } private void newProject() { saveAll(); if (!ensureProjectIsSaved()) { return; } UiUtils.bgRun(() -> { closeAll(); updateProject(new JadxProject(this)); }); } private void saveProject() { saveOpenTabs(); if (!project.isSaveFileSelected()) { saveProjectAs(); } else { project.save(); update(); } } private void saveProjectAs() { FileDialogWrapper fileDialog = new FileDialogWrapper(this, FileOpenMode.SAVE_PROJECT); if (project.getFilePaths().size() == 1) { // If there is only one file loaded we suggest saving the jadx project file next to the loaded file Path projectPath = getProjectPathForFile(this.project.getFilePaths().get(0)); fileDialog.setSelectedFile(projectPath); } List<Path> saveFiles = fileDialog.show(); if (saveFiles.isEmpty()) { return; } settings.setLastSaveProjectPath(fileDialog.getCurrentDir()); Path savePath = saveFiles.get(0); if (!savePath.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(JadxProject.PROJECT_EXTENSION)) { savePath = savePath.resolveSibling(savePath.getFileName() + "." + JadxProject.PROJECT_EXTENSION); } if (Files.exists(savePath)) { int res = JOptionPane.showConfirmDialog( this, NLS.str("confirm.save_as_message", savePath.getFileName()), NLS.str("confirm.save_as_title"), JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) { return; } } project.saveAs(savePath); settings.addRecentProject(savePath); update(); } public void addNewScript() { FileDialogWrapper fileDialog = new FileDialogWrapper(this, FileOpenMode.CUSTOM_SAVE); fileDialog.setTitle(NLS.str("file.save")); Path workingDir = project.getWorkingDir(); Path baseDir = workingDir != null ? workingDir : settings.getLastSaveFilePath(); fileDialog.setSelectedFile(baseDir.resolve("script.jadx.kts")); fileDialog.setFileExtList(Collections.singletonList("jadx.kts")); fileDialog.setSelectionMode(JFileChooser.FILES_ONLY); List<Path> paths = fileDialog.show(); if (paths.size() != 1) { return; } Path scriptFile = paths.get(0); try { TemplateFile tmpl = TemplateFile.fromResources("/files/script.jadx.kts.tmpl"); FileUtils.writeFile(scriptFile, tmpl.build()); } catch (Exception e) { LOG.error("Failed to save new script file: {}", scriptFile, e); } List<Path> inputs = project.getFilePaths(); inputs.add(scriptFile); refreshTree(inputs); } public void removeInput(Path file) { int dialogResult = JOptionPane.showConfirmDialog( this, NLS.str("message.confirm_remove_script"), NLS.str("msg.warning_title"), JOptionPane.YES_NO_OPTION); if (dialogResult == JOptionPane.NO_OPTION) { return; } List<Path> inputs = project.getFilePaths(); inputs.remove(file); refreshTree(inputs); } public void renameInput(Path file) { String newName = JOptionPane.showInputDialog(this, NLS.str("message.enter_new_name"), file.getFileName().toString()); if (newName == null || newName.trim().isEmpty()) { return; } Path targetPath = file.resolveSibling(newName); boolean success = FileUtils.renameFile(file, targetPath); if (success) { List<Path> inputs = project.getFilePaths(); inputs.remove(file); inputs.add(targetPath); refreshTree(inputs); } else { JOptionPane.showMessageDialog(this, NLS.str("message.could_not_rename"), NLS.str("message.errorTitle"), JOptionPane.ERROR_MESSAGE); } } private void refreshTree(List<Path> inputs) { project.setFilePaths(inputs); project.save(); reopen(); } public void open(Path path) { open(Collections.singletonList(path), UiUtils.EMPTY_RUNNABLE); } public void open(List<Path> paths) { open(paths, UiUtils.EMPTY_RUNNABLE); } private void open(List<Path> paths, Runnable onFinish) { saveAll(); UiUtils.bgRun(() -> { closeAll(); if (paths.size() == 1 && openSingleFile(paths.get(0), onFinish)) { return; } // start new project project = new JadxProject(this); project.setFilePaths(paths); showUndisplayedCharsDialog = false; loadFiles(onFinish); }); } private boolean openSingleFile(Path singleFile, Runnable onFinish) { if (singleFile.getFileName() == null) { return false; } String fileExtension = CommonFileUtils.getFileExtension(singleFile.getFileName().toString()); if (fileExtension != null && fileExtension.equalsIgnoreCase(JadxProject.PROJECT_EXTENSION)) { openProject(singleFile, onFinish); return true; } // check if project file already saved with default name Path projectPath = getProjectPathForFile(singleFile); if (Files.exists(projectPath)) { openProject(projectPath, onFinish); return true; } return false; } private static Path getProjectPathForFile(Path loadedFile) { String fileName = loadedFile.getFileName() + "." + JadxProject.PROJECT_EXTENSION; return loadedFile.resolveSibling(fileName); } public void reopen() { LOG.debug("starting reopen"); UiUtils.bgRun(() -> { getBackgroundExecutor().waitForComplete(); synchronized (ReloadProject.EVENT) { saveAll(); closeAll(); System.gc(); loadFiles(() -> { menuBar.reloadShortcuts(); events().send(ReloadSettingsWindow.INSTANCE); LOG.debug("reopen complete"); }); } }); } private void openProject(Path path, Runnable onFinish) { LOG.debug("Loading project: {}", path); JadxProject jadxProject = JadxProject.load(this, path); if (jadxProject == null) { JOptionPane.showMessageDialog( this, NLS.str("msg.project_error"), NLS.str("msg.project_error_title"), JOptionPane.INFORMATION_MESSAGE); jadxProject = new JadxProject(this); } settings.addRecentProject(path); project = jadxProject; loadFiles(onFinish); } private void loadFiles(Runnable onFinish) { if (project.getFilePaths().isEmpty()) { tabsController.selectTab(new StartPageNode()); onFinish.run(); return; } backgroundExecutor.execute(NLS.str("progress.load"), () -> { try { wrapper.open(); } catch (Exception e) { LOG.error("Project load error", e); closeAll(); } }, status -> { if (status == TaskStatus.CANCEL_BY_MEMORY) { showHeapUsageBar(); UiUtils.errorMessage(this, NLS.str("message.memoryLow")); return; } if (status != TaskStatus.COMPLETE) { LOG.warn("Loading task incomplete, status: {}", status); return; } checkLoadedStatus(); onOpen(onFinish); }); } private void saveAll() { saveOpenTabs(); project.setTreeExpansions(treeExpansionService.save()); BreakpointManager.saveAndExit(); } private void closeAll() { UiUtils.notUiThreadGuard(); cancelBackgroundJobs(); UiUtils.uiRunAndWait(() -> { tabsController.forceCloseAllTabs(); tabbedPane.reset(); navController.reset(); shortcutsController.reset(); clearTree(); UiUtils.resetClipboardOwner(); update(); }); wrapper.close(); LogCollector.getInstance().reset(); resetCache(); notifyLoadListeners(false); } private void checkLoadedStatus() { if (!wrapper.getClasses().isEmpty()) { return; } int errors = issuesPanel.getErrorsCount(); if (errors > 0) { int result = JOptionPane.showConfirmDialog(this, NLS.str("message.load_errors", errors), NLS.str("message.errorTitle"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE); if (result == JOptionPane.OK_OPTION) { showLogViewer(LogOptions.allWithLevel(Level.ERROR)); } } else { showLogViewer(LogOptions.allWithLevel(Level.WARN)); UiUtils.showMessageBox(this, NLS.str("message.no_classes")); } } private void onOpen(Runnable onFinish) { initTree(); updateLiveReload(project.isEnableLiveReload()); BreakpointManager.init(project.getFilePaths().get(0).toAbsolutePath().getParent()); List<EditorViewState> openTabs = project.getOpenTabs(this); backgroundExecutor.startLoading( () -> preLoadOpenTabs(openTabs), () -> { restoreOpenTabs(openTabs); update(); notifyLoadListeners(true); onFinish.run(); checkIfCodeHasNonPrintableChars(); runInitialBackgroundJobs(); }); // queue tree state restore after loading task treeExpansionService.load(project.getTreeExpansions()); } public void passesReloaded() { tabbedPane.reloadInactiveTabs(); reloadTree(); } private void initEvents() { events().global().addListener(JadxEvents.RELOAD_PROJECT, ev -> UiUtils.uiRun(this::reopen)); RenameService.init(this); } public void updateLiveReload(boolean state) { if (liveReloadWorker.isStarted() == state) { return; } project.setEnableLiveReload(state); liveReloadMenuItem.setEnabled(false); backgroundExecutor.execute( (state ? "Starting" : "Stopping") + " live reload", () -> liveReloadWorker.updateState(state), s -> { liveReloadMenuItem.setState(state); liveReloadMenuItem.setEnabled(true); }); } private void addTreeCustomNodes() { treeRoot.replaceCustomNode(ApkSignatureNode.getApkSignature(wrapper)); treeRoot.replaceCustomNode(new SummaryNode(this)); } private boolean ensureProjectIsSaved() { if (project.isSaved() || project.isInitial()) { return true; } if (project.getFilePaths().isEmpty()) { // ignore blank project save return true; } // Check if we saved settings that indicate what to do if (settings.getSaveOption() == SaveOptionEnum.NEVER) { return true; } if (settings.getSaveOption() == SaveOptionEnum.ALWAYS) { saveProject(); return true; } JCheckBox remember = new JCheckBox(NLS.str("confirm.remember")); JLabel message = new JLabel(NLS.str("confirm.not_saved_message")); JPanel inner = new JPanel(new BorderLayout()); inner.add(remember, BorderLayout.SOUTH); inner.add(message, BorderLayout.NORTH); int res = JOptionPane.showConfirmDialog( this, inner, NLS.str("confirm.not_saved_title"), JOptionPane.YES_NO_CANCEL_OPTION); switch (res) { case JOptionPane.YES_OPTION: if (remember.isSelected()) { settings.setSaveOption(SaveOptionEnum.ALWAYS); settings.sync(); } saveProject(); return true; case JOptionPane.NO_OPTION: if (remember.isSelected()) { settings.setSaveOption(SaveOptionEnum.NEVER); settings.sync(); } return true; case JOptionPane.CANCEL_OPTION: return false; } return true; } public void updateProject(@NotNull JadxProject jadxProject) { this.project = jadxProject; UiUtils.uiRun(this::update); } public void update() { UiUtils.uiThreadGuard(); newProjectAction.setEnabled(!project.isInitial()); saveProjectAction.setEnabled(loaded && !project.isSaved()); deobfToggleBtn.setSelected(settings.isDeobfuscationOn()); renameMappings.onUpdate(loaded); Path projectPath = project.getProjectPath(); String pathString; if (projectPath == null) { pathString = ""; } else { pathString = " [" + projectPath.toAbsolutePath().getParent() + ']'; } setTitle((project.isSaved() ? "" : '*') + project.getName() + pathString + " - " + DEFAULT_TITLE); } protected void resetCache() { cacheObject.reset(); } synchronized void runInitialBackgroundJobs() { if (settings.isAutoStartJobs()) { new Timer().schedule(new TimerTask() { @Override public void run() { requestFullDecompilation(); } }, 1000); } } public void requestFullDecompilation() { if (cacheObject.isFullDecompilationFinished()) { return; } backgroundExecutor.execute(new DecompileTask(this)); } public void resetCodeCache() { backgroundExecutor.execute( NLS.str("preferences.cache.task.delete"), () -> { try { getWrapper().getCurrentDecompiler().ifPresent(jadx -> { try { jadx.getArgs().getCodeCache().close(); } catch (Exception e) { LOG.error("Failed to close code cache", e); } }); Path cacheDir = project.getCacheDir(); project.resetCacheDir(); FileUtils.deleteDirIfExists(cacheDir); } catch (Exception e) { LOG.error("Error during code cache reset", e); } }, status -> events().send(ReloadProject.EVENT)); } public void cancelBackgroundJobs() { backgroundExecutor.cancelAll(); } public void exportProject() { ExportProjectDialog dialog = new ExportProjectDialog(this, props -> { JadxArgs args = wrapper.getArgs(); if (props.isAsGradleMode()) { args.setExportGradleType(props.getExportGradleType()); args.setSkipSources(false); args.setSkipResources(false); } else { args.setExportGradleType(null); args.setSkipSources(props.isSkipSources()); args.setSkipResources(props.isSkipResources()); } backgroundExecutor.execute(new ExportTask(this, wrapper, new File(props.getExportPath()))); }); dialog.setVisible(true); } public void initTree() { treeRoot = new JRoot(wrapper); treeRoot.setFlatPackages(isFlattenPackage); treeModel.setRoot(treeRoot); addTreeCustomNodes(); treeRoot.update(); reloadTree(); } private void clearTree() { treeRoot = null; treeModel.setRoot(null); treeModel.reload(); } public void reloadTree() { treeReloading = true; treeUpdateListener.forEach(listener -> listener.accept(treeRoot)); treeModel.reload(); treeReloading = false; } public void rebuildPackagesTree() { treeRoot.update(); } // simple save and restore tree state after renaming // maybe need improve for find and update only changed node public void reloadTreePreservingState() { List<String> treePath = treeExpansionService.save(); reloadTree(); treeExpansionService.load(treePath); } private void toggleFlattenPackage() { setFlattenPackage(!isFlattenPackage); } private void setFlattenPackage(boolean value) { isFlattenPackage = value; settings.setFlattenPackage(isFlattenPackage); flatPkgButton.setSelected(isFlattenPackage); flatPkgMenuItem.setState(isFlattenPackage); Object root = treeModel.getRoot(); if (root instanceof JRoot) { JRoot treeRoot = (JRoot) root; treeRoot.setFlatPackages(isFlattenPackage); reloadTree(); } } private void toggleDeobfuscation() { boolean deobfOn = !settings.isDeobfuscationOn(); settings.setDeobfuscationOn(deobfOn); settings.sync(); deobfToggleBtn.setSelected(deobfOn); deobfMenuItem.setState(deobfOn); reopen(); } private boolean nodeClickAction(@Nullable Object obj) { if (obj == null) { return false; } try { if (obj instanceof JResource) { JResource res = (JResource) obj; ResourceFile resFile = res.getResFile(); if (resFile != null) { if (JResource.isOpenInExternalTool(resFile.getType())) { FileOpenerHelper.openFile(this, res); return true; } if (JResource.isSupportedForView(resFile.getType())) { tabsController.selectTab(res, true); return true; } } } else if (obj instanceof JNode) { JNode treeNode = (JNode) obj; if (treeNode.hasContent() || treeNode.getJParent() != null) { tabsController.codeJump(treeNode, true); return true; } } } catch (Exception e) { LOG.error("Content loading error", e); } return false; } private void treeRightClickAction(MouseEvent e) { JNode node = getJNodeUnderMouse(e); if (node == null) { return; } JPopupMenu menu = node.onTreePopupMenu(this); CommonGuiPluginsContext pluginsContext = getWrapper().getGuiPluginsContext(); for (TreePopupMenuEntry entry : pluginsContext.getTreePopupMenuEntries()) { JMenuItem menuItem = entry.buildEntry(node); if (menuItem != null) { if (menu == null) { menu = new JPopupMenu(); } menu.add(menuItem); } } if (menu != null) { menu.show(e.getComponent(), e.getX(), e.getY()); } } @Nullable private JNode getJNodeUnderMouse(MouseEvent mouseEvent) { TreeNode treeNode = UiUtils.getTreeNodeUnderMouse(tree, mouseEvent); if (treeNode instanceof JNode) { return (JNode) treeNode; } return null; } // TODO: extract tree component into new class public void selectNodeInTree(JNode node) { if (node.getParent() == null && treeRoot != null) { // node not register in tree node = treeRoot.searchNode(node); if (node == null) { LOG.error("Class not found in tree"); return; } } TreeNode[] pathNodes = treeModel.getPathToRoot(node); if (pathNodes == null) { return; } TreePath path = new TreePath(pathNodes); tree.setSelectionPath(path); tree.makeVisible(path); tree.scrollPathToVisible(path); tree.requestFocus(); } public void textSearch() { ContentPanel panel = tabbedPane.getSelectedContentPanel(); if (panel instanceof AbstractCodeContentPanel) { AbstractCodeArea codeArea = ((AbstractCodeContentPanel) panel).getCodeArea(); if (codeArea != null) { String preferText = codeArea.getSelectedText(); if (StringUtils.isEmpty(preferText)) { preferText = codeArea.getWordUnderCaret(); } if (!StringUtils.isEmpty(preferText)) { SearchDialog.searchText(MainWindow.this, preferText); return; } } } SearchDialog.search(MainWindow.this, SearchDialog.SearchPreset.TEXT); } private void sendActionsToHexViewer(ActionModel action) { HexPreviewPanel hexPreviewPanel = getCurrentHexViewTab(); if (hexPreviewPanel != null) { HexInspectorPanel inspector = hexPreviewPanel.getInspector(); SectCodeArea hexEditor = hexPreviewPanel.getEditor(); switch (action) { case HEX_VIEWER_SHOW_INSPECTOR: hexPreviewPanel.getInspector().setVisible(!inspector.isVisible()); break; case HEX_VIEWER_CHANGE_ENCODING: String result = CharsetDialog.chooseCharset(this, hexEditor.getCharset().name()); if (!StringUtils.isEmpty(result)) { hexEditor.setCharset(Charset.forName(result)); } break; case HEX_VIEWER_GO_TO_ADDRESS: new GotoAddressDialog().showSetSelectionDialog(hexEditor); break; case HEX_VIEWER_FIND: hexPreviewPanel.showSearchBar(); break; } } } public HexPreviewPanel getCurrentHexViewTab() { ContentPanel panel = tabbedPane.getSelectedContentPanel(); if (panel instanceof AbstractCodeContentPanel) { Component childrenComponent = ((AbstractCodeContentPanel) panel).getChildrenComponent(); if (childrenComponent instanceof HexPreviewPanel) { return (HexPreviewPanel) childrenComponent; } } return null; } public void toggleHexViewMenu() { hexViewerMenu.setEnabled(getCurrentHexViewTab() != null); } public void goToMainActivity() { AndroidManifestParser parser = new AndroidManifestParser( AndroidManifestParser.getAndroidManifest(getWrapper().getResources()), EnumSet.of(AppAttribute.MAIN_ACTIVITY), getWrapper().getArgs().getSecurity()); if (!parser.isManifestFound()) { JOptionPane.showMessageDialog(MainWindow.this, NLS.str("error_dialog.not_found", "AndroidManifest.xml"), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); return; } try { ApplicationParams results = parser.parse(); if (results.getMainActivity() == null) { throw new JadxRuntimeException("Failed to get main activity name from manifest"); } JavaClass mainActivityClass = results.getMainActivityJavaClass(getWrapper().getDecompiler()); if (mainActivityClass == null) { throw new JadxRuntimeException("Failed to find main activity class: " + results.getMainActivity()); } tabsController.codeJump(getCacheObject().getNodeCache().makeFrom(mainActivityClass)); } catch (Exception e) { LOG.error("Main activity not found", e); JOptionPane.showMessageDialog(MainWindow.this, NLS.str("error_dialog.not_found", "Main Activity"), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); } } public void goToApplication() { AndroidManifestParser parser = new AndroidManifestParser(
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
true
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/JadxEventQueue.java
jadx-gui/src/main/java/jadx/gui/ui/JadxEventQueue.java
package jadx.gui.ui; import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import jadx.commons.app.JadxSystemInfo; public class JadxEventQueue extends EventQueue { private static final boolean IS_X_TOOLKIT = JadxSystemInfo.IS_LINUX && "sun.awt.X11.XToolkit".equals(Toolkit.getDefaultToolkit().getClass().getName()); public static void register() { if (IS_X_TOOLKIT) { Toolkit.getDefaultToolkit().getSystemEventQueue().push(new JadxEventQueue()); } } private JadxEventQueue() { } @Override protected void dispatchEvent(AWTEvent event) { AWTEvent mappedEvent = mapEvent(event); super.dispatchEvent(mappedEvent); } private static AWTEvent mapEvent(AWTEvent event) { if (IS_X_TOOLKIT && event instanceof MouseEvent && ((MouseEvent) event).getButton() > 3) { return mapXWindowMouseEvent((MouseEvent) event); } return event; } @SuppressWarnings({ "deprecation", "MagicConstant" }) private static AWTEvent mapXWindowMouseEvent(MouseEvent src) { if (src.getButton() < 6) { // buttons 4-5 come from touchpad, they must be converted to horizontal scrolling events int modifiers = src.getModifiers() | InputEvent.SHIFT_DOWN_MASK; return new MouseWheelEvent(src.getComponent(), MouseEvent.MOUSE_WHEEL, src.getWhen(), modifiers, src.getX(), src.getY(), 0, false, MouseWheelEvent.WHEEL_UNIT_SCROLL, src.getClickCount(), src.getButton() == 4 ? -1 : 1); } else { // Here we "shift" events with buttons `6` and `7` to similar events with buttons 4 and 5 // See `java.awt.InputEvent#BUTTON_DOWN_MASK`, 1<<14 is the 4th physical button, 1<<15 is the 5th. int modifiers = src.getModifiers() | (1 << (8 + src.getButton())); return new MouseEvent(src.getComponent(), src.getID(), src.getWhen(), modifiers, src.getX(), src.getY(), 1, src.isPopupTrigger(), src.getButton() - 2); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/HeapUsageBar.java
jadx-gui/src/main/java/jadx/gui/ui/HeapUsageBar.java
package jadx.gui.ui; import java.awt.Color; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.swing.FocusManager; import javax.swing.JProgressBar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import hu.akarnokd.rxjava3.swing.SwingSchedulers; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.schedulers.Schedulers; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class HeapUsageBar extends JProgressBar { private static final long serialVersionUID = -8739563124249884967L; private static final Logger LOG = LoggerFactory.getLogger(HeapUsageBar.class); private static final double GB = 1024 * 1024 * 1024d; private static final Color GREEN = new Color(0, 180, 0); private static final Color RED = new Color(200, 0, 0); private final transient Runtime runtime = Runtime.getRuntime(); private final transient FocusManager focusManager = FocusManager.getCurrentManager(); private final double maxGB; private final long limit; private final String labelTemplate; private transient Disposable timer; private transient Color currentColor; public HeapUsageBar() { setBorderPainted(false); setStringPainted(true); long maxMemory = runtime.maxMemory(); maxGB = maxMemory / GB; limit = maxMemory - UiUtils.MIN_FREE_MEMORY; labelTemplate = NLS.str("heapUsage.text"); setMaximum((int) (maxMemory / 1024)); setColor(GREEN); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Runtime.getRuntime().gc(); HeapUsageBar.this.update(); if (LOG.isDebugEnabled()) { LOG.debug("Memory used: {}", UiUtils.memoryInfo()); } } }); } @Override public void setVisible(boolean enabled) { super.setVisible(enabled); if (enabled) { startTimer(); } else { reset(); } } private static class UpdateData { int value; String label; Color color; } private static final UpdateData SKIP_UPDATE = new UpdateData(); private void startTimer() { if (timer != null) { return; } update(); timer = Flowable.interval(2, TimeUnit.SECONDS, Schedulers.newThread()) .map(i -> prepareUpdate()) .filter(update -> update != SKIP_UPDATE) .distinctUntilChanged((a, b) -> Objects.equals(a.label, b.label)) // pass only if label changed .subscribeOn(SwingSchedulers.edt()) .subscribe(this::applyUpdate); } public UpdateData prepareUpdate() { if (focusManager.getActiveWindow() == null) { // skip update if app window not active return SKIP_UPDATE; } UpdateData updateData = new UpdateData(); long used = runtime.totalMemory() - runtime.freeMemory(); updateData.value = (int) (used / 1024); updateData.label = String.format(labelTemplate, used / GB, maxGB); updateData.color = used > limit ? RED : GREEN; return updateData; } public void applyUpdate(UpdateData update) { setValue(update.value); setString(update.label); setColor(update.color); } private void setColor(Color color) { if (currentColor != color) { setForeground(color); currentColor = color; } } private void update() { UpdateData update = prepareUpdate(); if (update != SKIP_UPDATE) { applyUpdate(update); } } public void reset() { if (timer != null) { timer.dispose(); timer = null; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/startpage/StartPagePanel.java
jadx-gui/src/main/java/jadx/gui/ui/startpage/StartPagePanel.java
package jadx.gui.ui.startpage; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.nio.file.Path; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import jadx.gui.settings.JadxSettings; import jadx.gui.ui.MainWindow; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.Icons; import jadx.gui.utils.NLS; public class StartPagePanel extends ContentPanel { private static final long serialVersionUID = 2457805175218770732L; private final RecentProjectsJList recentList; private final DefaultListModel<RecentProjectItem> recentListModel; private final MainWindow mainWindow; private final JadxSettings settings; public static int hoveredRemoveBtnIndex = -1; public StartPagePanel(TabbedPane tabbedPane, StartPageNode node) { super(tabbedPane, node); this.mainWindow = tabbedPane.getMainWindow(); this.settings = mainWindow.getSettings(); Font baseFont = settings.getUiFont(); JButton openFile = new JButton(NLS.str("file.open_title"), Icons.OPEN); openFile.addActionListener(ev -> mainWindow.openFileDialog()); JButton openProject = new JButton(NLS.str("file.open_project"), Icons.OPEN_PROJECT); openProject.addActionListener(ev -> mainWindow.openProjectDialog()); JPanel start = new JPanel(); start.setBorder(sectionFrame(NLS.str("start_page.start"), baseFont)); start.setLayout(new BoxLayout(start, BoxLayout.LINE_AXIS)); start.add(openFile); start.add(Box.createRigidArea(new Dimension(10, 0))); start.add(openProject); start.add(Box.createHorizontalGlue()); this.recentListModel = new DefaultListModel<>(); this.recentList = new RecentProjectsJList(recentListModel); this.recentList.setCellRenderer(new RecentProjectListCellRenderer(baseFont)); this.recentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane scrollPane = new JScrollPane(recentList); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setPreferredSize(new Dimension(400, 250)); scrollPane.setBorder(BorderFactory.createEmptyBorder()); recentList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int index = recentList.locationToIndex(e.getPoint()); if (index == -1) { return; } RecentProjectItem item = recentListModel.getElementAt(index); if (item == null) { return; } RecentProjectListCellRenderer renderer = (RecentProjectListCellRenderer) recentList.getCellRenderer() .getListCellRendererComponent(recentList, item, index, false, false); Rectangle cellBounds = recentList.getCellBounds(index, index); if (cellBounds != null) { int xInCell = e.getX() - cellBounds.x; int yInCell = e.getY() - cellBounds.y; Rectangle removeIconBounds = renderer.getRemoveIconBounds(); if (removeIconBounds != null && removeIconBounds.contains(xInCell, yInCell)) { removeRecentProject(item.getPath()); return; } } if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) { openRecentProject(item.getPath()); } else if (SwingUtilities.isRightMouseButton(e)) { recentList.setSelectedIndex(index); showRecentProjectContextMenu(e); } } }); recentList.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { int oldHoveredRemoveBtnIndex = hoveredRemoveBtnIndex; hoveredRemoveBtnIndex = -1; int currentCellIndex = recentList.locationToIndex(e.getPoint()); if (currentCellIndex != -1) { RecentProjectItem item = recentListModel.getElementAt(currentCellIndex); RecentProjectListCellRenderer renderer = (RecentProjectListCellRenderer) recentList.getCellRenderer() .getListCellRendererComponent(recentList, item, currentCellIndex, recentList.isSelectedIndex(currentCellIndex), false); Rectangle cellBounds = recentList.getCellBounds(currentCellIndex, currentCellIndex); if (cellBounds != null) { int xInCell = e.getX() - cellBounds.x; int yInCell = e.getY() - cellBounds.y; Rectangle removeIconBounds = renderer.getRemoveIconBounds(); if (removeIconBounds != null && removeIconBounds.contains(xInCell, yInCell)) { hoveredRemoveBtnIndex = currentCellIndex; } } } if (oldHoveredRemoveBtnIndex != hoveredRemoveBtnIndex) { if (oldHoveredRemoveBtnIndex != -1) { Rectangle bounds = recentList.getCellBounds(oldHoveredRemoveBtnIndex, oldHoveredRemoveBtnIndex); if (bounds != null) { recentList.repaint(bounds); } } if (hoveredRemoveBtnIndex != -1) { Rectangle bounds = recentList.getCellBounds(hoveredRemoveBtnIndex, hoveredRemoveBtnIndex); if (bounds != null) { recentList.repaint(bounds); } } } } }); JPanel recent = new JPanel(); recent.setBorder(sectionFrame(NLS.str("start_page.recent"), baseFont)); recent.setLayout(new BoxLayout(recent, BoxLayout.PAGE_AXIS)); recent.add(scrollPane); JPanel center = new JPanel(); center.setLayout(new BorderLayout(10, 10)); center.add(start, BorderLayout.PAGE_START); center.add(recent, BorderLayout.CENTER); center.setMaximumSize(new Dimension(700, 600)); center.setAlignmentX(CENTER_ALIGNMENT); setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50)); add(Box.createVerticalGlue()); add(center); add(Box.createVerticalGlue()); fillRecentProjectsList(); } private void fillRecentProjectsList() { recentListModel.clear(); List<Path> recentPaths = settings.getRecentProjects(); for (Path path : recentPaths) { recentListModel.addElement(new RecentProjectItem(path)); } recentList.revalidate(); recentList.repaint(); } private void openRecentProject(Path path) { mainWindow.open(path); } private void removeRecentProject(Path path) { settings.removeRecentProject(path); fillRecentProjectsList(); if (hoveredRemoveBtnIndex != -1 && hoveredRemoveBtnIndex >= recentListModel.size()) { hoveredRemoveBtnIndex = -1; } } private void showRecentProjectContextMenu(MouseEvent e) { JPopupMenu popupMenu = new JPopupMenu(); RecentProjectItem selectedItem = recentList.getSelectedValue(); if (selectedItem != null) { JMenuItem openItem = new JMenuItem(NLS.str("file.open_project")); openItem.addActionListener(actionEvent -> openRecentProject(selectedItem.getPath())); popupMenu.add(openItem); JMenuItem removeItem = new JMenuItem(NLS.str("start_page.list.delete_recent_project")); removeItem.addActionListener(actionEvent -> removeRecentProject(selectedItem.getPath())); popupMenu.add(removeItem); } popupMenu.show(e.getComponent(), e.getX(), e.getY()); } private static Border sectionFrame(String title, Font font) { TitledBorder titledBorder = BorderFactory.createTitledBorder(title); titledBorder.setTitleFont(font.deriveFont(Font.BOLD, font.getSize() + 1)); Border spacing = BorderFactory.createEmptyBorder(10, 10, 10, 10); return BorderFactory.createCompoundBorder(titledBorder, spacing); } @Override public void loadSettings() { } /** * Inner class: Custom JList to override getToolTipText method. * This allows displaying specific tooltips based on mouse position within a cell. */ private static class RecentProjectsJList extends JList<RecentProjectItem> { private static final long serialVersionUID = 1L; public RecentProjectsJList(DefaultListModel<RecentProjectItem> model) { super(model); } @Override public String getToolTipText(MouseEvent event) { int index = locationToIndex(event.getPoint()); if (index == -1) { return null; } RecentProjectItem item = getModel().getElementAt(index); if (item == null) { return null; } RecentProjectListCellRenderer renderer = (RecentProjectListCellRenderer) getCellRenderer() .getListCellRendererComponent(this, item, index, isSelectedIndex(index), false); Rectangle cellBounds = getCellBounds(index, index); if (cellBounds != null) { int xInCell = event.getX() - cellBounds.x; int yInCell = event.getY() - cellBounds.y; Rectangle removeIconBounds = renderer.getRemoveIconBounds(); if (removeIconBounds != null && removeIconBounds.contains(xInCell, yInCell)) { return NLS.str("start_page.list.delete_recent_project.tooltip"); } } return item.getAbsolutePath(); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/startpage/RecentProjectListCellRenderer.java
jadx-gui/src/main/java/jadx/gui/ui/startpage/RecentProjectListCellRenderer.java
package jadx.gui.ui.startpage; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.awt.Rectangle; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.plaf.basic.BasicButtonUI; import jadx.gui.utils.Icons; public class RecentProjectListCellRenderer extends JPanel implements ListCellRenderer<RecentProjectItem> { private static final long serialVersionUID = 5550591869239586857L; private final JLabel fileNameLabel; private final JLabel pathLabel; private final JButton removeProjectBtn; private final Color defaultBackground; private final Color defaultForeground; private final Color selectedBackground; private final Color selectedForeground; private Rectangle removeIconBounds; public RecentProjectListCellRenderer(Font baseFont) { super(new BorderLayout(5, 0)); setOpaque(true); setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 5)); this.fileNameLabel = new JLabel(); fileNameLabel.setFont(baseFont.deriveFont(Font.BOLD, baseFont.getSize())); this.pathLabel = new JLabel(); pathLabel.setFont(baseFont.deriveFont(baseFont.getSize() - 2f)); pathLabel.setForeground(UIManager.getColor("Label.disabledForeground")); JPanel textPanel = new JPanel(new BorderLayout()); textPanel.setOpaque(false); textPanel.add(fileNameLabel, BorderLayout.NORTH); textPanel.add(pathLabel, BorderLayout.SOUTH); removeProjectBtn = new JButton(); removeProjectBtn.setIcon(Icons.CLOSE_INACTIVE); removeProjectBtn.setOpaque(false); removeProjectBtn.setUI(new BasicButtonUI()); removeProjectBtn.setContentAreaFilled(false); removeProjectBtn.setFocusable(false); removeProjectBtn.setBorder(null); removeProjectBtn.setBorderPainted(false); add(textPanel, BorderLayout.CENTER); add(removeProjectBtn, BorderLayout.EAST); defaultBackground = UIManager.getColor("List.background"); defaultForeground = UIManager.getColor("List.foreground"); selectedBackground = UIManager.getColor("List.selectionBackground"); selectedForeground = UIManager.getColor("List.selectionForeground"); } @Override public Component getListCellRendererComponent(JList<? extends RecentProjectItem> list, RecentProjectItem value, int index, boolean isSelected, boolean cellHasFocus) { fileNameLabel.setText(value.getProjectName()); pathLabel.setText(value.getAbsolutePath()); boolean isThisRemoveButtonHovered = (index == StartPagePanel.hoveredRemoveBtnIndex); removeProjectBtn.setIcon(isThisRemoveButtonHovered ? Icons.CLOSE : Icons.CLOSE_INACTIVE); removeProjectBtn.setRolloverEnabled(isThisRemoveButtonHovered); if (isSelected) { setBackground(selectedBackground); fileNameLabel.setForeground(selectedForeground); pathLabel.setForeground(selectedForeground.darker()); removeProjectBtn.setForeground(selectedForeground); } else { setBackground(defaultBackground); fileNameLabel.setForeground(defaultForeground); pathLabel.setForeground(UIManager.getColor("Label.disabledForeground")); removeProjectBtn.setForeground(defaultForeground); } setToolTipText(value.getAbsolutePath()); return this; } /** * Overriding paint to calculate the bounds of the remove button. * This is crucial for the MouseListener on the JList to determine if a click/hover was on the * button. */ @Override public void paint(Graphics g) { super.paint(g); // Ensure the button's layout is valid before getting bounds removeProjectBtn.doLayout(); // Calculate bounds of the remove button relative to this renderer panel int x = getWidth() - removeProjectBtn.getWidth() - getBorder().getBorderInsets(this).right; int y = (getHeight() - removeProjectBtn.getHeight()) / 2; removeIconBounds = new Rectangle(x, y, removeProjectBtn.getWidth(), removeProjectBtn.getHeight()); } /** * Returns the bounds of the remove button within the renderer component's coordinate system. * This is crucial for the MouseListener on the JList to determine if a click was on the icon. * * @return Rectangle representing the bounds of the remove icon. */ public Rectangle getRemoveIconBounds() { return removeIconBounds; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/startpage/StartPageNode.java
jadx-gui/src/main/java/jadx/gui/ui/startpage/StartPageNode.java
package jadx.gui.ui.startpage; import javax.swing.Icon; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.Icons; import jadx.gui.utils.NLS; public class StartPageNode extends JNode { private static final long serialVersionUID = 8983134608645736174L; @Override public boolean hasContent() { return true; } @Override public ContentPanel getContentPanel(TabbedPane tabbedPane) { return new StartPagePanel(tabbedPane, this); } @Override public String makeString() { return NLS.str("start_page.title"); } @Override public Icon getIcon() { return Icons.START_PAGE; } @Override public JClass getJParent() { return null; } @Override public boolean supportsQuickTabs() { return false; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/startpage/RecentProjectItem.java
jadx-gui/src/main/java/jadx/gui/ui/startpage/RecentProjectItem.java
package jadx.gui.ui.startpage; import java.nio.file.Path; import java.util.Objects; import jadx.api.plugins.utils.CommonFileUtils; /** * Represents an item in the recent projects list. */ public class RecentProjectItem { private final Path path; public RecentProjectItem(Path path) { this.path = Objects.requireNonNull(path); } public Path getPath() { return path; } public String getProjectName() { return CommonFileUtils.removeFileExtension(path.getFileName().toString()); } public String getAbsolutePath() { return path.toAbsolutePath().toString(); } @Override public String toString() { return getProjectName(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RecentProjectItem that = (RecentProjectItem) o; return Objects.equals(path, that.path); } @Override public int hashCode() { return Objects.hash(path); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/ADBDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/ADBDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.commons.app.JadxSystemInfo; import jadx.core.utils.StringUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.device.debugger.DbgUtils; import jadx.gui.device.debugger.DebugSettings; import jadx.gui.device.protocol.ADB; import jadx.gui.device.protocol.ADBDevice; import jadx.gui.device.protocol.ADBDeviceInfo; import jadx.gui.settings.JadxSettings; import jadx.gui.ui.MainWindow; import jadx.gui.ui.panel.IDebugController; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class ADBDialog extends JDialog implements ADB.DeviceStateListener, ADB.JDWPProcessListener { private static final Logger LOG = LoggerFactory.getLogger(ADBDialog.class); private static final long serialVersionUID = -1111111202102181630L; private static final ImageIcon ICON_DEVICE = UiUtils.openSvgIcon("adb/androidDevice"); private static final ImageIcon ICON_PROCESS = UiUtils.openSvgIcon("adb/addToWatch"); private final transient MainWindow mainWindow; private transient Label tipLabel; private transient JTextField pathTextField; private transient JTextField hostTextField; private transient JTextField portTextField; private transient DefaultTreeModel procTreeModel; private transient DefaultMutableTreeNode procTreeRoot; private transient JTree procTree; private Socket deviceSocket; private transient List<DeviceNode> deviceNodes = new ArrayList<>(); private transient DeviceNode lastSelectedDeviceNode; public ADBDialog(MainWindow mainWindow) { super(mainWindow); this.mainWindow = mainWindow; initUI(); pathTextField.setText(mainWindow.getSettings().getAdbDialogPath()); hostTextField.setText(mainWindow.getSettings().getAdbDialogHost()); portTextField.setText(mainWindow.getSettings().getAdbDialogPort()); if (pathTextField.getText().isEmpty()) { detectADBPath(); } else { pathTextField.setText(""); } SwingUtilities.invokeLater(this::connectToADB); UiUtils.addEscapeShortCutToDispose(this); } private void initUI() { pathTextField = new JTextField(); portTextField = new JTextField(); hostTextField = new JTextField(); JPanel adbPanel = new JPanel(new BorderLayout(5, 5)); adbPanel.add(new JLabel(NLS.str("adb_dialog.path")), BorderLayout.WEST); adbPanel.add(pathTextField, BorderLayout.CENTER); JPanel portPanel = new JPanel(new BorderLayout(5, 0)); portPanel.add(new JLabel(NLS.str("adb_dialog.port")), BorderLayout.WEST); portPanel.add(portTextField, BorderLayout.CENTER); JPanel hostPanel = new JPanel(new BorderLayout(5, 0)); hostPanel.add(new JLabel(NLS.str("adb_dialog.addr")), BorderLayout.WEST); hostPanel.add(hostTextField, BorderLayout.CENTER); JPanel wrapperPanel = new JPanel(new GridLayout(1, 2, 5, 0)); wrapperPanel.add(hostPanel); wrapperPanel.add(portPanel); adbPanel.add(wrapperPanel, BorderLayout.SOUTH); procTree = new JTree(); JScrollPane scrollPane = new JScrollPane(procTree); scrollPane.setMinimumSize(new Dimension(100, 150)); scrollPane.setBorder(BorderFactory.createLineBorder(Color.black)); procTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); procTreeRoot = new DefaultMutableTreeNode(NLS.str("adb_dialog.device_node")); procTreeModel = new DefaultTreeModel(procTreeRoot); procTree.setModel(procTreeModel); procTree.setRowHeight(-1); procTree.setFont(mainWindow.getSettings().getCodeFont()); procTree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { processSelected(e); } } }); procTree.setCellRenderer(new DefaultTreeCellRenderer() { private static final long serialVersionUID = -1111111202103170735L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); if (value instanceof DeviceTreeNode || value == procTreeRoot) { setIcon(ICON_DEVICE); } else { setIcon(ICON_PROCESS); } return c; } }); procTree.addTreeSelectionListener(event -> { Object selectedNode = procTree.getLastSelectedPathComponent(); if (selectedNode instanceof DeviceTreeNode) { lastSelectedDeviceNode = deviceNodes.stream() .filter(item -> item.tNode == selectedNode) .findFirst().orElse(null); } }); JPanel btnPane = new JPanel(); BoxLayout boxLayout = new BoxLayout(btnPane, BoxLayout.LINE_AXIS); btnPane.setLayout(boxLayout); tipLabel = new Label(NLS.str("adb_dialog.waiting")); btnPane.add(tipLabel); JButton refreshBtn = new JButton(NLS.str("adb_dialog.refresh")); JButton startServerBtn = new JButton(NLS.str("adb_dialog.start_server")); JButton launchAppBtn = new JButton(NLS.str("adb_dialog.launch_app")); btnPane.add(launchAppBtn); btnPane.add(startServerBtn); btnPane.add(refreshBtn); refreshBtn.addActionListener(e -> { clear(); procTreeRoot.removeAllChildren(); procTreeModel.reload(procTreeRoot); SwingUtilities.invokeLater(this::connectToADB); }); startServerBtn.addActionListener(e -> startADBServer()); launchAppBtn.addActionListener(e -> launchApp()); JPanel mainPane = new JPanel(new BorderLayout(5, 5)); mainPane.add(adbPanel, BorderLayout.NORTH); mainPane.add(scrollPane, BorderLayout.CENTER); mainPane.add(btnPane, BorderLayout.SOUTH); mainPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); getContentPane().add(mainPane); pack(); setSize(800, 500); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setModalityType(ModalityType.MODELESS); } private void clear() { if (deviceSocket != null) { try { deviceSocket.close(); } catch (Exception e) { LOG.error("Failed to close device socket", e); } deviceSocket = null; } for (DeviceNode deviceNode : deviceNodes) { deviceNode.device.stopListenForJDWP(); } deviceNodes.clear(); } private void detectADBPath() { boolean isWinOS = JadxSystemInfo.IS_WINDOWS; String slash = isWinOS ? "\\" : "/"; String adbName = isWinOS ? "adb.exe" : "adb"; String sdkPath = System.getenv("ANDROID_HOME"); if (!StringUtils.isEmpty(sdkPath)) { if (!sdkPath.endsWith(slash)) { sdkPath += slash; } sdkPath += "platform-tools" + slash + adbName; if ((new File(sdkPath)).exists()) { pathTextField.setText(sdkPath); return; } } String envPath = System.getenv("PATH"); String[] paths = envPath.split(isWinOS ? ";" : ":"); for (String path : paths) { if (!path.endsWith(slash)) { path += slash; } path = path + adbName; if (new File(path).exists()) { pathTextField.setText(path); return; } } } private void startADBServer() { String path = pathTextField.getText(); if (path.isEmpty()) { UiUtils.showMessageBox(mainWindow, NLS.str("adb_dialog.missing_path")); return; } String tip; try { if (ADB.startServer(path, Integer.parseInt(portTextField.getText()))) { tip = NLS.str("adb_dialog.start_okay", portTextField.getText()); } else { tip = NLS.str("adb_dialog.start_fail", portTextField.getText()); } } catch (Exception e) { LOG.error("Failed to start adb server", e); tip = e.getMessage(); } UiUtils.showMessageBox(mainWindow, tip); tipLabel.setText(tip); } private void connectToADB() { String tip; try { String host = hostTextField.getText().trim(); String port = portTextField.getText().trim(); tipLabel.setText(NLS.str("adb_dialog.connecting", host, port)); deviceSocket = ADB.listenForDeviceState(this, host, Integer.parseInt(port)); if (deviceSocket != null) { tip = NLS.str("adb_dialog.connect_okay", host, port); this.setTitle(tip); } else { tip = NLS.str("adb_dialog.connect_fail"); } } catch (Exception e) { LOG.error("Failed to connect to adb", e); tip = e.getMessage(); UiUtils.showMessageBox(mainWindow, tip); } tipLabel.setText(tip); } @Override public void onDeviceStatusChange(List<ADBDeviceInfo> deviceInfoList) { List<DeviceNode> nodes = new ArrayList<>(deviceInfoList.size()); info_loop: for (ADBDeviceInfo info : deviceInfoList) { for (DeviceNode deviceNode : deviceNodes) { if (deviceNode.device.updateDeviceInfo(info)) { deviceNode.refresh(); nodes.add(deviceNode); continue info_loop; } } ADBDevice device = new ADBDevice(info); device.getAndroidReleaseVersion(); nodes.add(new DeviceNode(device)); listenJDWP(device); } deviceNodes = nodes; SwingUtilities.invokeLater(() -> { tipLabel.setText(NLS.str("adb_dialog.tip_devices", deviceNodes.size())); procTreeRoot.removeAllChildren(); deviceNodes.forEach(n -> procTreeRoot.add(n.tNode)); procTreeModel.reload(procTreeRoot); for (DeviceNode deviceNode : deviceNodes) { procTree.expandPath(new TreePath(deviceNode.tNode.getPath())); } }); } private void processSelected(MouseEvent e) { TreePath path = procTree.getPathForLocation(e.getX(), e.getY()); if (path != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent(); String pid = getPid((String) node.getUserObject()); if (StringUtils.isEmpty(pid)) { return; } if (mainWindow.getDebuggerPanel() != null && mainWindow.getDebuggerPanel().getDbgController().isDebugging()) { if (JOptionPane.showConfirmDialog(mainWindow, NLS.str("adb_dialog.restart_while_debugging_msg"), NLS.str("adb_dialog.restart_while_debugging_title"), JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) { IDebugController ctrl = mainWindow.getDebuggerPanel().getDbgController(); if (launchForDebugging(mainWindow, ctrl.getProcessName(), true)) { dispose(); } } return; } DeviceNode deviceNode = getDeviceNode((DefaultMutableTreeNode) node.getParent()); if (deviceNode == null) { return; } if (!setupArgs(deviceNode.device, pid, (String) node.getUserObject())) { return; } if (DebugSettings.INSTANCE.isBeingDebugged()) { if (JOptionPane.showConfirmDialog(mainWindow, NLS.str("adb_dialog.being_debugged_msg"), NLS.str("adb_dialog.being_debugged_title"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) { return; } } tipLabel.setText(NLS.str("adb_dialog.starting_debugger")); if (!attachProcess(mainWindow)) { tipLabel.setText(NLS.str("adb_dialog.init_dbg_fail")); } else { dispose(); } } } private static boolean attachProcess(MainWindow mainWindow) { DebugSettings debugSettings = DebugSettings.INSTANCE; debugSettings.clearForward(); String rst = debugSettings.forwardJDWP(); if (!rst.isEmpty()) { UiUtils.showMessageBox(mainWindow, rst); return false; } try { return mainWindow.getDebuggerPanel().showDebugger( debugSettings.getName(), debugSettings.getDevice().getDeviceInfo().getAdbHost(), debugSettings.getForwardTcpPort(), debugSettings.getVer(), debugSettings.getDevice(), debugSettings.getPid()); } catch (Exception e) { LOG.error("Failed to attach to process", e); return false; } } public static boolean launchForDebugging(MainWindow mainWindow, String fullAppPath, boolean autoAttach) { DebugSettings debugSettings = DebugSettings.INSTANCE; debugSettings.setAutoAttachPkg(autoAttach); try { int pid = debugSettings.getDevice().launchApp(fullAppPath); if (pid != -1) { debugSettings.setPid(String.valueOf(pid)) .setName(fullAppPath); return attachProcess(mainWindow); } } catch (Exception e) { LOG.error("Failed to launch app", e); } return false; } private String getPid(String nodeText) { if (nodeText.startsWith("[pid:")) { int pos = nodeText.indexOf(']', "[pid:".length()); if (pos != -1) { return nodeText.substring("[pid:".length(), pos).trim(); } } return null; } private DeviceNode getDeviceNode(DefaultMutableTreeNode node) { for (DeviceNode deviceNode : deviceNodes) { if (deviceNode.tNode == node) { return deviceNode; } } return null; } private DeviceNode getDeviceNode(ADBDevice device) { for (DeviceNode deviceNode : deviceNodes) { if (deviceNode.device.equals(device)) { return deviceNode; } } throw new JadxRuntimeException("Unexpected device: " + device); } private void listenJDWP(ADBDevice device) { try { device.listenForJDWP(this); } catch (Exception e) { LOG.error("Failed listen for JDWP", e); } } @Override public void dispose() { clear(); JadxSettings settings = mainWindow.getSettings(); boolean changed = !settings.getAdbDialogPath().equals(pathTextField.getText()); changed |= !settings.getAdbDialogHost().equals(hostTextField.getText()); changed |= !settings.getAdbDialogPort().equals(portTextField.getText()); if (changed) { settings.setAdbDialogPath(pathTextField.getText()); settings.setAdbDialogHost(hostTextField.getText()); settings.setAdbDialogPort(portTextField.getText()); settings.sync(); } super.dispose(); } @Override public void adbDisconnected() { deviceSocket = null; SwingUtilities.invokeLater(() -> { tipLabel.setText(NLS.str("adb_dialog.disconnected")); this.setTitle(""); }); } @Override public void jdwpProcessOccurred(ADBDevice device, Set<String> id) { List<ADB.Process> procs; try { Thread.sleep(40); /* * wait for a moment, let the new processes on remote be fully initialized, * otherwise we may not get its real name but the <pre-initialized> state text. */ procs = device.getProcessList(); } catch (Exception e) { LOG.error("Failed to get device process list", e); procs = Collections.emptyList(); } List<String> procList = new ArrayList<>(id.size()); if (procs.isEmpty()) { procList.addAll(id); } else { for (ADB.Process proc : procs) { if (id.contains(proc.pid)) { procList.add(String.format("[pid: %-6s] %s", proc.pid, proc.name)); } } } Collections.reverse(procList); DeviceNode node; try { node = getDeviceNode(device); } catch (Exception e) { LOG.error("Failed to find device", e); return; } SwingUtilities.invokeLater(() -> { node.tNode.removeAllChildren(); DefaultMutableTreeNode foundNode = null; DebugSettings debugSettings = DebugSettings.INSTANCE; for (String procStr : procList) { DefaultMutableTreeNode pnode = new DefaultMutableTreeNode(procStr); node.tNode.add(pnode); if (!debugSettings.getExpectPkg().isEmpty() && procStr.endsWith(debugSettings.getExpectPkg())) { if (debugSettings.isAutoAttachPkg() && debugSettings.getDevice().equals(node.device)) { debugSettings.set(node.device, debugSettings.getVer(), getPid(procStr), procStr); if (attachProcess(mainWindow)) { dispose(); return; } } foundNode = pnode; } } procTreeModel.reload(node.tNode); procTree.expandPath(new TreePath(node.tNode.getPath())); if (foundNode != null) { TreePath thePath = new TreePath(foundNode.getPath()); procTree.scrollPathToVisible(thePath); procTree.setSelectionPath(thePath); } }); } private void launchApp() { if (deviceNodes.isEmpty()) { UiUtils.showMessageBox(mainWindow, NLS.str("adb_dialog.no_devices")); return; } DbgUtils.AppData appData = DbgUtils.parseAppData(mainWindow); if (appData == null) { // error already reported return; } if (scrollToProcNode(appData.getAppPackage())) { return; } String processName = appData.getProcessName(); ADBDevice device = lastSelectedDeviceNode == null ? deviceNodes.get(0).device : lastSelectedDeviceNode.device; if (device != null) { try { device.launchApp(processName); } catch (Exception e) { LOG.error("Failed to launch app: {}", processName, e); UiUtils.showMessageBox(mainWindow, e.getMessage()); } } } private boolean scrollToProcNode(String pkg) { if (pkg.isEmpty()) { return false; } DebugSettings.INSTANCE.setExpectPkg(" " + pkg); for (int i = 0; i < procTreeRoot.getChildCount(); i++) { DefaultMutableTreeNode rn = (DefaultMutableTreeNode) procTreeRoot.getChildAt(i); for (int j = 0; j < rn.getChildCount(); j++) { DefaultMutableTreeNode n = (DefaultMutableTreeNode) rn.getChildAt(j); String pName = (String) n.getUserObject(); if (pName.endsWith(DebugSettings.INSTANCE.getExpectPkg())) { TreePath path = new TreePath(n.getPath()); procTree.scrollPathToVisible(path); procTree.setSelectionPath(path); return true; } } } return false; } @Override public void jdwpListenerClosed(ADBDevice device) { } private static class DeviceTreeNode extends DefaultMutableTreeNode { private static final long serialVersionUID = -1111111202103131112L; } private static class DeviceNode { ADBDevice device; DeviceTreeNode tNode; DeviceNode(ADBDevice adbDevice) { this.device = adbDevice; tNode = new DeviceTreeNode(); refresh(); } void refresh() { ADBDeviceInfo info = device.getDeviceInfo(); String text = info.getModel(); if (text != null) { if (!text.equals(info.getSerial())) { text += String.format(" [serial: %s]", info.getSerial()); } text += String.format(" [state: %s]", info.isOnline() ? "online" : "offline"); tNode.setUserObject(text); } } } private boolean setupArgs(ADBDevice device, String pid, String name) { String ver = device.getAndroidReleaseVersion(); if (StringUtils.isEmpty(ver)) { if (JOptionPane.showConfirmDialog(mainWindow, NLS.str("adb_dialog.unknown_android_ver"), "", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) { return false; } ver = "8"; } ver = getMajorVer(ver); DebugSettings.INSTANCE.set(device, Integer.parseInt(ver), pid, name); return true; } private String getMajorVer(String ver) { int pos = ver.indexOf('.'); if (pos != -1) { ver = ver.substring(0, pos); } return ver; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/ExcludePkgDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/ExcludePkgDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.WindowConstants; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import jadx.api.JavaPackage; import jadx.gui.ui.MainWindow; import jadx.gui.utils.Icons; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class ExcludePkgDialog extends JDialog { private static final long serialVersionUID = -1111111202104151030L; private final transient MainWindow mainWindow; private transient JTree tree; private transient DefaultMutableTreeNode treeRoot; private final transient List<PkgNode> roots = new ArrayList<>(); public ExcludePkgDialog(MainWindow mainWindow) { super(mainWindow); this.mainWindow = mainWindow; initUI(); UiUtils.addEscapeShortCutToDispose(this); initPackageList(); } private void initUI() { setTitle(NLS.str("exclude_dialog.title")); tree = new JTree(); tree.setRowHeight(-1); treeRoot = new DefaultMutableTreeNode("Packages"); DefaultTreeModel treeModel = new DefaultTreeModel(treeRoot); tree.setModel(treeModel); tree.setCellRenderer(new PkgListCellRenderer()); JScrollPane listPanel = new JScrollPane(tree); listPanel.setBorder(BorderFactory.createEmptyBorder()); tree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path != null && path.getLastPathComponent() instanceof PkgNode) { PkgNode node = (PkgNode) path.getLastPathComponent(); node.toggle(); repaint(); } } }); JPanel actionPanel = new JPanel(); actionPanel.setLayout(new BoxLayout(actionPanel, BoxLayout.LINE_AXIS)); JButton btnOk = new JButton(NLS.str("common_dialog.ok")); JButton btnAll = new JButton(NLS.str("exclude_dialog.select_all")); JButton btnInvert = new JButton(NLS.str("exclude_dialog.invert")); JButton btnDeselect = new JButton(NLS.str("exclude_dialog.deselect")); actionPanel.add(btnDeselect); actionPanel.add(Box.createRigidArea(new Dimension(10, 0))); actionPanel.add(btnInvert); actionPanel.add(Box.createRigidArea(new Dimension(10, 0))); actionPanel.add(btnAll); actionPanel.add(Box.createHorizontalGlue()); actionPanel.add(btnOk, BorderLayout.PAGE_END); JPanel mainPane = new JPanel(new BorderLayout(5, 5)); mainPane.add(listPanel, BorderLayout.CENTER); mainPane.add(actionPanel, BorderLayout.SOUTH); mainPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); getContentPane().add(mainPane); pack(); setSize(600, 700); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setModalityType(ModalityType.MODELESS); btnOk.addActionListener(e -> { mainWindow.getWrapper().setExcludedPackages(getExcludes()); mainWindow.reopen(); dispose(); }); btnAll.addActionListener(e -> { roots.forEach(p -> p.setSelected(true)); tree.updateUI(); }); btnDeselect.addActionListener(e -> { roots.forEach(p -> p.setSelected(false)); tree.updateUI(); }); btnInvert.addActionListener(e -> { roots.forEach(PkgNode::toggle); tree.updateUI(); }); } private void initPackageList() { List<String> pkgs = mainWindow.getWrapper().getPackages() .stream() .map(JavaPackage::getFullName) .collect(Collectors.toList()); getPackageTree(pkgs).forEach(treeRoot::add); initCheckbox(); tree.expandPath(new TreePath(treeRoot.getPath())); } private List<PkgNode> getPackageTree(List<String> names) { List<PkgNode> roots = new ArrayList<>(); Set<String> nameSet = new HashSet<>(); Map<String, List<PkgNode>> childMap = new HashMap<>(); for (String name : names) { String parent = ""; int last = 0; do { int pos = name.indexOf('.', last); if (pos == -1) { pos = name.length(); } String fullName = name.substring(0, pos); if (!nameSet.contains(fullName)) { nameSet.add(fullName); PkgNode node = new PkgNode(fullName, name.substring(last, pos)); if (!parent.isEmpty()) { childMap.computeIfAbsent(parent, k -> new ArrayList<>()) .add(node); } else { roots.add(node); } } parent = fullName; last = pos + 1; } while (last < name.length()); } addToParent(null, roots, childMap); return this.roots; } private PkgNode addToParent(PkgNode parent, List<PkgNode> roots, Map<String, List<PkgNode>> childMap) { for (PkgNode root : roots) { String tempFullName = root.getFullName(); do { List<PkgNode> children = childMap.get(tempFullName); if (children != null) { if (children.size() == 1) { PkgNode next = children.get(0); next.name = root.name + "." + next.name; tempFullName = next.fullName; next.fullName = root.fullName; root = next; continue; } else { addToParent(root, children, childMap); } } if (parent == null) { this.roots.add(root); } else { parent.add(root); } break; } while (true); } return parent; } private List<String> getExcludes() { List<String> excludes = new ArrayList<>(); walkTree(true, p -> excludes.add(p.getFullName())); return excludes; } private void initCheckbox() { Font tmp = mainWindow.getSettings().getCodeFont(); Font font = tmp.deriveFont(tmp.getSize() + 1.f); Set<String> excluded = new HashSet<>(mainWindow.getWrapper().getExcludedPackages()); walkTree(false, p -> p.initCheckbox(excluded.contains(p.getFullName()), font)); } private void walkTree(boolean findSelected, Consumer<PkgNode> consumer) { List<PkgNode> queue = new ArrayList<>(roots); for (int i = 0; i < queue.size(); i++) { PkgNode node = queue.get(i); if (findSelected && node.isSelected()) { consumer.accept(node); } else { if (!findSelected) { consumer.accept(node); } for (int j = 0; j < node.getChildCount(); j++) { queue.add((PkgNode) node.getChildAt(j)); } } } } private static class PkgNode extends DefaultMutableTreeNode { private static final long serialVersionUID = -1111111202104151430L; String name; String fullName; JCheckBox checkbox; PkgNode(String fullName, String name) { this.name = name; this.fullName = fullName; } void initCheckbox(boolean select, Font font) { if (!select) { if (getParent() instanceof PkgNode) { select = ((PkgNode) getParent()).isSelected(); } } checkbox = new JCheckBox(name, select); checkbox.setFont(font); } boolean toggle() { boolean selected = !checkbox.isSelected(); setSelected(selected); toggleParents(selected); return selected; } void toggleParents(boolean select) { if (getParent() instanceof PkgNode) { PkgNode p = ((PkgNode) getParent()); if (select) { select = p.isChildrenAllSelected(); if (select) { p.checkbox.setSelected(true); p.toggleParents(true); } } else { p.checkbox.setSelected(false); p.toggleParents(false); } } } void setSelected(boolean select) { checkbox.setSelected(select); for (int i = 0; i < getChildCount(); i++) { ((PkgNode) getChildAt(i)).setSelected(select); } } boolean isSelected() { return checkbox.isSelected(); } String getFullName() { return fullName; } String getDisplayName() { return name; } boolean isChildrenAllSelected() { for (int i = 0; i < getChildCount(); i++) { if (!((PkgNode) getChildAt(i)).isSelected()) { return false; } } return true; } @Override public String toString() { return name; } } private static class PkgListCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = -1111111202104151235L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof PkgNode) { PkgNode node = (PkgNode) value; node.checkbox.setBackground(tree.getBackground()); node.checkbox.setForeground(tree.getForeground()); return node.checkbox; } Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); setIcon(Icons.PACKAGE); return c; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/UsageDialogPlus.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/UsageDialogPlus.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.JavaClass; import jadx.api.JavaMethod; import jadx.api.JavaNode; import jadx.api.utils.CodeUtils; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.visitors.prepare.CollectConstValues; import jadx.gui.JadxWrapper; import jadx.gui.jobs.TaskStatus; import jadx.gui.treemodel.CodeNode; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JField; import jadx.gui.treemodel.JMethod; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.cellrenders.PathHighlightTreeCellRenderer; import jadx.gui.ui.panel.ProgressPanel; import jadx.gui.ui.panel.SimpleCodePanel; import jadx.gui.utils.JNodeCache; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class UsageDialogPlus extends CommonSearchDialog { private static final long serialVersionUID = -5105405789969134107L; private final JPanel mainPanel; private final JSplitPane splitPane; private final SimpleCodePanel simpleCodePanel; private final JTree usageTree; private final DefaultTreeModel treeModel; private final DefaultMutableTreeNode rootNode; private final ProgressPanel localProgressPanel; private final JLabel resultsInfoLabel; private final JLabel progressInfoLabel; private final JNode initialNode; private static final Logger LOG = LoggerFactory.getLogger(UsageDialogPlus.class); public static void open(MainWindow mainWindow, JNode node) { UsageDialogPlus usageDialog = new UsageDialogPlus(mainWindow, node); mainWindow.addLoadListener(loaded -> { if (!loaded) { usageDialog.dispose(); return true; } return false; }); usageDialog.setVisible(true); // Set the position of the split panel after the window is displayed. SwingUtilities.invokeLater(() -> { int width = usageDialog.splitPane.getWidth(); if (width > 0) { usageDialog.splitPane.setDividerLocation((int) (width * 0.3)); } }); } private UsageDialogPlus(MainWindow mainWindow, JNode node) { super(mainWindow, NLS.str("usage_dialog_plus.title")); this.initialNode = node; // Initialize the progress panel and warning label progressPane = new ProgressPanel(mainWindow, false); warnLabel = new JLabel(); warnLabel.setForeground(Color.RED); warnLabel.setVisible(false); // Initialize result and progress info labels resultsInfoLabel = new JLabel(); progressInfoLabel = new JLabel(); localProgressPanel = new ProgressPanel(mainWindow, false); mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); // Create the code panel simpleCodePanel = new SimpleCodePanel(mainWindow); // Create the tree rootNode = new DefaultMutableTreeNode(node); treeModel = new DefaultTreeModel(rootNode); usageTree = new JTree(treeModel); usageTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); usageTree.setRootVisible(true); usageTree.setShowsRootHandles(true); usageTree.putClientProperty("JTree.lineStyle", "Horizontal"); usageTree.setRowHeight(22); usageTree.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); usageTree.setFont(mainWindow.getSettings().getCodeFont()); // Use a custom renderer instead of a custom UI usageTree.setCellRenderer(new PathHighlightTreeCellRenderer()); // Add tree listeners usageTree.addTreeSelectionListener(e -> { DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) usageTree.getLastSelectedPathComponent(); if (node1 == null) { return; } Object nodeInfo = node1.getUserObject(); if (nodeInfo instanceof CodeNode) { CodeNode codeNode = (CodeNode) nodeInfo; simpleCodePanel.showCode(codeNode, codeNode.makeDescString()); } else if (nodeInfo instanceof JNode) { JNode jNode = (JNode) nodeInfo; simpleCodePanel.showCode(jNode, jNode.makeDescString()); } // Update the result information to display the number of child nodes of the currently selected node updateResultsInfo(node1); }); usageTree.addTreeExpansionListener(new TreeExpansionListener() { @Override public void treeExpanded(TreeExpansionEvent event) { TreePath path = event.getPath(); DefaultMutableTreeNode expandedNode = (DefaultMutableTreeNode) path.getLastPathComponent(); // Load only when the node has no child nodes. if (expandedNode.getChildCount() == 0) { Object userObject = expandedNode.getUserObject(); if (userObject instanceof JNode) { JNode nodeToUse = (JNode) userObject; // If it is a CodeNode, first convert it to an actual JNode and then search for its usage. if (nodeToUse.getClass() == CodeNode.class) { nodeToUse = getNodeFromCodeNode((CodeNode) nodeToUse); } if (nodeToUse != null) { loadNodeUsages(nodeToUse, expandedNode); } } } } @Override public void treeCollapsed(TreeExpansionEvent event) { // No need to process } }); usageTree.addMouseListener(new MouseAdapter() { private long lastClickTime = 0; private TreePath lastClickPath = null; @Override public void mouseClicked(MouseEvent e) { TreePath path = usageTree.getPathForLocation(e.getX(), e.getY()); if (path == null) { return; } // Set the selected path usageTree.setSelectionPath(path); // Handle the right-click menu if (SwingUtilities.isRightMouseButton(e)) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent(); Object userObject = selectedNode.getUserObject(); if (userObject instanceof JNode || userObject instanceof CodeNode) { JNode nodeForMenu = (userObject instanceof JNode) ? (JNode) userObject : getNodeFromCodeNode((CodeNode) userObject); showPopupMenu(e, nodeForMenu, path); } return; } // Handle left-click single/double click if (SwingUtilities.isLeftMouseButton(e)) { long clickTime = System.currentTimeMillis(); // Double-click interval long doubleClickInterval = 300; DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent(); // If the time interval between two clicks is less than the threshold and the same node is clicked, // it is considered a double-click if ((clickTime - lastClickTime) < doubleClickInterval && path.equals(lastClickPath)) { // Double-click processing - switch between expanded/collapsed states if (usageTree.isExpanded(path)) { usageTree.collapsePath(path); } else { usageTree.expandPath(path); // If the node has no child nodes and is a JNode, load its usage if (selectedNode.getChildCount() == 0 && selectedNode.getUserObject() instanceof JNode) { JNode nodeToUse = (JNode) selectedNode.getUserObject(); // If it is a CodeNode, first convert it to an actual JNode and then search for its usage if (nodeToUse.getClass() == CodeNode.class) { nodeToUse = getNodeFromCodeNode((CodeNode) nodeToUse); } if (nodeToUse != null) { loadNodeUsages(nodeToUse, selectedNode); } } } // Update the result information to display the number of child nodes of the currently selected node updateResultsInfo(selectedNode); } else { // Single-click processing - if the node is not expanded, expand it if (!usageTree.isExpanded(path)) { usageTree.expandPath(path); // If the node has no child nodes and is a JNode, then load its usage. if (selectedNode.getChildCount() == 0 && selectedNode.getUserObject() instanceof JNode) { JNode nodeToUse = (JNode) selectedNode.getUserObject(); // If it is a CodeNode, first convert it to an actual JNode and then search for its usage if (nodeToUse.getClass() == CodeNode.class) { nodeToUse = getNodeFromCodeNode((CodeNode) nodeToUse); } if (nodeToUse != null) { loadNodeUsages(nodeToUse, selectedNode); } } } // Update the result information to display the number of child nodes of the currently selected node updateResultsInfo(selectedNode); } lastClickTime = clickTime; lastClickPath = path; } } }); // Create the split panel splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); splitPane.setOneTouchExpandable(true); splitPane.setContinuousLayout(true); splitPane.setResizeWeight(0.3); // Left 30% splitPane.setDividerSize(10); // Increase the width of the divider for easier dragging // Add tree to the scroll pane JScrollPane treeScrollPane = new JScrollPane(usageTree); treeScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); treeScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); // Create status panel JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); statusPanel.add(resultsInfoLabel); statusPanel.add(Box.createRigidArea(new Dimension(10, 0))); statusPanel.add(progressInfoLabel); statusPanel.add(Box.createRigidArea(new Dimension(10, 0))); statusPanel.add(localProgressPanel); // Add components to the main panel JPanel leftPanel = new JPanel(new BorderLayout()); leftPanel.add(treeScrollPane, BorderLayout.CENTER); leftPanel.add(statusPanel, BorderLayout.SOUTH); splitPane.setLeftComponent(leftPanel); splitPane.setRightComponent(simpleCodePanel); mainPanel.add(splitPane, BorderLayout.CENTER); initUI(); registerInitOnOpen(); loadWindowPos(); } private void initUI() { initCommon(); JPanel buttonPane = initButtonsPanel(); JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout(5, 5)); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); contentPanel.add(mainPanel, BorderLayout.CENTER); contentPanel.add(buttonPane, BorderLayout.PAGE_END); getContentPane().add(contentPanel); pack(); setSize(1300, 700); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // Add a window size change listener to ensure the divider position adapts to window size changes addComponentListener(new java.awt.event.ComponentAdapter() { @Override public void componentResized(java.awt.event.ComponentEvent e) { // Keep the left-right ratio int width = splitPane.getWidth(); if (width > 0) { int currentDividerLocation = splitPane.getDividerLocation(); double ratio = (double) currentDividerLocation / width; // If the ratio is too small or too large, reset to a reasonable value if (ratio < 0.2 || ratio > 0.5) { splitPane.setDividerLocation((int) (width * 0.3)); // Use pixel values } } } }); } @Override protected void openInit() { prepareUsageData(initialNode); localProgressPanel.setIndeterminate(true); localProgressPanel.setVisible(true); progressInfoLabel.setText(NLS.str("search_dialog.tip_searching")); // Load the usage of the root node loadNodeUsages(initialNode, rootNode); } private void loadNodeUsages(JNode node, DefaultMutableTreeNode treeNode) { // When loading starts, display the searching state localProgressPanel.setIndeterminate(true); localProgressPanel.setVisible(true); progressInfoLabel.setText(NLS.str("search_dialog.tip_searching")); mainWindow.getBackgroundExecutor().execute(NLS.str("progress.load"), () -> collectUsageData(node, treeNode), (status) -> { if (status == TaskStatus.CANCEL_BY_MEMORY) { mainWindow.showHeapUsageBar(); UiUtils.errorMessage(UsageDialogPlus.this, NLS.str("message.memoryLow")); } localProgressPanel.setVisible(false); progressInfoLabel.setText(NLS.str("usage_dialog_plus.search_complete")); // Update the result information - always display the number of child nodes of the currently // selected node updateResultsInfo(treeNode); // Expand the root node if (treeNode == rootNode) { usageTree.expandPath(new TreePath(rootNode.getPath())); } }); } private void updateResultsInfo(DefaultMutableTreeNode node) { if (node != null) { int childCount = node.getChildCount(); resultsInfoLabel.setText(NLS.str("search_dialog.results_complete", childCount)); } } private int getTotalChildCount(DefaultMutableTreeNode node) { int count = node.getChildCount(); for (Enumeration<TreeNode> e = node.children(); e.hasMoreElements();) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) e.nextElement(); count += getTotalChildCount(child); } return count; } private void prepareUsageData(JNode node) { if (mainWindow.getSettings().isReplaceConsts() && node instanceof JField) { FieldNode fld = ((JField) node).getJavaField().getFieldNode(); boolean constField = CollectConstValues.getFieldConstValue(fld) != null; if (constField && !fld.getAccessFlags().isPrivate()) { // run full decompilation to prepare for full code scan mainWindow.requestFullDecompilation(); } } } private void collectUsageData(JNode node, DefaultMutableTreeNode treeNode) { List<CodeNode> usageList = new ArrayList<>(); buildUsageQuery(node).forEach( (searchNode, useNodes) -> useNodes.stream() .map(JavaNode::getTopParentClass) .distinct() .forEach(u -> processUsage(searchNode, u, usageList))); // Sort and add to the tree node Collections.sort(usageList); SwingUtilities.invokeLater(() -> { for (CodeNode codeNode : usageList) { DefaultMutableTreeNode usageTreeNode = new DefaultMutableTreeNode(codeNode); treeModel.insertNodeInto(usageTreeNode, treeNode, treeNode.getChildCount()); } treeModel.nodeStructureChanged(treeNode); }); } private Map<JavaNode, List<? extends JavaNode>> buildUsageQuery(JNode node) { Map<JavaNode, List<? extends JavaNode>> map = new HashMap<>(); if (node instanceof JMethod) { JavaMethod javaMethod = ((JMethod) node).getJavaMethod(); for (JavaMethod mth : getMethodWithOverrides(javaMethod)) { map.put(mth, mth.getUseIn()); } return map; } if (node instanceof JClass) { JavaClass javaCls = ((JClass) node).getCls(); map.put(javaCls, javaCls.getUseIn()); // add constructors usage into class usage for (JavaMethod javaMth : javaCls.getMethods()) { if (javaMth.isConstructor()) { map.put(javaMth, javaMth.getUseIn()); } } return map; } if (node instanceof JField && mainWindow.getSettings().isReplaceConsts()) { FieldNode fld = ((JField) node).getJavaField().getFieldNode(); boolean constField = CollectConstValues.getFieldConstValue(fld) != null; if (constField && !fld.getAccessFlags().isPrivate()) { // search all classes to collect usage of replaced constants map.put(fld.getJavaNode(), mainWindow.getWrapper().getIncludedClasses()); return map; } } JavaNode javaNode = node.getJavaNode(); map.put(javaNode, javaNode.getUseIn()); return map; } private List<JavaMethod> getMethodWithOverrides(JavaMethod javaMethod) { List<JavaMethod> relatedMethods = javaMethod.getOverrideRelatedMethods(); if (!relatedMethods.isEmpty()) { return relatedMethods; } return Collections.singletonList(javaMethod); } private void processUsage(JavaNode searchNode, JavaClass topUseClass, List<CodeNode> usageList) { ICodeInfo codeInfo = topUseClass.getCodeInfo(); List<Integer> usePositions = topUseClass.getUsePlacesFor(codeInfo, searchNode); if (usePositions.isEmpty()) { return; } String code = codeInfo.getCodeStr(); JadxWrapper wrapper = mainWindow.getWrapper(); for (int pos : usePositions) { String line = CodeUtils.getLineForPos(code, pos); if (line.startsWith("import ")) { continue; } JNodeCache nodeCache = getNodeCache(); JavaNode enclosingNode = wrapper.getEnclosingNode(codeInfo, pos); JClass rootJCls = nodeCache.makeFrom(topUseClass); JNode usageJNode = enclosingNode == null ? rootJCls : nodeCache.makeFrom(enclosingNode); // Create CodeNode and add to list CodeNode codeNode = new CodeNode(rootJCls, usageJNode, line.trim(), pos); usageList.add(codeNode); } } private JNode getNodeFromCodeNode(CodeNode codeNode) { if (codeNode != null) { try { // Try to get the actual node referenced by the CodeNode JavaNode javaNode = codeNode.getJavaNode(); JNodeCache nodeCache = getNodeCache(); JNode node = nodeCache.makeFrom(javaNode); // If it cannot be obtained directly, try to get it from jParent if (node == null) { node = codeNode.getJParent(); } // Record the log for debugging if (node != null) { LOG.debug("Converted CodeNode to {} of type {}", node.getName(), node.getClass().getSimpleName()); } else { LOG.debug("Failed to convert CodeNode: {}", codeNode.getName()); } return node; } catch (Exception e) { LOG.error("Error converting CodeNode to JNode", e); } } return null; } private void showPopupMenu(MouseEvent e, JNode node, TreePath path) { if (node == null) { return; } JPopupMenu popup = new JPopupMenu(); // Add the expand/load usage menu item DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) path.getLastPathComponent(); JMenuItem expandItem = new JMenuItem(NLS.str("usage_dialog_plus.expand_usages")); expandItem.addActionListener(evt -> { // Expand the node and load the usage if (treeNode.getChildCount() == 0) { JNode nodeToUse = node; // If it is a CodeNode, first convert it to an actual JNode and then search for its usage if (node.getClass() == CodeNode.class) { nodeToUse = getNodeFromCodeNode((CodeNode) node); } if (nodeToUse != null) { loadNodeUsages(nodeToUse, treeNode); } } usageTree.expandPath(path); }); JMenuItem jumpToItem = new JMenuItem(NLS.str("usage_dialog_plus.jump_to")); jumpToItem.addActionListener(evt -> openItem(node)); JMenuItem copyPathItem = new JMenuItem(NLS.str("usage_dialog_plus.copy_path")); copyPathItem.addActionListener(evt -> copyUsagePath(path)); popup.add(expandItem); popup.addSeparator(); popup.add(jumpToItem); popup.add(copyPathItem); popup.show(e.getComponent(), e.getX(), e.getY()); } private void copyUsagePath(TreePath path) { if (path != null) { StringBuilder pathBuilder = new StringBuilder(); Object[] nodes = path.getPath(); // Actually reverse the node order, from the leaf node (currently selected node) to the root node for (int i = nodes.length - 1; i >= 0; i--) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) nodes[i]; Object userObject = treeNode.getUserObject(); if (i < nodes.length - 1) { pathBuilder.append("\n"); // Add indentation - reverse calculate the indentation level int indentLevel = nodes.length - 1 - i; for (int j = 0; j < indentLevel; j++) { pathBuilder.append(" "); } pathBuilder.append("-> "); } // Add node information if (userObject instanceof JNode) { pathBuilder.append(((JNode) userObject).getJavaNode().getCodeNodeRef().toString()); } else if (userObject instanceof CodeNode) { CodeNode codeNode = (CodeNode) userObject; pathBuilder.append(codeNode.getJavaNode().getCodeNodeRef().toString()); } } // Copy to clipboard UiUtils.copyToClipboard(pathBuilder.toString()); } } @NotNull @Override protected JPanel initButtonsPanel() { progressPane = new ProgressPanel(mainWindow, false); JButton cancelButton = new JButton(NLS.str("search_dialog.cancel")); cancelButton.addActionListener(event -> dispose()); JButton openBtn = new JButton(NLS.str("search_dialog.open")); openBtn.addActionListener(event -> openSelectedItem()); getRootPane().setDefaultButton(openBtn); JCheckBox cbKeepOpen = new JCheckBox(NLS.str("search_dialog.keep_open")); cbKeepOpen.setSelected(mainWindow.getSettings().isKeepCommonDialogOpen()); cbKeepOpen.addActionListener(e -> mainWindow.getSettings().saveKeepCommonDialogOpen(cbKeepOpen.isSelected())); cbKeepOpen.setAlignmentY(Component.CENTER_ALIGNMENT); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.add(cbKeepOpen); buttonPane.add(Box.createRigidArea(new Dimension(15, 0))); buttonPane.add(progressPane); buttonPane.add(Box.createRigidArea(new Dimension(5, 0))); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(openBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(cancelButton); return buttonPane; } @Override protected void openSelectedItem() { // Get the currently selected node JNode node = getSelectedNode(); if (node == null) { return; } openItem(node); } @Override protected void loadFinished() { // The tree loading is already handled } @Override protected void loadStart() { // The tree loading is already handled } @Nullable private JNode getSelectedNode() { try { DefaultMutableTreeNode node = (DefaultMutableTreeNode) usageTree.getLastSelectedPathComponent(); if (node == null) { return null; } Object userObject = node.getUserObject(); if (userObject instanceof JNode) { return (JNode) userObject; } else if (userObject instanceof CodeNode) { CodeNode codeNode = (CodeNode) userObject; return getNodeFromCodeNode(codeNode); } return null; } catch (Exception e) { LOG.error("Failed to get selected node", e); return null; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/CommonSearchDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/CommonSearchDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rtextarea.SearchContext; import org.fife.ui.rtextarea.SearchEngine; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import jadx.api.JavaNode; import jadx.gui.logs.LogOptions; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JResSearchNode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.panel.ProgressPanel; import jadx.gui.ui.tab.TabsController; import jadx.gui.utils.CacheObject; import jadx.gui.utils.JNodeCache; import jadx.gui.utils.JumpPosition; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.NodeLabel; import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; public abstract class CommonSearchDialog extends JFrame { private static final Logger LOG = LoggerFactory.getLogger(CommonSearchDialog.class); private static final long serialVersionUID = 8939332306115370276L; protected final transient TabsController tabsController; protected final transient CacheObject cache; protected final transient MainWindow mainWindow; protected final transient Font codeFont; protected final transient String windowTitle; protected ResultsModel resultsModel; protected ResultsTable resultsTable; protected JLabel resultsInfoLabel; protected JLabel progressInfoLabel; protected JLabel warnLabel; protected ProgressPanel progressPane; private SearchContext highlightContext; public CommonSearchDialog(MainWindow mainWindow, String title) { this.mainWindow = mainWindow; this.tabsController = mainWindow.getTabsController(); this.cache = mainWindow.getCacheObject(); this.codeFont = mainWindow.getSettings().getCodeFont(); this.windowTitle = title; UiUtils.setWindowIcons(this); updateTitle(""); } protected abstract void openInit(); protected abstract void loadFinished(); protected abstract void loadStart(); public void loadWindowPos() { if (!mainWindow.getSettings().loadWindowPos(this)) { setSize(800, 500); } } private void updateTitle(String searchText) { if (searchText == null || searchText.isEmpty() || searchText.trim().isEmpty()) { setTitle(windowTitle); } else { setTitle(windowTitle + ": " + searchText); } } public void updateHighlightContext(String text, boolean caseSensitive, boolean regexp, boolean wholeWord) { updateTitle(text); highlightContext = new SearchContext(text); highlightContext.setMatchCase(caseSensitive); highlightContext.setWholeWord(wholeWord); highlightContext.setRegularExpression(regexp); highlightContext.setMarkAll(true); } public void disableHighlight() { highlightContext = null; } protected void registerInitOnOpen() { addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { SwingUtilities.invokeLater(CommonSearchDialog.this::openInit); } }); } protected void openSelectedItem() { JNode node = getSelectedNode(); if (node == null) { return; } openItem(node); } protected void openItem(JNode node) { if (node instanceof JResSearchNode) { JumpPosition jmpPos = new JumpPosition(((JResSearchNode) node).getResNode(), node.getPos()); tabsController.codeJump(jmpPos); } else { tabsController.codeJump(node); } if (!mainWindow.getSettings().isKeepCommonDialogOpen()) { dispose(); } } @Nullable private JNode getSelectedNode() { try { int selectedId = resultsTable.getSelectedRow(); if (selectedId == -1 || selectedId >= resultsTable.getRowCount()) { return null; } return (JNode) resultsModel.getValueAt(selectedId, 0); } catch (Exception e) { LOG.error("Failed to get results table selected object", e); return null; } } @Override public void dispose() { mainWindow.getSettings().saveWindowPos(this); super.dispose(); } protected void initCommon() { UiUtils.addEscapeShortCutToDispose(this); } protected void copyAllSearchResults() { StringBuilder sb = new StringBuilder(); Set<String> uniqueRefs = new HashSet<>(); for (JNode node : resultsModel.rows) { JavaNode javaNode = node.getJavaNode(); if (javaNode != null) { String codeNodeRef = javaNode.getCodeNodeRef().toString(); if (uniqueRefs.add(codeNodeRef)) { sb.append(codeNodeRef).append("\n"); } } } UiUtils.copyToClipboard(sb.toString()); } @NotNull protected JPanel initButtonsPanel() { progressPane = new ProgressPanel(mainWindow, false); JButton cancelButton = new JButton(NLS.str("search_dialog.cancel")); cancelButton.addActionListener(event -> dispose()); JButton openBtn = new JButton(NLS.str("search_dialog.open")); openBtn.addActionListener(event -> openSelectedItem()); getRootPane().setDefaultButton(openBtn); JButton copyBtn = new JButton(NLS.str("search_dialog.copy")); copyBtn.addActionListener(event -> copyAllSearchResults()); JCheckBox cbKeepOpen = new JCheckBox(NLS.str("search_dialog.keep_open")); cbKeepOpen.setSelected(mainWindow.getSettings().isKeepCommonDialogOpen()); cbKeepOpen.addActionListener(e -> mainWindow.getSettings().saveKeepCommonDialogOpen(cbKeepOpen.isSelected())); cbKeepOpen.setAlignmentY(Component.CENTER_ALIGNMENT); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.add(cbKeepOpen); buttonPane.add(Box.createRigidArea(new Dimension(15, 0))); buttonPane.add(progressPane); buttonPane.add(Box.createRigidArea(new Dimension(5, 0))); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(copyBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(openBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(cancelButton); return buttonPane; } protected JPanel initResultsTable() { ResultsTableCellRenderer renderer = new ResultsTableCellRenderer(); resultsModel = new ResultsModel(); resultsModel.addTableModelListener(e -> updateProgressLabel(false)); resultsTable = new ResultsTable(resultsModel, renderer); resultsTable.setShowHorizontalLines(false); resultsTable.setDragEnabled(false); resultsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); resultsTable.setColumnSelectionAllowed(false); resultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); resultsTable.setAutoscrolls(false); resultsTable.setDefaultRenderer(Object.class, renderer); Enumeration<TableColumn> columns = resultsTable.getColumnModel().getColumns(); while (columns.hasMoreElements()) { TableColumn column = columns.nextElement(); column.setCellRenderer(renderer); } resultsTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { openSelectedItem(); } } }); resultsTable.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { openSelectedItem(); } } }); // override copy action to copy long string of node column resultsTable.getActionMap().put("copy", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { JNode selectedNode = getSelectedNode(); if (selectedNode != null) { UiUtils.copyToClipboard(selectedNode.makeLongString()); } } }); warnLabel = new JLabel(); warnLabel.setForeground(Color.RED); warnLabel.setVisible(false); JScrollPane scroll = new JScrollPane(resultsTable, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_AS_NEEDED); resultsInfoLabel = new JLabel(""); resultsInfoLabel.setFont(mainWindow.getSettings().getUiFont()); progressInfoLabel = new JLabel(""); progressInfoLabel.setFont(mainWindow.getSettings().getUiFont()); progressInfoLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { mainWindow.showLogViewer(LogOptions.allWithLevel(Level.INFO)); } }); JPanel resultsActionsPanel = new JPanel(); resultsActionsPanel.setLayout(new BoxLayout(resultsActionsPanel, BoxLayout.LINE_AXIS)); resultsActionsPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0)); addResultsActions(resultsActionsPanel); JPanel resultsPanel = new JPanel(); resultsPanel.setLayout(new BoxLayout(resultsPanel, BoxLayout.PAGE_AXIS)); resultsPanel.add(warnLabel, BorderLayout.PAGE_START); resultsPanel.add(scroll, BorderLayout.CENTER); resultsPanel.add(resultsActionsPanel, BorderLayout.PAGE_END); return resultsPanel; } protected void addResultsActions(JPanel resultsActionsPanel) { resultsActionsPanel.add(Box.createRigidArea(new Dimension(20, 0))); resultsActionsPanel.add(resultsInfoLabel); resultsActionsPanel.add(Box.createRigidArea(new Dimension(20, 0))); resultsActionsPanel.add(progressInfoLabel); resultsActionsPanel.add(Box.createHorizontalGlue()); } protected void updateProgressLabel(boolean complete) { int count = resultsModel.getRowCount(); String statusText; if (complete) { statusText = NLS.str("search_dialog.results_complete", count); } else { statusText = NLS.str("search_dialog.results_incomplete", count); } resultsInfoLabel.setText(statusText); } protected void showSearchState() { resultsInfoLabel.setText(NLS.str("search_dialog.tip_searching") + "..."); } protected static final class ResultsTable extends JTable { private static final long serialVersionUID = 3901184054736618969L; private final transient ResultsModel model; public ResultsTable(ResultsModel resultsModel, ResultsTableCellRenderer renderer) { super(resultsModel); this.model = resultsModel; setRowHeight(renderer.getMaxRowHeight()); } public void initColumnWidth() { int columnCount = getColumnCount(); int width = getParent().getWidth(); int colWidth = model.isAddDescColumn() ? width / 2 : width; columnModel.getColumn(0).setPreferredWidth(colWidth); for (int col = 1; col < columnCount; col++) { columnModel.getColumn(col).setPreferredWidth(width); } } public void updateTable() { UiUtils.uiThreadGuard(); int rowCount = getRowCount(); if (rowCount == 0) { updateUI(); return; } long start = System.currentTimeMillis(); int width = getParent().getWidth(); TableColumn firstColumn = columnModel.getColumn(0); if (model.isAddDescColumn()) { if (firstColumn.getWidth() > width * 0.8) { // first column too big and hide second column, resize it firstColumn.setPreferredWidth(width / 2); } TableColumn secondColumn = columnModel.getColumn(1); int columnMaxWidth = width * 2; // set big enough size to skip per row check if (secondColumn.getWidth() < columnMaxWidth) { secondColumn.setPreferredWidth(columnMaxWidth); } } else { firstColumn.setPreferredWidth(width); } updateUI(); if (LOG.isDebugEnabled()) { LOG.debug("Update results table in {}ms, count: {}", System.currentTimeMillis() - start, rowCount); } } @Override public Object getValueAt(int row, int column) { return model.getValueAt(row, column); } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { // ResultsTable only has two wide columns, the default increment is way too fast if (orientation == SwingConstants.HORIZONTAL) { return 30; } return super.getScrollableUnitIncrement(visibleRect, orientation, direction); } } protected static final class ResultsModel extends AbstractTableModel { private static final long serialVersionUID = -7821286846923903208L; private static final String[] COLUMN_NAMES = { NLS.str("search_dialog.col_node"), NLS.str("search_dialog.col_code") }; private final transient List<JNode> rows = new ArrayList<>(); private transient boolean addDescColumn; public void addAll(Collection<? extends JNode> nodes) { rows.addAll(nodes); if (!addDescColumn) { for (JNode row : rows) { if (row.hasDescString()) { addDescColumn = true; break; } } } } public void clear() { addDescColumn = false; rows.clear(); } public void sort() { Collections.sort(rows); } public boolean isAddDescColumn() { return addDescColumn; } @Override public int getRowCount() { return rows.size(); } @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int index) { return COLUMN_NAMES[index]; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return rows.get(rowIndex); } } protected final class ResultsTableCellRenderer implements TableCellRenderer { private final NodeLabel label; private final RSyntaxTextArea codeArea; private final NodeLabel emptyLabel; private final Color codeSelectedColor; private final Color codeBackground; public ResultsTableCellRenderer() { codeArea = AbstractCodeArea.getDefaultArea(mainWindow); codeArea.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); codeArea.setRows(1); codeBackground = codeArea.getBackground(); codeSelectedColor = codeArea.getSelectionColor(); label = new NodeLabel(); label.setOpaque(true); label.setFont(codeArea.getFont()); label.setHorizontalAlignment(SwingConstants.LEFT); emptyLabel = new NodeLabel(); emptyLabel.setOpaque(true); } @Override public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row, int column) { if (obj == null || table == null) { return emptyLabel; } Component comp = makeCell((JNode) obj, column); updateSelection(table, comp, column, isSelected); return comp; } private void updateSelection(JTable table, Component comp, int column, boolean isSelected) { if (column == 1) { if (isSelected) { comp.setBackground(codeSelectedColor); } else { comp.setBackground(codeBackground); } } else { if (isSelected) { comp.setBackground(table.getSelectionBackground()); comp.setForeground(table.getSelectionForeground()); } else { comp.setBackground(table.getBackground()); comp.setForeground(table.getForeground()); } } } private Component makeCell(JNode node, int column) { if (column == 0) { label.disableHtml(node.disableHtml()); label.setText(node.makeLongStringHtml()); label.setToolTipText(node.getTooltip()); label.setIcon(node.getIcon()); return label; } if (!node.hasDescString()) { return emptyLabel; } codeArea.setSyntaxEditingStyle(node.getSyntaxName()); String descStr = node.makeDescString(); codeArea.setText(descStr); codeArea.setColumns(descStr.length() + 1); if (highlightContext != null) { SearchEngine.markAll(codeArea, highlightContext); } return codeArea; } public int getMaxRowHeight() { label.setText("Text"); codeArea.setText("Text"); return Math.max(getCompHeight(label), getCompHeight(codeArea)); } private int getCompHeight(Component comp) { return Math.max(comp.getHeight(), comp.getPreferredSize().height); } } void progressStartCommon() { progressPane.setIndeterminate(true); progressPane.setVisible(true); warnLabel.setVisible(false); } void progressFinishedCommon() { progressPane.setVisible(false); } protected JNodeCache getNodeCache() { return mainWindow.getCacheObject().getNodeCache(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/MethodsDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/MethodsDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Dimension; import java.util.List; import java.util.function.Consumer; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.DefaultListSelectionModel; import javax.swing.JButton; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.WindowConstants; import jadx.api.JavaMethod; import jadx.gui.ui.MainWindow; import jadx.gui.ui.cellrenders.MethodsListRenderer; import jadx.gui.utils.NLS; public class MethodsDialog extends CommonDialog { private JList<JavaMethod> methodList; private final Consumer<List<JavaMethod>> listConsumer; public MethodsDialog(MainWindow mainWindow, List<JavaMethod> methods, Consumer<List<JavaMethod>> listConsumer) { super(mainWindow); this.listConsumer = listConsumer; initUI(methods); setVisible(true); } private void initUI(List<JavaMethod> methods) { setTitle(NLS.str("methods_dialog.title")); DefaultListModel<JavaMethod> defaultListModel = new DefaultListModel<>(); defaultListModel.addAll(methods); methodList = new JList<>(); methodList.setModel(defaultListModel); methodList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); methodList.setCellRenderer(new MethodsListRenderer()); methodList.setSelectionModel(new DefaultListSelectionModel() { @Override public void setSelectionInterval(int index0, int index1) { if (super.isSelectedIndex(index0)) { super.removeSelectionInterval(index0, index1); } else { super.addSelectionInterval(index0, index1); } } }); JScrollPane scrollPane = new JScrollPane(methodList); JPanel buttonPane = initButtonsPanel(); JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout(5, 5)); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); contentPanel.add(scrollPane, BorderLayout.CENTER); contentPanel.add(buttonPane, BorderLayout.PAGE_END); getContentPane().add(contentPanel); pack(); setSize(500, 300); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } protected JPanel initButtonsPanel() { JButton cancelButton = new JButton(NLS.str("common_dialog.cancel")); cancelButton.addActionListener(event -> dispose()); JButton okBtn = new JButton(NLS.str("common_dialog.ok")); okBtn.addActionListener(event -> generateForSelected()); getRootPane().setDefaultButton(okBtn); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(okBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(cancelButton); return buttonPane; } private void generateForSelected() { List<JavaMethod> selectedMethods = methodList.getSelectedValuesList(); if (!selectedMethods.isEmpty()) { this.listConsumer.accept(selectedMethods); } dispose(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/GotoAddressDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/GotoAddressDialog.java
package jadx.gui.ui.dialog; import javax.swing.JOptionPane; import org.exbin.bined.swing.section.SectCodeArea; import jadx.gui.utils.HexUtils; import jadx.gui.utils.NLS; public class GotoAddressDialog { public void showSetSelectionDialog(SectCodeArea codeArea) { Object o = JOptionPane.showInputDialog( codeArea, NLS.str("hex_viewer.enter_address"), NLS.str("hex_viewer.goto_address"), JOptionPane.QUESTION_MESSAGE, null, null, Long.toHexString(codeArea.getDataPosition())); if (o != null) { boolean isValidAddress = HexUtils.isValidHexString(toString()); if (!isValidAddress) { return; } codeArea.setActiveCaretPosition(Long.parseLong(o.toString(), 16)); codeArea.validateCaret(); codeArea.revealCursor(); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/CommentDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/CommentDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.data.CommentStyle; import jadx.api.data.ICodeComment; import jadx.api.data.impl.JadxCodeComment; import jadx.api.data.impl.JadxCodeData; import jadx.gui.settings.JadxProject; import jadx.gui.ui.codearea.CodeArea; import jadx.gui.utils.NLS; import jadx.gui.utils.TextStandardActions; public class CommentDialog extends CommonDialog { private static final long serialVersionUID = -1865682124935757528L; private static final Logger LOG = LoggerFactory.getLogger(CommentDialog.class); public static void show(CodeArea codeArea, ICodeComment comment, boolean updateComment) { CommentDialog dialog = new CommentDialog(codeArea, comment, updateComment); dialog.setVisible(true); } private static void updateCommentsData(CodeArea codeArea, Consumer<List<ICodeComment>> updater) { try { JadxProject project = codeArea.getProject(); JadxCodeData codeData = project.getCodeData(); if (codeData == null) { codeData = new JadxCodeData(); } List<ICodeComment> list = new ArrayList<>(codeData.getComments()); updater.accept(list); Collections.sort(list); codeData.setComments(list); project.setCodeData(codeData); codeArea.getMainWindow().getWrapper().reloadCodeData(); } catch (Exception e) { LOG.error("Comment action failed", e); } try { // refresh code codeArea.refreshClass(); } catch (Exception e) { LOG.error("Failed to reload code", e); } } private final transient CodeArea codeArea; private final transient ICodeComment comment; private final transient boolean updateComment; private transient JTextArea commentArea; private transient JComboBox<CommentStyle> styleCombo; public CommentDialog(CodeArea codeArea, ICodeComment comment, boolean updateComment) { super(codeArea.getMainWindow()); this.codeArea = codeArea; this.comment = comment; this.updateComment = updateComment; initUI(); } private void apply() { String newCommentStr = commentArea.getText().trim(); if (newCommentStr.isEmpty()) { if (updateComment) { remove(); } else { cancel(); } return; } CommentStyle style = (CommentStyle) styleCombo.getSelectedItem(); ICodeComment newComment = new JadxCodeComment(comment.getNodeRef(), comment.getCodeRef(), newCommentStr, style); if (updateComment) { updateCommentsData(codeArea, list -> { list.remove(comment); list.add(newComment); }); } else { updateCommentsData(codeArea, list -> list.add(newComment)); } dispose(); } private void remove() { updateCommentsData(codeArea, list -> list.removeIf(c -> c == comment)); dispose(); } private void cancel() { dispose(); } private void initUI() { commentArea = new JTextArea(); TextStandardActions.attach(commentArea); commentArea.setEditable(true); commentArea.setFont(mainWindow.getSettings().getCodeFont()); commentArea.setAlignmentX(Component.LEFT_ALIGNMENT); commentArea.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_ENTER: if (e.isShiftDown() || e.isControlDown()) { commentArea.insert("\n", commentArea.getCaretPosition()); } else { apply(); } break; case KeyEvent.VK_ESCAPE: cancel(); break; } } }); if (updateComment) { commentArea.setText(comment.getComment()); } JScrollPane textAreaScrollPane = new JScrollPane(commentArea); textAreaScrollPane.setAlignmentX(LEFT_ALIGNMENT); styleCombo = new JComboBox<>(CommentStyle.values()); styleCombo.setSelectedItem(comment.getStyle()); JLabel commentLabel = new JLabel(NLS.str("comment_dialog.label"), SwingConstants.LEFT); JLabel styleLabel = new JLabel(NLS.str("comment_dialog.style"), SwingConstants.LEFT); JLabel usageLabel = new JLabel(NLS.str("comment_dialog.usage"), SwingConstants.LEFT); JPanel inputPanel = new JPanel(); inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.PAGE_AXIS)); inputPanel.add(commentLabel); inputPanel.add(Box.createRigidArea(new Dimension(0, 5))); inputPanel.add(textAreaScrollPane); inputPanel.add(Box.createRigidArea(new Dimension(0, 5))); inputPanel.add(usageLabel); JPanel stylePanel = new JPanel(); stylePanel.setLayout(new BoxLayout(stylePanel, BoxLayout.LINE_AXIS)); stylePanel.setAlignmentX(LEFT_ALIGNMENT); stylePanel.add(styleLabel); stylePanel.add(Box.createRigidArea(new Dimension(5, 0))); stylePanel.add(styleCombo); JPanel mainPanel = new JPanel(new BorderLayout(10, 10)); mainPanel.add(inputPanel, BorderLayout.CENTER); mainPanel.add(stylePanel, BorderLayout.PAGE_END); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JPanel buttonPane = initButtonsPanel(); Container contentPane = getContentPane(); contentPane.add(mainPanel, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.PAGE_END); if (updateComment) { setTitle(NLS.str("comment_dialog.title.update")); } else { setTitle(NLS.str("comment_dialog.title.add")); } commonWindowInit(); } protected JPanel initButtonsPanel() { JButton cancelButton = new JButton(NLS.str("common_dialog.cancel")); cancelButton.addActionListener(event -> cancel()); String applyStr = updateComment ? NLS.str("common_dialog.update") : NLS.str("common_dialog.add"); JButton renameBtn = new JButton(applyStr); renameBtn.addActionListener(event -> apply()); getRootPane().setDefaultButton(renameBtn); JButton removeBtn; if (updateComment) { removeBtn = new JButton(NLS.str("common_dialog.remove")); removeBtn.addActionListener(event -> remove()); } else { removeBtn = null; } JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createRigidArea(new Dimension(5, 0))); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(renameBtn); if (removeBtn != null) { buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(removeBtn); } buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(cancelButton); return buttonPane; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/SearchDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/SearchDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SpinnerNumberModel; import javax.swing.WindowConstants; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeListener; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.formdev.flatlaf.FlatClientProperties; import com.formdev.flatlaf.icons.FlatSearchWithHistoryIcon; import io.reactivex.rxjava3.core.BackpressureStrategy; import io.reactivex.rxjava3.core.Emitter; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.schedulers.Schedulers; import jadx.api.JavaClass; import jadx.api.JavaPackage; import jadx.api.resources.ResourceContentType; import jadx.core.dex.nodes.PackageNode; import jadx.core.utils.ListUtils; import jadx.core.utils.StringUtils; import jadx.core.utils.Utils; import jadx.gui.jobs.ITaskInfo; import jadx.gui.jobs.ITaskProgress; import jadx.gui.search.SearchSettings; import jadx.gui.search.SearchTask; import jadx.gui.search.providers.ClassSearchProvider; import jadx.gui.search.providers.CodeSearchProvider; import jadx.gui.search.providers.CommentSearchProvider; import jadx.gui.search.providers.FieldSearchProvider; import jadx.gui.search.providers.MergedSearchProvider; import jadx.gui.search.providers.MethodSearchProvider; import jadx.gui.search.providers.ResourceFilter; import jadx.gui.search.providers.ResourceSearchProvider; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JResource; import jadx.gui.ui.MainWindow; import jadx.gui.utils.CacheObject; import jadx.gui.utils.Icons; import jadx.gui.utils.JumpPosition; import jadx.gui.utils.NLS; import jadx.gui.utils.SimpleListener; import jadx.gui.utils.TextStandardActions; import jadx.gui.utils.UiUtils; import jadx.gui.utils.cache.ValueCache; import jadx.gui.utils.layout.WrapLayout; import jadx.gui.utils.rx.RxUtils; import jadx.gui.utils.ui.DocumentUpdateListener; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.ACTIVE_TAB; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.CLASS; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.CODE; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.COMMENT; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.FIELD; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.IGNORE_CASE; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.METHOD; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.RESOURCE; import static jadx.gui.ui.dialog.SearchDialog.SearchOptions.USE_REGEX; public class SearchDialog extends CommonSearchDialog { private static final Logger LOG = LoggerFactory.getLogger(SearchDialog.class); private static final long serialVersionUID = -5105405456969134105L; public static void search(MainWindow window, SearchPreset preset) { SearchDialog searchDialog = new SearchDialog(window, preset, Collections.emptySet()); show(searchDialog, window); } public static void searchInActiveTab(MainWindow window, SearchPreset preset) { SearchDialog searchDialog = new SearchDialog(window, preset, EnumSet.of(ACTIVE_TAB)); show(searchDialog, window); } public static void searchText(MainWindow window, String text) { SearchDialog searchDialog = new SearchDialog(window, SearchPreset.TEXT, Collections.emptySet()); searchDialog.initSearchText = text; show(searchDialog, window); } public static void searchPackage(MainWindow window, String packageName) { SearchDialog searchDialog = new SearchDialog(window, SearchPreset.TEXT, Collections.emptySet()); searchDialog.initSearchPackage = packageName; show(searchDialog, window); } private static void show(SearchDialog searchDialog, MainWindow mw) { mw.addLoadListener(loaded -> { if (!loaded) { searchDialog.dispose(); return true; } return false; }); searchDialog.setVisible(true); } public enum SearchPreset { TEXT, CLASS, COMMENT } public enum SearchOptions { CLASS, METHOD, FIELD, CODE, RESOURCE, COMMENT, IGNORE_CASE, USE_REGEX, ACTIVE_TAB } private final transient SearchPreset searchPreset; private final transient Set<SearchOptions> options; private final transient SimpleListener<Set<SearchOptions>> optionsListener = new SimpleListener<>(); private transient JTextField searchField; private transient JTextField packageField; private transient JTextField resExtField; private transient JSpinner resSizeLimit; private transient @Nullable SearchTask searchTask; private transient JButton loadAllButton; private transient JButton loadMoreButton; private transient JButton stopBtn; private transient JButton sortBtn; private transient Disposable searchDisposable; private transient SearchEventEmitter searchEmitter; private transient ChangeListener activeTabListener; private transient String initSearchText = null; private transient String initSearchPackage = null; // temporal list for pending results private final List<JNode> pendingResults = new ArrayList<>(); /** * Use single thread to do all background work, so additional synchronization not needed */ private final Executor searchBackgroundExecutor = Executors.newSingleThreadExecutor(); // save values between searches private final ValueCache<String, List<JavaClass>> includedClsCache = new ValueCache<>(); private final ValueCache<List<JavaClass>, List<List<JavaClass>>> batchesCache = new ValueCache<>(); private SearchDialog(MainWindow mainWindow, SearchPreset preset, Set<SearchOptions> additionalOptions) { super(mainWindow, NLS.str("menu.text_search")); this.searchPreset = preset; this.options = buildOptions(preset); this.options.addAll(additionalOptions); loadWindowPos(); initUI(); initSearchEvents(); registerInitOnOpen(); registerActiveTabListener(); } @Override public void dispose() { if (searchDisposable != null && !searchDisposable.isDisposed()) { searchDisposable.dispose(); } resultsModel.clear(); removeActiveTabListener(); searchBackgroundExecutor.execute(() -> { stopSearchTask(); unloadTempData(); }); super.dispose(); } private Set<SearchOptions> buildOptions(SearchPreset preset) { Set<SearchOptions> searchOptions = cache.getLastSearchOptions().get(preset); if (searchOptions == null) { searchOptions = EnumSet.noneOf(SearchOptions.class); } switch (preset) { case TEXT: if (searchOptions.isEmpty()) { searchOptions.add(SearchOptions.CODE); searchOptions.add(IGNORE_CASE); } break; case CLASS: searchOptions.add(CLASS); break; case COMMENT: searchOptions.add(COMMENT); searchOptions.remove(ACTIVE_TAB); break; } return searchOptions; } @Override protected void openInit() { String searchText = initSearchText != null ? initSearchText : cache.getLastSearch(); if (searchText != null) { searchField.setText(searchText); searchField.selectAll(); } String searchPackage = initSearchPackage != null ? initSearchPackage : cache.getLastSearchPackage(); if (searchPackage != null) { packageField.setText(searchPackage); } searchField.requestFocus(); resultsTable.initColumnWidth(); if (options.contains(COMMENT)) { // show all comments on empty input searchEmitter.emitSearch(); } } private void initUI() { searchField = new JTextField(); TextStandardActions.attach(searchField); addSearchHistoryButton(); searchField.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); boolean autoSearch = mainWindow.getSettings().isUseAutoSearch(); JButton searchBtn = new JButton(NLS.str("search_dialog.search_button")); searchBtn.setVisible(!autoSearch); searchBtn.addActionListener(ev -> searchEmitter.emitSearch()); JCheckBox autoSearchCB = new JCheckBox(NLS.str("search_dialog.auto_search")); autoSearchCB.setSelected(autoSearch); autoSearchCB.addActionListener(ev -> { boolean newValue = autoSearchCB.isSelected(); mainWindow.getSettings().saveUseAutoSearch(newValue); searchBtn.setVisible(!newValue); initSearchEvents(); if (newValue) { searchEmitter.emitSearch(); } }); JPanel searchButtons = new JPanel(); searchButtons.setLayout(new BoxLayout(searchButtons, BoxLayout.LINE_AXIS)); searchButtons.add(searchBtn); searchButtons.add(Box.createRigidArea(new Dimension(5, 0))); searchButtons.add(makeOptionsToggleButton(NLS.str("search_dialog.ignorecase"), Icons.ICON_MATCH, Icons.ICON_MATCH_SELECTED, SearchOptions.IGNORE_CASE)); searchButtons.add(Box.createRigidArea(new Dimension(5, 0))); searchButtons.add(makeOptionsToggleButton(NLS.str("search_dialog.regex"), Icons.ICON_REGEX, Icons.ICON_REGEX_SELECTED, SearchOptions.USE_REGEX)); searchButtons.add(Box.createRigidArea(new Dimension(5, 0))); searchButtons.add(makeOptionsToggleButton(NLS.str("search_dialog.active_tab"), Icons.ICON_ACTIVE_TAB, Icons.ICON_ACTIVE_TAB_SELECTED, SearchOptions.ACTIVE_TAB)); searchButtons.add(Box.createRigidArea(new Dimension(5, 0))); searchButtons.add(autoSearchCB); JPanel searchFieldPanel = new JPanel(); searchFieldPanel.setLayout(new BorderLayout(5, 5)); searchFieldPanel.add(new JLabel(NLS.str("search_dialog.open_by_name")), BorderLayout.LINE_START); searchFieldPanel.add(searchField, BorderLayout.CENTER); searchFieldPanel.add(searchButtons, BorderLayout.LINE_END); JPanel searchInPanel = new JPanel(); searchInPanel.setLayout(new BoxLayout(searchInPanel, BoxLayout.LINE_AXIS)); searchInPanel.setBorder(BorderFactory.createTitledBorder(NLS.str("search_dialog.search_in"))); searchInPanel.add(makeOptionsCheckBox(NLS.str("search_dialog.class"), SearchOptions.CLASS)); searchInPanel.add(makeOptionsCheckBox(NLS.str("search_dialog.method"), SearchOptions.METHOD)); searchInPanel.add(makeOptionsCheckBox(NLS.str("search_dialog.field"), SearchOptions.FIELD)); searchInPanel.add(makeOptionsCheckBox(NLS.str("search_dialog.code"), SearchOptions.CODE)); searchInPanel.add(makeOptionsCheckBox(NLS.str("search_dialog.resource"), SearchOptions.RESOURCE)); searchInPanel.add(makeOptionsCheckBox(NLS.str("search_dialog.comments"), SearchOptions.COMMENT)); packageField = new JTextField(Math.min(100, getMaxPkgLen())); TextStandardActions.attach(packageField); packageField.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); packageField.setToolTipText(NLS.str("search_dialog.limit_package")); JPanel searchPackagePanel = new JPanel(new BorderLayout()); searchPackagePanel.setBorder(BorderFactory.createTitledBorder(NLS.str("search_dialog.limit_package"))); searchPackagePanel.add(packageField, BorderLayout.CENTER); Dimension minPanelSize = calcMinSizeForTitledBorder(searchPackagePanel); searchPackagePanel .setPreferredSize(new Dimension(Math.max(packageField.getPreferredSize().width, minPanelSize.width), minPanelSize.height)); resExtField = new JTextField(30); TextStandardActions.attach(resExtField); resExtField.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); resExtField.setToolTipText(NLS.str("preferences.res_file_ext")); String resFilterStr = mainWindow.getProject().getSearchResourcesFilter(); resExtField.setText(resFilterStr); ResourceFilter resFilter = ResourceFilter.parse(resFilterStr); JCheckBox textResBox = new JCheckBox(NLS.str("search_dialog.res_text")); textResBox.setSelected(resFilter.getContentTypes().contains(ResourceContentType.CONTENT_TEXT)); JCheckBox binResBox = new JCheckBox(NLS.str("search_dialog.res_binary")); binResBox.setSelected(resFilter.getContentTypes().contains(ResourceContentType.CONTENT_BINARY)); ItemListener resContentTypeListener = ev -> { try { Set<ResourceContentType> contentTypes = EnumSet.noneOf(ResourceContentType.class); if (textResBox.isSelected()) { contentTypes.add(ResourceContentType.CONTENT_TEXT); } if (binResBox.isSelected()) { contentTypes.add(ResourceContentType.CONTENT_BINARY); } String newStr = ResourceFilter.withContentType(resExtField.getText(), contentTypes); if (!newStr.equals(resExtField.getText())) { resExtField.setText(newStr); } } catch (Exception e) { // ignore } }; textResBox.addItemListener(resContentTypeListener); binResBox.addItemListener(resContentTypeListener); resExtField.getDocument().addDocumentListener(new DocumentUpdateListener(ev -> UiUtils.uiRun(() -> { try { ResourceFilter filter = ResourceFilter.parse(resExtField.getText()); textResBox.setSelected(filter.getContentTypes().contains(ResourceContentType.CONTENT_TEXT)); binResBox.setSelected(filter.getContentTypes().contains(ResourceContentType.CONTENT_BINARY)); } catch (Exception e) { // ignore } }))); JPanel resExtFilePanel = new JPanel(); resExtFilePanel.setLayout(new BoxLayout(resExtFilePanel, BoxLayout.LINE_AXIS)); resExtFilePanel.setBorder(BorderFactory.createTitledBorder(NLS.str("preferences.res_file_ext"))); resExtFilePanel.add(resExtField); resExtFilePanel.add(textResBox); resExtFilePanel.add(binResBox); resExtFilePanel.setPreferredSize(calcMinSizeForTitledBorder(resExtFilePanel)); resSizeLimit = new JSpinner(new SpinnerNumberModel(mainWindow.getProject().getSearchResourcesSizeLimit(), 0, Integer.MAX_VALUE, 1)); resSizeLimit.setToolTipText(NLS.str("preferences.res_skip_file")); JPanel sizeLimitPanel = new JPanel(new BorderLayout()); sizeLimitPanel.setBorder(BorderFactory.createTitledBorder(NLS.str("preferences.res_skip_file"))); sizeLimitPanel.add(resSizeLimit, BorderLayout.CENTER); sizeLimitPanel.setPreferredSize(calcMinSizeForTitledBorder(sizeLimitPanel)); JPanel optionsPanel = new JPanel(new WrapLayout(FlowLayout.LEFT)); optionsPanel.add(searchInPanel); optionsPanel.add(searchPackagePanel); optionsPanel.add(resExtFilePanel); optionsPanel.add(sizeLimitPanel); optionsListener.addListener(searchOptions -> { boolean codeSearch = Utils.isSetContainsAny(searchOptions, EnumSet.of(CODE, CLASS, METHOD, FIELD, COMMENT)); searchPackagePanel.setVisible(codeSearch); boolean resSearch = searchOptions.contains(RESOURCE); resExtFilePanel.setVisible(resSearch); sizeLimitPanel.setVisible(resSearch); optionsPanel.revalidate(); optionsPanel.repaint(); }); JPanel searchPane = new JPanel(); searchPane.setLayout(new BoxLayout(searchPane, BoxLayout.PAGE_AXIS)); searchPane.add(searchFieldPanel); searchPane.add(Box.createRigidArea(new Dimension(0, 5))); searchPane.add(optionsPanel); initCommon(); JPanel resultsPanel = initResultsTable(); JPanel buttonPane = initButtonsPanel(); JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout(5, 5)); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); contentPanel.add(searchPane, BorderLayout.PAGE_START); contentPanel.add(resultsPanel, BorderLayout.CENTER); contentPanel.add(buttonPane, BorderLayout.PAGE_END); getContentPane().add(contentPanel); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { optionsPanel.revalidate(); optionsPanel.repaint(); } }); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } private int getMaxPkgLen() { CacheObject cacheObject = mainWindow.getCacheObject(); int maxPkgLength = cacheObject.getMaxPkgLength(); if (maxPkgLength != 0) { return maxPkgLength; } int max = 1; for (PackageNode pkg : mainWindow.getWrapper().getRootNode().getPackages()) { int len = pkg.getPkgInfo().getFullName().length(); if (len > max) { max = len; } } cacheObject.setMaxPkgLength(max); return max; } /** * Workaround to calculate minimum size for a panel with titled border */ private Dimension calcMinSizeForTitledBorder(JPanel panel) { TitledBorder border = (TitledBorder) panel.getBorder(); Insets borderInsets = border.getBorderInsets(panel); int insets = 2 * (borderInsets.left + borderInsets.right); double titleWidth = panel.getFontMetrics(border.getTitleFont()).stringWidth(border.getTitle()); return new Dimension((int) titleWidth + insets, panel.getPreferredSize().height); } private void addSearchHistoryButton() { JButton searchHistoryButton = new JButton(new FlatSearchWithHistoryIcon(true)); searchHistoryButton.setToolTipText(NLS.str("search_dialog.search_history")); searchHistoryButton.addActionListener(e -> { JPopupMenu popupMenu = new JPopupMenu(); List<String> searchHistory = mainWindow.getProject().getSearchHistory(); if (searchHistory.isEmpty()) { popupMenu.add("(empty)"); } else { for (String str : searchHistory) { JMenuItem item = popupMenu.add(str); item.addActionListener(ev -> searchField.setText(str)); } } popupMenu.show(searchHistoryButton, 0, searchHistoryButton.getHeight()); }); searchField.putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_COMPONENT, searchHistoryButton); } protected void addResultsActions(JPanel resultsActionsPanel) { loadAllButton = new JButton(NLS.str("search_dialog.load_all")); loadAllButton.addActionListener(e -> loadMoreResults(true)); loadAllButton.setEnabled(false); loadMoreButton = new JButton(NLS.str("search_dialog.load_more")); loadMoreButton.addActionListener(e -> loadMoreResults(false)); loadMoreButton.setEnabled(false); stopBtn = new JButton(NLS.str("search_dialog.stop")); stopBtn.addActionListener(e -> pauseSearch()); stopBtn.setEnabled(false); sortBtn = new JButton(NLS.str("search_dialog.sort_results")); sortBtn.addActionListener(e -> { synchronized (pendingResults) { resultsModel.sort(); resultsTable.updateTable(); } }); sortBtn.setEnabled(false); resultsActionsPanel.add(loadAllButton); resultsActionsPanel.add(Box.createRigidArea(new Dimension(10, 0))); resultsActionsPanel.add(loadMoreButton); resultsActionsPanel.add(Box.createRigidArea(new Dimension(10, 0))); resultsActionsPanel.add(stopBtn); resultsActionsPanel.add(Box.createRigidArea(new Dimension(10, 0))); resultsActionsPanel.add(stopBtn); super.addResultsActions(resultsActionsPanel); resultsActionsPanel.add(Box.createRigidArea(new Dimension(10, 0))); resultsActionsPanel.add(sortBtn); } private class SearchEventEmitter { private final Flowable<String> flowable; private Emitter<String> emitter; public SearchEventEmitter() { flowable = Flowable.create(this::saveEmitter, BackpressureStrategy.LATEST); } public Flowable<String> getFlowable() { return flowable; } private void saveEmitter(Emitter<String> emitter) { this.emitter = emitter; } public synchronized void emitSearch() { this.emitter.onNext(searchField.getText()); } } private void initSearchEvents() { if (searchDisposable != null) { searchDisposable.dispose(); searchDisposable = null; } searchEmitter = new SearchEventEmitter(); Flowable<String> searchEvents; if (mainWindow.getSettings().isUseAutoSearch()) { searchEvents = Flowable.merge(List.of( RxUtils.textFieldChanges(searchField), RxUtils.textFieldEnterPress(searchField), RxUtils.textFieldChanges(packageField), RxUtils.textFieldEnterPress(packageField), RxUtils.textFieldChanges(resExtField), RxUtils.textFieldEnterPress(resExtField), RxUtils.spinnerChanges(resSizeLimit), RxUtils.spinnerEnterPress(resSizeLimit), searchEmitter.getFlowable())); } else { searchEvents = Flowable.merge(List.of( RxUtils.textFieldEnterPress(searchField), RxUtils.textFieldEnterPress(packageField), RxUtils.textFieldEnterPress(resExtField), RxUtils.spinnerEnterPress(resSizeLimit), searchEmitter.getFlowable())); } searchDisposable = searchEvents .debounce(100, TimeUnit.MILLISECONDS) .observeOn(Schedulers.from(searchBackgroundExecutor)) .subscribe(t -> this.search(searchField.getText())); // set initial values optionsListener.sendUpdate(options); } private void search(String text) { UiUtils.notUiThreadGuard(); stopSearchTask(); UiUtils.uiRun(this::resetSearch); searchTask = prepareSearch(text); if (searchTask == null) { return; } UiUtils.uiRunAndWait(() -> { updateTableHighlight(); prepareForSearch(); }); this.searchTask.setResultsLimit(mainWindow.getSettings().getSearchResultsPerPage()); this.searchTask.setProgressListener(this::updateProgress); this.searchTask.fetchResults(); LOG.debug("Total search items count estimation: {}", this.searchTask.getTaskProgress().total()); } private SearchTask prepareSearch(String text) { if (text == null || options.isEmpty()) { return null; } // allow empty text for search in comments if (text.isEmpty() && !options.contains(COMMENT)) { return null; } LOG.debug("Building search for '{}', options: {}", text, options); SearchSettings searchSettings = new SearchSettings(text); searchSettings.setIgnoreCase(options.contains(IGNORE_CASE)); searchSettings.setUseRegex(options.contains(USE_REGEX)); searchSettings.setSearchPkgStr(packageField.getText().trim()); searchSettings.setResFilterStr(resExtField.getText().trim()); searchSettings.setResSizeLimit((Integer) resSizeLimit.getValue()); String error = searchSettings.prepare(mainWindow); UiUtils.highlightAsErrorField(searchField, !StringUtils.isEmpty(error)); if (!StringUtils.isEmpty(error)) { resultsInfoLabel.setText(error); return null; } SearchTask newSearchTask = new SearchTask(mainWindow, this::addSearchResult, this::searchFinished); if (!buildSearch(newSearchTask, text, searchSettings)) { UiUtils.highlightAsErrorField(searchField, true); return null; } // save search settings mainWindow.getProject().setSearchResourcesFilter(resExtField.getText().trim()); mainWindow.getProject().setSearchResourcesSizeLimit(searchSettings.getResSizeLimit()); return newSearchTask; } private boolean buildSearch(SearchTask newSearchTask, String text, SearchSettings searchSettings) { List<JavaClass> searchClasses; if (options.contains(ACTIVE_TAB)) { JumpPosition currentPos = mainWindow.getTabbedPane().getCurrentPosition(); if (currentPos == null) { resultsInfoLabel.setText("Can't search in current tab"); return false; } JNode currentNode = currentPos.getNode(); if (currentNode instanceof JClass) { JClass activeCls = currentNode.getRootClass(); searchSettings.setActiveCls(activeCls); searchClasses = Collections.singletonList(activeCls.getCls()); } else if (currentNode instanceof JResource) { searchSettings.setActiveResource((JResource) currentNode); searchClasses = Collections.emptyList(); } else { resultsInfoLabel.setText("Can't search in current tab"); return false; } } else { searchClasses = includedClsCache.get(mainWindow.getSettings().getExcludedPackages(), exc -> mainWindow.getWrapper().getIncludedClassesWithInners()); } JavaPackage searchPkg = searchSettings.getSearchPackage(); if (searchPkg != null) { searchClasses = searchClasses.stream() .filter(searchSettings::isInSearchPkg) .collect(Collectors.toList()); } if (text.isEmpty() && options.contains(COMMENT)) { // allow empty text for comment search newSearchTask.addProviderJob(new CommentSearchProvider(mainWindow, searchSettings, searchClasses)); return true; } if (!searchClasses.isEmpty()) { // using ordered execution for fast tasks MergedSearchProvider merged = new MergedSearchProvider(); if (options.contains(CLASS)) { merged.add(new ClassSearchProvider(mainWindow, searchSettings, searchClasses)); } if (options.contains(METHOD)) { merged.add(new MethodSearchProvider(mainWindow, searchSettings, searchClasses)); } if (options.contains(FIELD)) { merged.add(new FieldSearchProvider(mainWindow, searchSettings, searchClasses)); } if (!merged.isEmpty()) { merged.prepare(); newSearchTask.addProviderJob(merged); } if (options.contains(CODE)) { int clsCount = searchClasses.size(); if (clsCount == 1) { newSearchTask.addProviderJob(new CodeSearchProvider(mainWindow, searchSettings, searchClasses, null)); } else if (clsCount > 1) { List<JavaClass> topClasses = ListUtils.filter(searchClasses, c -> !c.isInner()); List<List<JavaClass>> batches = batchesCache.get(topClasses, clsList -> mainWindow.getWrapper().buildDecompileBatches(clsList)); Set<JavaClass> includedClasses = new HashSet<>(topClasses); for (List<JavaClass> batch : batches) { newSearchTask.addProviderJob(new CodeSearchProvider(mainWindow, searchSettings, batch, includedClasses)); } } } if (options.contains(COMMENT)) { newSearchTask.addProviderJob(new CommentSearchProvider(mainWindow, searchSettings, searchClasses)); } } if (options.contains(RESOURCE)) { newSearchTask.addProviderJob(new ResourceSearchProvider(mainWindow, searchSettings, this)); } return true; } @Override protected void openItem(JNode node) { if (mainWindow.getSettings().isUseAutoSearch()) { // for auto search save only searches which leads to node opening mainWindow.getProject().addToSearchHistory(searchField.getText()); } super.openItem(node); } private void pauseSearch() { stopBtn.setEnabled(false); searchBackgroundExecutor.execute(() -> { if (searchTask != null) { searchTask.cancel(); } }); } private void stopSearchTask() { UiUtils.notUiThreadGuard(); if (searchTask != null) { searchTask.cancel(); searchTask.waitTask(); searchTask = null; } } private void loadMoreResults(boolean all) { searchBackgroundExecutor.execute(() -> { if (searchTask == null) { return; } searchTask.cancel(); searchTask.waitTask(); UiUtils.uiRunAndWait(this::prepareForSearch); if (all) { searchTask.setResultsLimit(0); } searchTask.fetchResults(); }); } private void resetSearch() { UiUtils.uiThreadGuard(); resultsModel.clear(); resultsTable.updateTable(); synchronized (pendingResults) { pendingResults.clear(); } updateProgressLabel(""); progressPane.setVisible(false); warnLabel.setVisible(false); loadAllButton.setEnabled(false); loadMoreButton.setEnabled(false); } private void prepareForSearch() { UiUtils.uiThreadGuard(); stopBtn.setEnabled(true); sortBtn.setEnabled(false); showSearchState(); progressStartCommon(); } private void addSearchResult(JNode node) { Objects.requireNonNull(node); synchronized (pendingResults) { UiUtils.notUiThreadGuard(); pendingResults.add(node); } } private void updateTable() { synchronized (pendingResults) { UiUtils.uiThreadGuard(); Collections.sort(pendingResults); resultsModel.addAll(pendingResults); pendingResults.clear(); resultsTable.updateTable(); } } private void updateTableHighlight() { String text = searchField.getText(); updateHighlightContext(text, !options.contains(IGNORE_CASE), options.contains(USE_REGEX), false); cache.setLastSearch(text); cache.setLastSearchPackage(packageField.getText()); cache.getLastSearchOptions().put(searchPreset, options); if (!mainWindow.getSettings().isUseAutoSearch()) { mainWindow.getProject().addToSearchHistory(text); } } private void updateProgress(ITaskProgress progress) { UiUtils.uiRun(() -> { progressPane.setProgress(progress); updateTable(); }); } public void updateProgressLabel(String text) { UiUtils.uiRun(() -> progressInfoLabel.setText(text)); } private void searchFinished(ITaskInfo status, Boolean complete) { UiUtils.uiThreadGuard(); LOG.debug("Search complete: {}, complete: {}", status, complete); loadAllButton.setEnabled(!complete); loadMoreButton.setEnabled(!complete); stopBtn.setEnabled(false); progressFinishedCommon(); updateTable(); updateProgressLabel(complete); sortBtn.setEnabled(resultsModel.getRowCount() != 0); } private void unloadTempData() { mainWindow.getWrapper().unloadClasses(); System.gc(); } private JCheckBox makeOptionsCheckBox(String name, final SearchOptions opt) { final JCheckBox chBox = new JCheckBox(name); chBox.setSelected(options.contains(opt)); chBox.addItemListener(e -> { if (chBox.isSelected()) { options.add(opt); } else { options.remove(opt); } optionsListener.sendUpdate(options); searchEmitter.emitSearch(); }); return chBox; } private JToggleButton makeOptionsToggleButton(String name, ImageIcon icon, ImageIcon selectedIcon, final SearchOptions opt) { final JToggleButton toggleButton = new JToggleButton(); toggleButton.setToolTipText(name); toggleButton.setIcon(icon); toggleButton.setSelectedIcon(selectedIcon); toggleButton.setSelected(options.contains(opt)); toggleButton.addItemListener(e -> { if (toggleButton.isSelected()) { options.add(opt); } else { options.remove(opt); } optionsListener.sendUpdate(options); searchEmitter.emitSearch(); }); return toggleButton; } @Override protected void loadFinished() { resultsTable.setEnabled(true); searchField.setEnabled(true); searchEmitter.emitSearch(); } @Override protected void loadStart() { resultsTable.setEnabled(false); searchField.setEnabled(false); } private void registerActiveTabListener() { removeActiveTabListener(); activeTabListener = e -> { if (options.contains(ACTIVE_TAB)) { LOG.debug("active tab change event received"); searchEmitter.emitSearch(); } }; mainWindow.getTabbedPane().addChangeListener(activeTabListener); } private void removeActiveTabListener() { if (activeTabListener != null) { mainWindow.getTabbedPane().removeChangeListener(activeTabListener); activeTabListener = null; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/SetValueDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/SetValueDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Map.Entry; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.WindowConstants; import jadx.core.dex.instructions.args.ArgType; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.ui.MainWindow; import jadx.gui.ui.panel.JDebuggerPanel.ValueTreeNode; import jadx.gui.utils.NLS; import jadx.gui.utils.TextStandardActions; import jadx.gui.utils.UiUtils; public class SetValueDialog extends JDialog { private static final long serialVersionUID = -1111111202103121002L; private final transient MainWindow mainWindow; private final transient ValueTreeNode valNode; public SetValueDialog(MainWindow mainWindow, ValueTreeNode valNode) { super(mainWindow); this.mainWindow = mainWindow; this.valNode = valNode; initUI(); UiUtils.addEscapeShortCutToDispose(this); setTitle(valNode.toString()); } private void initUI() { JTextField valField = new JTextField(); TextStandardActions.attach(valField); JPanel valPane = new JPanel(new BorderLayout(5, 5)); valPane.add(new JLabel(NLS.str("set_value_dialog.label_value")), BorderLayout.WEST); valPane.add(valField, BorderLayout.CENTER); JPanel btnPane = new JPanel(); btnPane.setLayout(new BoxLayout(btnPane, BoxLayout.LINE_AXIS)); JButton setValueBtn = new JButton(NLS.str("set_value_dialog.btn_set")); btnPane.add(new Label()); btnPane.add(setValueBtn); UiUtils.addKeyBinding(valField, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "set value", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { setValueBtn.doClick(); } }); JPanel typePane = new JPanel(); typePane.setLayout(new BoxLayout(typePane, BoxLayout.LINE_AXIS)); java.util.List<JRadioButton> rbs = new ArrayList<>(6); rbs.add(new JRadioButton("int")); rbs.add(new JRadioButton("String")); rbs.add(new JRadioButton("long")); rbs.add(new JRadioButton("float")); rbs.add(new JRadioButton("double")); rbs.add(new JRadioButton("Object id")); rbs.get(0).setSelected(true); // select int radio ButtonGroup rbGroup = new ButtonGroup(); rbs.forEach(rbGroup::add); rbs.forEach(typePane::add); JPanel mainPane = new JPanel(new BorderLayout(5, 5)); mainPane.add(typePane, BorderLayout.NORTH); mainPane.add(valPane, BorderLayout.CENTER); mainPane.add(btnPane, BorderLayout.SOUTH); mainPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); getContentPane().add(mainPane); this.setTitle(NLS.str("set_value_dialog.title")); pack(); setSize(480, 160); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setModalityType(ModalityType.MODELESS); UiUtils.addEscapeShortCutToDispose(this); setValueBtn.addActionListener(new AbstractAction() { private static final long serialVersionUID = -1111111202103260220L; @Override public void actionPerformed(ActionEvent e) { boolean ok; try { Entry<ArgType, Object> type = getType(); if (type != null) { ok = mainWindow .getDebuggerPanel() .getDbgController() .modifyRegValue(valNode, type.getKey(), type.getValue()); } else { UiUtils.showMessageBox(mainWindow, NLS.str("set_value_dialog.sel_type")); return; } } catch (JadxRuntimeException except) { UiUtils.showMessageBox(mainWindow, except.getMessage()); return; } if (ok) { dispose(); } else { UiUtils.showMessageBox(mainWindow, NLS.str("set_value_dialog.neg_msg")); } } private Entry<ArgType, Object> getType() { String val = valField.getText(); for (JRadioButton rb : rbs) { if (rb.isSelected()) { switch (rb.getText()) { case "int": return new SimpleEntry<>(ArgType.INT, Integer.valueOf(val)); case "String": return new SimpleEntry<>(ArgType.STRING, val); case "long": return new SimpleEntry<>(ArgType.LONG, Long.valueOf(val)); case "float": return new SimpleEntry<>(ArgType.FLOAT, Float.valueOf(val)); case "double": return new SimpleEntry<>(ArgType.DOUBLE, Double.valueOf(val)); case "Object id": return new SimpleEntry<>(ArgType.OBJECT, Long.valueOf(val)); default: throw new JadxRuntimeException("Unexpected type: " + rb.getText()); } } } return null; } }); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/UsageDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/UsageDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; import jadx.api.ICodeInfo; import jadx.api.JavaClass; import jadx.api.JavaMethod; import jadx.api.JavaNode; import jadx.api.utils.CodeUtils; import jadx.core.dex.nodes.FieldNode; import jadx.core.dex.visitors.prepare.CollectConstValues; import jadx.gui.JadxWrapper; import jadx.gui.jobs.TaskStatus; import jadx.gui.settings.JadxSettings; import jadx.gui.treemodel.CodeNode; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JField; import jadx.gui.treemodel.JMethod; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.utils.JNodeCache; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.NodeLabel; public class UsageDialog extends CommonSearchDialog { private static final long serialVersionUID = -5105405789969134105L; private final transient JNode node; private transient List<CodeNode> usageList; public static void open(MainWindow mainWindow, JNode node) { UsageDialog usageDialog = new UsageDialog(mainWindow, node); mainWindow.addLoadListener(loaded -> { if (!loaded) { usageDialog.dispose(); return true; } return false; }); usageDialog.setVisible(true); } private UsageDialog(MainWindow mainWindow, JNode node) { super(mainWindow, NLS.str("usage_dialog.title")); this.node = node; initUI(); registerInitOnOpen(); loadWindowPos(); } @Override protected void openInit() { progressStartCommon(); prepareUsageData(); mainWindow.getBackgroundExecutor().execute(NLS.str("progress.load"), this::collectUsageData, (status) -> { if (status == TaskStatus.CANCEL_BY_MEMORY) { mainWindow.showHeapUsageBar(); UiUtils.errorMessage(this, NLS.str("message.memoryLow")); } progressFinishedCommon(); loadFinished(); }); } private void prepareUsageData() { if (mainWindow.getSettings().isReplaceConsts() && node instanceof JField) { FieldNode fld = ((JField) node).getJavaField().getFieldNode(); boolean constField = CollectConstValues.getFieldConstValue(fld) != null; if (constField && !fld.getAccessFlags().isPrivate()) { // run full decompilation to prepare for full code scan mainWindow.requestFullDecompilation(); } } } private void collectUsageData() { usageList = new ArrayList<>(); buildUsageQuery().forEach( (searchNode, useNodes) -> useNodes.stream() .map(JavaNode::getTopParentClass) .distinct() .forEach(u -> processUsage(searchNode, u))); } /** * Return mapping of 'node to search' to 'use places' */ private Map<JavaNode, List<? extends JavaNode>> buildUsageQuery() { Map<JavaNode, List<? extends JavaNode>> map = new HashMap<>(); if (node instanceof JMethod) { JavaMethod javaMethod = ((JMethod) node).getJavaMethod(); for (JavaMethod mth : getMethodWithOverrides(javaMethod)) { map.put(mth, mth.getUseIn()); } return map; } if (node instanceof JClass) { JavaClass javaCls = ((JClass) node).getCls(); map.put(javaCls, javaCls.getUseIn()); // add constructors usage into class usage for (JavaMethod javaMth : javaCls.getMethods()) { if (javaMth.isConstructor()) { map.put(javaMth, javaMth.getUseIn()); } } return map; } if (node instanceof JField && mainWindow.getSettings().isReplaceConsts()) { FieldNode fld = ((JField) node).getJavaField().getFieldNode(); boolean constField = CollectConstValues.getFieldConstValue(fld) != null; if (constField && !fld.getAccessFlags().isPrivate()) { // search all classes to collect usage of replaced constants map.put(fld.getJavaNode(), mainWindow.getWrapper().getIncludedClasses()); return map; } } JavaNode javaNode = node.getJavaNode(); map.put(javaNode, javaNode.getUseIn()); return map; } private List<JavaMethod> getMethodWithOverrides(JavaMethod javaMethod) { List<JavaMethod> relatedMethods = javaMethod.getOverrideRelatedMethods(); if (!relatedMethods.isEmpty()) { return relatedMethods; } return Collections.singletonList(javaMethod); } private void processUsage(JavaNode searchNode, JavaClass topUseClass) { ICodeInfo codeInfo = topUseClass.getCodeInfo(); List<Integer> usePositions = topUseClass.getUsePlacesFor(codeInfo, searchNode); if (usePositions.isEmpty()) { return; } String code = codeInfo.getCodeStr(); JadxWrapper wrapper = mainWindow.getWrapper(); for (int pos : usePositions) { String line = CodeUtils.getLineForPos(code, pos); if (line.startsWith("import ")) { continue; } JNodeCache nodeCache = getNodeCache(); JavaNode enclosingNode = wrapper.getEnclosingNode(codeInfo, pos); JClass rootJCls = nodeCache.makeFrom(topUseClass); JNode usageJNode = enclosingNode == null ? rootJCls : nodeCache.makeFrom(enclosingNode); usageList.add(new CodeNode(rootJCls, usageJNode, line.trim(), pos)); } } @Override protected void loadFinished() { resultsTable.setEnabled(true); resultsModel.clear(); Collections.sort(usageList); resultsModel.addAll(usageList); updateHighlightContext(node.getName(), true, false, true); resultsTable.initColumnWidth(); resultsTable.updateTable(); updateProgressLabel(true); } @Override protected void loadStart() { resultsTable.setEnabled(false); } private void initUI() { JadxSettings settings = mainWindow.getSettings(); Font codeFont = settings.getCodeFont(); JLabel lbl = new JLabel(NLS.str("usage_dialog.label")); lbl.setFont(codeFont); JLabel nodeLabel = NodeLabel.longName(node); nodeLabel.setFont(codeFont); lbl.setLabelFor(nodeLabel); JPanel searchPane = new JPanel(); searchPane.setLayout(new FlowLayout(FlowLayout.LEFT)); searchPane.add(lbl); searchPane.add(nodeLabel); searchPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); initCommon(); JPanel resultsPanel = initResultsTable(); JPanel buttonPane = initButtonsPanel(); JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout(5, 5)); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); contentPanel.add(searchPane, BorderLayout.PAGE_START); contentPanel.add(resultsPanel, BorderLayout.CENTER); contentPanel.add(buttonPane, BorderLayout.PAGE_END); getContentPane().add(contentPanel); pack(); setSize(800, 500); setLocationRelativeTo(null); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/RenameDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/RenameDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.jetbrains.annotations.NotNull; import jadx.api.metadata.ICodeNodeRef; import jadx.api.plugins.events.types.NodeRenamedByUser; import jadx.core.utils.Utils; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JPackage; import jadx.gui.treemodel.JRenameNode; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; import jadx.gui.utils.TextStandardActions; import jadx.gui.utils.pkgs.JRenamePackage; import jadx.gui.utils.ui.DocumentUpdateListener; import jadx.gui.utils.ui.NodeLabel; public class RenameDialog extends CommonDialog { private static final long serialVersionUID = -3269715644416902410L; private final transient JRenameNode node; private transient JTextField renameField; private transient JButton renameBtn; public static boolean rename(MainWindow mainWindow, JRenameNode node) { SwingUtilities.invokeLater(() -> { RenameDialog renameDialog = new RenameDialog(mainWindow, node); renameDialog.initRenameField(); renameDialog.setVisible(true); }); return true; } public static JPopupMenu buildRenamePopup(MainWindow mainWindow, JRenameNode node) { JPopupMenu menu = new JPopupMenu(); menu.add(buildRenamePopupMenuItem(mainWindow, node)); return menu; } public static JMenuItem buildRenamePopupMenuItem(MainWindow mainWindow, JRenameNode node) { JMenuItem jmi = new JMenuItem(NLS.str("popup.rename")); jmi.addActionListener(action -> RenameDialog.rename(mainWindow, node)); jmi.setEnabled(node.canRename()); return jmi; } private RenameDialog(MainWindow mainWindow, JRenameNode node) { super(mainWindow); this.node = node.replace(); initUI(); } private void initRenameField() { renameField.setText(node.getName()); renameField.selectAll(); } private boolean checkNewName(String newName) { if (newName.isEmpty()) { // use empty name to reset rename (revert to original) return true; } boolean valid = node.isValidName(newName); if (renameBtn.isEnabled() != valid) { renameBtn.setEnabled(valid); renameField.putClientProperty("JComponent.outline", valid ? "" : "error"); } return valid; } private void rename() { rename(renameField.getText().trim()); } private void resetName() { rename(""); } private void rename(String newName) { if (!checkNewName(newName)) { return; } String oldName = node.getName(); String newNodeName; boolean reset = newName.isEmpty(); if (reset) { node.removeAlias(); newNodeName = Utils.getOrElse(node.getJavaNode().getName(), ""); } else { newNodeName = newName; } sendRenameEvent(oldName, newNodeName, reset); dispose(); } private void sendRenameEvent(String oldName, String newName, boolean reset) { ICodeNodeRef nodeRef = node.getJavaNode().getCodeNodeRef(); NodeRenamedByUser event = new NodeRenamedByUser(nodeRef, oldName, newName); event.setRenameNode(node); event.setResetName(reset); mainWindow.events().send(event); } @NotNull protected JPanel initButtonsPanel() { JButton resetButton = new JButton(NLS.str("common_dialog.reset")); resetButton.addActionListener(event -> resetName()); JButton cancelButton = new JButton(NLS.str("common_dialog.cancel")); cancelButton.addActionListener(event -> dispose()); renameBtn = new JButton(NLS.str("common_dialog.ok")); renameBtn.addActionListener(event -> rename()); getRootPane().setDefaultButton(renameBtn); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(resetButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(renameBtn); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(cancelButton); return buttonPane; } private void initUI() { JLabel lbl = new JLabel(NLS.str("popup.rename")); NodeLabel nodeLabel = new NodeLabel(node.getTitle()); nodeLabel.setIcon(node.getIcon()); if (node instanceof JNode) { nodeLabel.disableHtml(((JNode) node).disableHtml()); } else if (node instanceof JRenamePackage) { // TODO: get from JRenameNode directly nodeLabel.disableHtml(!node.getTitle().equals(JPackage.PACKAGE_DEFAULT_HTML_STR)); } lbl.setLabelFor(nodeLabel); renameField = new JTextField(40); renameField.setFont(mainWindow.getSettings().getCodeFont()); renameField.getDocument().addDocumentListener(new DocumentUpdateListener(ev -> checkNewName(renameField.getText()))); renameField.addActionListener(e -> rename()); new TextStandardActions(renameField); JPanel renamePane = new JPanel(); renamePane.setLayout(new FlowLayout(FlowLayout.LEFT)); renamePane.add(lbl); renamePane.add(nodeLabel); renamePane.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10)); JPanel textPane = new JPanel(); textPane.setLayout(new BoxLayout(textPane, BoxLayout.PAGE_AXIS)); textPane.add(renameField); if (node instanceof JClass) { textPane.add(new JLabel(NLS.str("rename_dialog.class_help"))); } textPane.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10)); JPanel buttonPane = initButtonsPanel(); Container contentPane = getContentPane(); contentPane.add(renamePane, BorderLayout.PAGE_START); contentPane.add(textPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.PAGE_END); setTitle(NLS.str("popup.rename")); commonWindowInit(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/CommonDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/CommonDialog.java
package jadx.gui.ui.dialog; import java.awt.Dimension; import javax.swing.JDialog; import javax.swing.WindowConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.ui.MainWindow; import jadx.gui.utils.UiUtils; public abstract class CommonDialog extends JDialog { private static final Logger LOG = LoggerFactory.getLogger(CommonDialog.class); protected final MainWindow mainWindow; public CommonDialog(MainWindow mainWindow) { super(mainWindow); this.mainWindow = mainWindow; } protected void commonWindowInit() { setModalityType(ModalityType.APPLICATION_MODAL); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); UiUtils.addEscapeShortCutToDispose(this); setLocationRelativeTo(null); UiUtils.uiRunAndWait(this::pack); Dimension minSize = getSize(); setMinimumSize(minSize); if (!mainWindow.getSettings().loadWindowPos(this)) { setSize(incByPercent(minSize.getWidth(), 30), incByPercent(minSize.getHeight(), 30)); } } @Override public void dispose() { try { mainWindow.getSettings().saveWindowPos(this); } catch (Exception e) { LOG.warn("Failed to save window size and position", e); } super.dispose(); } private static int incByPercent(double value, int percent) { return (int) (value * (1 + percent * 0.01)); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/CharsetDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/CharsetDialog.java
package jadx.gui.ui.dialog; import java.awt.Component; import java.nio.charset.Charset; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.swing.JOptionPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.utils.NLS; public class CharsetDialog { private static final Logger LOG = LoggerFactory.getLogger(CharsetDialog.class); private static final Comparator<Charset> CHARSET_COMPARATOR = Comparator.comparing( Charset::displayName, String::compareToIgnoreCase); public static String chooseCharset(Component parent, String currentCharsetName) { Collection<Charset> availableCharsets = Charset.availableCharsets().values(); List<Charset> sortedCharsets = availableCharsets.stream() .sorted(CHARSET_COMPARATOR) .collect(Collectors.toList()); Charset initialSelection = null; try { if (currentCharsetName != null && Charset.isSupported(currentCharsetName)) { initialSelection = Charset.forName(currentCharsetName); if (!sortedCharsets.contains(initialSelection)) { initialSelection = null; } } } catch (Exception e) { LOG.warn("Failed to find initial charset '{}'", currentCharsetName, e); } if (initialSelection == null && !sortedCharsets.isEmpty()) { initialSelection = sortedCharsets.get(0); } Charset[] charsetArray = sortedCharsets.toArray(new Charset[0]); Object selectedValue = JOptionPane.showInputDialog( parent, NLS.str("encoding_dialog.message"), NLS.str("encoding_dialog.title"), JOptionPane.INFORMATION_MESSAGE, null, charsetArray, initialSelection); if (selectedValue instanceof Charset) { return ((Charset) selectedValue).name(); } else { return null; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/AboutDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/AboutDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import jadx.api.JadxDecompiler; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class AboutDialog extends JDialog { private static final long serialVersionUID = 5763493590584039096L; public AboutDialog() { initUI(); } public final void initUI() { URL logoURL = getClass().getResource("/logos/jadx-logo-48px.png"); Icon logo = new ImageIcon(logoURL, "JADX logo"); JLabel name = new JLabel("JADX", logo, SwingConstants.CENTER); name.setAlignmentX(0.5f); JLabel desc = new JLabel("Dex to Java decompiler"); desc.setAlignmentX(0.5f); JLabel version = new JLabel("JADX version: " + JadxDecompiler.getVersion()); version.setAlignmentX(0.5f); String javaVm = System.getProperty("java.vm.name"); String javaVer = System.getProperty("java.version"); javaVm = javaVm == null ? "" : javaVm; JLabel javaVmLabel = new JLabel("Java VM: " + javaVm); javaVmLabel.setAlignmentX(0.5f); javaVer = javaVer == null ? "" : javaVer; JLabel javaVerLabel = new JLabel("Java version: " + javaVer); javaVerLabel.setAlignmentX(0.5f); JPanel textPane = new JPanel(); textPane.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); textPane.setLayout(new BoxLayout(textPane, BoxLayout.PAGE_AXIS)); textPane.add(Box.createRigidArea(new Dimension(0, 10))); textPane.add(name); textPane.add(Box.createRigidArea(new Dimension(0, 10))); textPane.add(desc); textPane.add(Box.createRigidArea(new Dimension(0, 10))); textPane.add(version); textPane.add(Box.createRigidArea(new Dimension(0, 20))); textPane.add(javaVmLabel); textPane.add(javaVerLabel); textPane.add(Box.createRigidArea(new Dimension(0, 20))); JButton close = new JButton(NLS.str("tabs.close")); close.addActionListener(event -> dispose()); close.setAlignmentX(0.5f); Container contentPane = getContentPane(); contentPane.add(textPane, BorderLayout.CENTER); contentPane.add(close, BorderLayout.PAGE_END); UiUtils.setWindowIcons(this); setModalityType(ModalityType.APPLICATION_MODAL); setTitle(NLS.str("about_dialog.title")); pack(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLocationRelativeTo(null); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/dialog/LogViewerDialog.java
jadx-gui/src/main/java/jadx/gui/ui/dialog/LogViewerDialog.java
package jadx.gui.ui.dialog; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import jadx.gui.logs.LogOptions; import jadx.gui.logs.LogPanel; import jadx.gui.settings.JadxSettings; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class LogViewerDialog extends JFrame { private static final long serialVersionUID = -2188700277429054641L; private static LogViewerDialog openLogDialog; private final transient JadxSettings settings; private final transient LogPanel logPanel; public static void open(MainWindow mainWindow, LogOptions logOptions) { LogViewerDialog logDialog; if (openLogDialog != null) { logDialog = openLogDialog; } else { logDialog = new LogViewerDialog(mainWindow, logOptions); openLogDialog = logDialog; } logDialog.setVisible(true); logDialog.toFront(); } private LogViewerDialog(MainWindow mainWindow, LogOptions logOptions) { settings = mainWindow.getSettings(); UiUtils.setWindowIcons(this); Runnable dock = () -> { mainWindow.getSettings().saveDockLogViewer(true); dispose(); mainWindow.showLogViewer(LogOptions.current()); }; logPanel = new LogPanel(mainWindow, logOptions, dock, this::dispose); Container contentPane = getContentPane(); contentPane.add(logPanel, BorderLayout.CENTER); setTitle(NLS.str("log_viewer.title")); pack(); setSize(800, 600); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setLocationRelativeTo(null); settings.loadWindowPos(this); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { openLogDialog = null; } }); } @Override public void dispose() { logPanel.dispose(); settings.saveWindowPos(this); super.dispose(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/popupmenu/RecentProjectsMenuListener.java
jadx-gui/src/main/java/jadx/gui/ui/popupmenu/RecentProjectsMenuListener.java
package jadx.gui.ui.popupmenu; import java.nio.file.Path; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; public class RecentProjectsMenuListener implements MenuListener { private final MainWindow mainWindow; private final JMenu menu; public RecentProjectsMenuListener(MainWindow mainWindow, JMenu menu) { this.mainWindow = mainWindow; this.menu = menu; } @Override public void menuSelected(MenuEvent menuEvent) { Set<Path> current = new HashSet<>(mainWindow.getProject().getFilePaths()); List<JMenuItem> items = mainWindow.getSettings().getRecentProjects() .stream() .filter(path -> !current.contains(path)) .map(path -> { JMenuItem menuItem = new JMenuItem(path.toAbsolutePath().toString()); menuItem.addActionListener(e -> mainWindow.open(Collections.singletonList(path))); return menuItem; }).collect(Collectors.toList()); menu.removeAll(); if (items.isEmpty()) { menu.add(new JMenuItem(NLS.str("menu.no_recent_projects"))); } else { items.forEach(menu::add); } } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JPackagePopupMenu.java
jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JPackagePopupMenu.java
package jadx.gui.ui.popupmenu; import java.awt.event.ActionEvent; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.JadxWrapper; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JPackage; import jadx.gui.ui.MainWindow; import jadx.gui.ui.dialog.ExcludePkgDialog; import jadx.gui.ui.dialog.RenameDialog; import jadx.gui.ui.dialog.SearchDialog; import jadx.gui.ui.filedialog.FileDialogWrapper; import jadx.gui.ui.filedialog.FileOpenMode; import jadx.gui.utils.NLS; import jadx.gui.utils.pkgs.JRenamePackage; import jadx.gui.utils.pkgs.PackageHelper; public class JPackagePopupMenu extends JPopupMenu { private static final long serialVersionUID = -7781009781149224131L; private static final Logger LOG = LoggerFactory.getLogger(JPackagePopupMenu.class); private final transient MainWindow mainWindow; public JPackagePopupMenu(MainWindow mainWindow, JPackage pkg) { this.mainWindow = mainWindow; add(makeExcludeItem(pkg)); add(makeExcludeItem()); add(makeRenameMenuItem(pkg)); add(makeExportSubMenu(pkg)); add(makeSearchItem(pkg)); } private JMenuItem makeRenameMenuItem(JPackage pkg) { JMenuItem renameSubMenu = new JMenu(NLS.str("popup.rename")); PackageHelper packageHelper = mainWindow.getCacheObject().getPackageHelper(); List<JRenamePackage> nodes = packageHelper.getRenameNodes(pkg); for (JRenamePackage node : nodes) { JMenuItem pkgPartItem = new JMenuItem(node.getTitle(), node.getIcon()); pkgPartItem.addActionListener(e -> rename(node)); renameSubMenu.add(pkgPartItem); } return renameSubMenu; } private void rename(JRenamePackage pkg) { LOG.debug("Renaming package: {}", pkg); RenameDialog.rename(mainWindow, pkg); } private JMenuItem makeExcludeItem(JPackage pkg) { JMenuItem excludeItem = new JCheckBoxMenuItem(NLS.str("popup.exclude")); excludeItem.setSelected(!pkg.isEnabled()); excludeItem.addItemListener(e -> { JadxWrapper wrapper = mainWindow.getWrapper(); String fullName = pkg.getPkg().getFullName(); if (excludeItem.isSelected()) { wrapper.addExcludedPackage(fullName); } else { wrapper.removeExcludedPackage(fullName); } mainWindow.reopen(); }); return excludeItem; } private JMenuItem makeExportSubMenu(JPackage pkg) { JMenu exportSubMenu = new JMenu(NLS.str("popup.export")); exportSubMenu.add(makeExportMenuItem(pkg, NLS.str("tabs.code"), JClassExportType.Code)); exportSubMenu.add(makeExportMenuItem(pkg, NLS.str("tabs.smali"), JClassExportType.Smali)); exportSubMenu.add(makeExportMenuItem(pkg, "Simple", JClassExportType.Simple)); exportSubMenu.add(makeExportMenuItem(pkg, "Fallback", JClassExportType.Fallback)); return exportSubMenu; } public JMenuItem makeExportMenuItem(JPackage pkg, String label, JClassExportType exportType) { JMenuItem exportMenuItem = new JMenuItem(label); exportMenuItem.addActionListener(event -> { FileDialogWrapper fileDialog = new FileDialogWrapper(mainWindow, FileOpenMode.EXPORT_NODE_FOLDER); List<Path> selectedPaths = fileDialog.show(); if (selectedPaths.size() != 1) { return; } Path savePath = selectedPaths.get(0); saveJPackage(pkg, savePath, exportType); }); return exportMenuItem; } private static void saveJPackage(JPackage pkg, Path savePath, JClassExportType exportType) { Path subSavePath = savePath.resolve(pkg.getName()); try { if (!Files.isDirectory(subSavePath)) { Files.createDirectory(subSavePath); } } catch (IOException e) { throw new RuntimeException(e); } for (JClass jClass : pkg.getClasses()) { String fileName = jClass.getName() + "." + exportType.extension; JClassPopupMenu.saveJClass(jClass, subSavePath.resolve(fileName), exportType); } for (JPackage subPkg : pkg.getSubPackages()) { saveJPackage(subPkg, subSavePath, exportType); } } private JMenuItem makeExcludeItem() { return new JMenuItem(new AbstractAction(NLS.str("popup.exclude_packages")) { private static final long serialVersionUID = -1111111202104151028L; @Override public void actionPerformed(ActionEvent e) { new ExcludePkgDialog(mainWindow).setVisible(true); } }); } private JMenuItem makeSearchItem(JPackage pkg) { JMenuItem searchItem = new JMenuItem(NLS.str("menu.text_search")); searchItem.addActionListener(e -> { String fullName = pkg.getPkg().getFullName(); LOG.debug("Searching package: {}", fullName); SearchDialog.searchPackage(mainWindow, fullName); }); return searchItem; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JClassExportType.java
jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JClassExportType.java
package jadx.gui.ui.popupmenu; public enum JClassExportType { Code("java"), Smali("smali"), Simple("java"), Fallback("java"); final String extension; JClassExportType(String extension) { this.extension = extension; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/popupmenu/VarTreePopupMenu.java
jadx-gui/src/main/java/jadx/gui/ui/popupmenu/VarTreePopupMenu.java
package jadx.gui.ui.popupmenu; import java.awt.Component; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.instructions.args.ArgType; import jadx.gui.ui.MainWindow; import jadx.gui.ui.dialog.SetValueDialog; import jadx.gui.ui.panel.JDebuggerPanel.ValueTreeNode; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class VarTreePopupMenu extends JPopupMenu { private static final Logger LOG = LoggerFactory.getLogger(VarTreePopupMenu.class); private static final long serialVersionUID = -1111111202103170724L; private final MainWindow mainWindow; private ValueTreeNode valNode; public VarTreePopupMenu(MainWindow mainWindow) { this.mainWindow = mainWindow; addItems(); } public void show(ValueTreeNode treeNode, Component invoker, int x, int y) { valNode = treeNode; super.show(invoker, x, y); } private void addItems() { JMenuItem copyValItem = new JMenuItem(new AbstractAction(NLS.str("debugger.popup_copy_value")) { private static final long serialVersionUID = -1111111202103171118L; @Override public void actionPerformed(ActionEvent e) { String val = valNode.getValue(); if (val != null) { if (val.startsWith("\"") && val.endsWith("\"")) { val = val.substring(1, val.length() - 1); } StringSelection stringSelection = new StringSelection(val); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); } } }); JMenuItem setValItem = new JMenuItem(new AbstractAction(NLS.str("debugger.popup_set_value")) { private static final long serialVersionUID = -1111111202103171119L; @Override public void actionPerformed(ActionEvent e) { (new SetValueDialog(mainWindow, valNode)).setVisible(true); } }); JMenuItem zeroItem = new JMenuItem(new AbstractAction(NLS.str("debugger.popup_change_to_zero")) { private static final long serialVersionUID = -1111111202103171120L; @Override public void actionPerformed(ActionEvent event) { try { mainWindow.getDebuggerPanel() .getDbgController() .modifyRegValue(valNode, ArgType.INT, 0); } catch (Exception e) { LOG.error("Change to zero failed", e); UiUtils.showMessageBox(mainWindow, e.getMessage()); } } }); JMenuItem oneItem = new JMenuItem(new AbstractAction(NLS.str("debugger.popup_change_to_one")) { private static final long serialVersionUID = -1111111202103171121L; @Override public void actionPerformed(ActionEvent event) { try { mainWindow.getDebuggerPanel() .getDbgController() .modifyRegValue(valNode, ArgType.INT, 1); } catch (Exception e) { LOG.error("Change to one failed", e); UiUtils.showMessageBox(mainWindow, e.getMessage()); } } }); this.add(copyValItem); this.add(new Separator()); this.add(setValItem); this.add(zeroItem); this.add(oneItem); this.add(zeroItem); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JClassPopupMenu.java
jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JClassPopupMenu.java
package jadx.gui.ui.popupmenu; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Locale; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.DecompilationMode; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.mode.JCodeMode; import jadx.gui.ui.dialog.RenameDialog; import jadx.gui.ui.filedialog.FileDialogWrapper; import jadx.gui.ui.filedialog.FileOpenMode; import jadx.gui.utils.NLS; public class JClassPopupMenu extends JPopupMenu { private static final long serialVersionUID = -7781009781149260806L; private static final Logger LOG = LoggerFactory.getLogger(JClassPopupMenu.class); private final transient MainWindow mainWindow; public JClassPopupMenu(MainWindow mainWindow, JClass jClass) { this.mainWindow = mainWindow; add(RenameDialog.buildRenamePopupMenuItem(mainWindow, jClass)); add(makeExportSubMenu(jClass)); } private JMenuItem makeExportSubMenu(JClass jClass) { JMenu exportSubMenu = new JMenu(NLS.str("popup.export")); exportSubMenu.add(makeExportMenuItem(jClass, NLS.str("tabs.code"), JClassExportType.Code)); exportSubMenu.add(makeExportMenuItem(jClass, NLS.str("tabs.smali"), JClassExportType.Smali)); exportSubMenu.add(makeExportMenuItem(jClass, "Simple", JClassExportType.Simple)); exportSubMenu.add(makeExportMenuItem(jClass, "Fallback", JClassExportType.Fallback)); return exportSubMenu; } public JMenuItem makeExportMenuItem(JClass jClass, String label, JClassExportType exportType) { JMenuItem exportMenuItem = new JMenuItem(label); exportMenuItem.addActionListener(event -> { String fileName = jClass.getName() + "." + exportType.extension; FileDialogWrapper fileDialog = new FileDialogWrapper(mainWindow, FileOpenMode.EXPORT_NODE); fileDialog.setFileExtList(Collections.singletonList(exportType.extension)); Path currentDir = fileDialog.getCurrentDir(); if (currentDir != null) { fileDialog.setSelectedFile(currentDir.resolve(fileName)); } List<Path> selectedPaths = fileDialog.show(); if (selectedPaths.size() != 1) { return; } Path selectedPath = selectedPaths.get(0); Path savePath; // Append file extension if missing if (!selectedPath.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(exportType.extension)) { savePath = selectedPath.resolveSibling(selectedPath.getFileName() + "." + exportType.extension); } else { savePath = selectedPath; } saveJClass(jClass, savePath, exportType); LOG.info("Done saving {}", savePath); }); return exportMenuItem; } public static void saveJClass(JClass jClass, Path savePath, JClassExportType exportType) { try (Writer writer = Files.newBufferedWriter(savePath, StandardCharsets.UTF_8)) { writer.write(getCode(jClass, exportType)); } catch (Exception e) { throw new RuntimeException("Error saving project", e); } } private static String getCode(JClass jClass, JClassExportType exportType) { switch (exportType) { case Code: return jClass.getCodeInfo().getCodeStr(); case Smali: return jClass.getSmali(); case Simple: JNode jClassSimple = new JCodeMode(jClass, DecompilationMode.SIMPLE); return jClassSimple.getCodeInfo().getCodeStr(); case Fallback: JNode jClassFallback = new JCodeMode(jClass, DecompilationMode.FALLBACK); return jClassFallback.getCodeInfo().getCodeStr(); default: throw new RuntimeException("Unsupported JClassExportType " + exportType); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JResourcePopupMenu.java
jadx-gui/src/main/java/jadx/gui/ui/popupmenu/JResourcePopupMenu.java
package jadx.gui.ui.popupmenu; import java.io.IOException; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Locale; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.plugins.utils.CommonFileUtils; import jadx.gui.treemodel.JResource; import jadx.gui.ui.MainWindow; import jadx.gui.ui.filedialog.FileDialogWrapper; import jadx.gui.ui.filedialog.FileOpenMode; import jadx.gui.utils.NLS; import jadx.gui.utils.ui.FileOpenerHelper; public class JResourcePopupMenu extends JPopupMenu { private static final long serialVersionUID = -7781009781149260806L; private static final Logger LOG = LoggerFactory.getLogger(JResourcePopupMenu.class); private final transient MainWindow mainWindow; public JResourcePopupMenu(MainWindow mainWindow, JResource resource) { this.mainWindow = mainWindow; if (resource.getType() != JResource.JResType.ROOT) { add(makeExportMenuItem(resource)); } } private JMenuItem makeExportMenuItem(JResource resource) { JMenuItem exportMenu = new JMenuItem(NLS.str("popup.export")); exportMenu.addActionListener(event -> { Path savePath = null; switch (resource.getType()) { case ROOT: case DIR: savePath = getSaveDirPath(resource); break; case FILE: savePath = getSaveFilePath(resource); break; } if (savePath == null) { return; } saveJResource(resource, savePath, true); LOG.info("Done saving {}", savePath); }); return exportMenu; } private Path getSaveFilePath(JResource resource) { String extension = CommonFileUtils.getFileExtension(resource.getName()); FileDialogWrapper fileDialog = new FileDialogWrapper(mainWindow, FileOpenMode.EXPORT_NODE); if (extension != null) { fileDialog.setFileExtList(Collections.singletonList(extension)); } Path currentDir = fileDialog.getCurrentDir(); if (currentDir != null) { fileDialog.setSelectedFile(currentDir.resolve(resource.getName())); } List<Path> selectedPaths = fileDialog.show(); if (selectedPaths.size() != 1) { return null; } Path selectedPath = selectedPaths.get(0); Path savePath; // Append file extension if missing if (extension != null && !selectedPath.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(extension)) { savePath = selectedPath.resolveSibling(selectedPath.getFileName() + "." + extension); } else { savePath = selectedPath; } return savePath; } private Path getSaveDirPath(JResource resource) { FileDialogWrapper fileDialog = new FileDialogWrapper(mainWindow, FileOpenMode.EXPORT_NODE_FOLDER); List<Path> selectedPaths = fileDialog.show(); if (selectedPaths.size() != 1) { return null; } return selectedPaths.get(0); } private static void saveJResource(JResource resource, Path savePath, boolean comingFromDialog) { switch (resource.getType()) { case ROOT: case DIR: saveJResourceDir(resource, savePath, comingFromDialog); break; case FILE: saveJResourceFile(resource, savePath, comingFromDialog); break; } } private static void saveJResourceDir(JResource resource, Path savePath, boolean comingFromDialog) { Path subSavePath = savePath.resolve(resource.getName()); try { if (!Files.isDirectory(subSavePath)) { Files.createDirectory(subSavePath); } } catch (IOException e) { throw new RuntimeException(e); } for (JResource subResource : resource.getSubNodes()) { saveJResource(subResource, subSavePath, false); } } private static void saveJResourceFile(JResource resource, Path savePath, boolean comingFromDialog) { if (!comingFromDialog) { Path fileName = Path.of(resource.getName()).getFileName(); savePath = savePath.resolve(fileName); } switch (resource.getResFile().getType()) { case MANIFEST: case XML: exportString(resource, savePath); break; default: FileOpenerHelper.exportBinary(resource, savePath); break; } } private static void exportString(JResource resource, Path savePath) { try (Writer writer = Files.newBufferedWriter(savePath, StandardCharsets.UTF_8)) { writer.write(resource.getCodeInfo().getCodeStr()); } catch (Exception e) { throw new RuntimeException("Error saving file " + resource.getName(), e); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/IShortcutAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/IShortcutAction.java
package jadx.gui.ui.action; import javax.swing.JComponent; import jadx.gui.utils.shortcut.Shortcut; public interface IShortcutAction { ActionModel getActionModel(); JComponent getShortcutComponent(); void performAction(); void setShortcut(Shortcut shortcut); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/ActionModel.java
jadx-gui/src/main/java/jadx/gui/ui/action/ActionModel.java
package jadx.gui.ui.action; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javax.swing.ImageIcon; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.shortcut.Shortcut; import static jadx.gui.ui.action.ActionCategory.*; public enum ActionModel { ABOUT(MENU_TOOLBAR, "menu.about", "menu.about", "ui/showInfos", Shortcut.keyboard(KeyEvent.VK_F1)), OPEN(MENU_TOOLBAR, "file.open_action", "file.open_action", "ui/openDisk", Shortcut.keyboard(KeyEvent.VK_O, KeyEvent.CTRL_DOWN_MASK)), OPEN_PROJECT(MENU_TOOLBAR, "file.open_project", "file.open_project", "ui/projectDirectory", Shortcut.keyboard(KeyEvent.VK_O, InputEvent.SHIFT_DOWN_MASK | UiUtils.ctrlButton())), ADD_FILES(MENU_TOOLBAR, "file.add_files_action", "file.add_files_action", "ui/addFile", Shortcut.none()), NEW_PROJECT(MENU_TOOLBAR, "file.new_project", "file.new_project", "ui/newFolder", Shortcut.none()), SAVE_PROJECT(MENU_TOOLBAR, "file.save_project", "file.save_project", null, Shortcut.none()), SAVE_PROJECT_AS(MENU_TOOLBAR, "file.save_project_as", "file.save_project_as", null, Shortcut.none()), RELOAD(MENU_TOOLBAR, "file.reload", "file.reload", "ui/refresh", Shortcut.keyboard(KeyEvent.VK_F5)), LIVE_RELOAD(MENU_TOOLBAR, "file.live_reload", "file.live_reload_desc", null, Shortcut.keyboard(KeyEvent.VK_F5, InputEvent.SHIFT_DOWN_MASK)), SAVE_ALL(MENU_TOOLBAR, "file.save_all", "file.save_all", "ui/menu-saveall", Shortcut.keyboard(KeyEvent.VK_E, UiUtils.ctrlButton())), EXPORT(MENU_TOOLBAR, "file.export", "file.export", "ui/export", Shortcut.keyboard(KeyEvent.VK_E, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)), PREFS(MENU_TOOLBAR, "menu.preferences", "menu.preferences", "ui/settings", Shortcut.keyboard(KeyEvent.VK_P, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)), EXIT(MENU_TOOLBAR, "file.exit", "file.exit", "ui/exit", Shortcut.none()), SYNC(MENU_TOOLBAR, "menu.sync", "menu.sync", "ui/locate", Shortcut.keyboard(KeyEvent.VK_T, UiUtils.ctrlButton())), TEXT_SEARCH(MENU_TOOLBAR, "menu.text_search", "menu.text_search", "ui/find", Shortcut.keyboard(KeyEvent.VK_F, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)), CLASS_SEARCH(MENU_TOOLBAR, "menu.class_search", "menu.class_search", "ui/ejbFinderMethod", Shortcut.keyboard(KeyEvent.VK_N, UiUtils.ctrlButton())), COMMENT_SEARCH(MENU_TOOLBAR, "menu.comment_search", "menu.comment_search", "ui/usagesFinder", Shortcut.keyboard(KeyEvent.VK_SEMICOLON, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)), GO_TO_MAIN_ACTIVITY(MENU_TOOLBAR, "menu.go_to_main_activity", "menu.go_to_main_activity", "ui/home", Shortcut.keyboard(KeyEvent.VK_M, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)), GO_TO_APPLICATION(MENU_TOOLBAR, "menu.go_to_application", "menu.go_to_application", "ui/application", Shortcut.keyboard(KeyEvent.VK_A, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)), GO_TO_ANDROID_MANIFEST(MENU_TOOLBAR, "menu.go_to_android_manifest", "menu.go_to_android_manifest", "ui/androidManifest", Shortcut.none()), PREVIEW_TAB(MENU_TOOLBAR, "menu.enable_preview_tab", "menu.enable_preview_tab", "ui/editorPreview", Shortcut.none()), DECOMPILE_ALL(MENU_TOOLBAR, "menu.decompile_all", "menu.decompile_all", "ui/runAll", Shortcut.none()), RESET_CACHE(MENU_TOOLBAR, "menu.reset_cache", "menu.reset_cache", "ui/reset", Shortcut.none()), DEOBF(MENU_TOOLBAR, "menu.deobfuscation", "preferences.deobfuscation", "ui/helmChartLock", Shortcut.keyboard(KeyEvent.VK_D, UiUtils.ctrlButton() | KeyEvent.ALT_DOWN_MASK)), SHOW_LOG(MENU_TOOLBAR, "menu.log", "menu.log", "ui/logVerbose", Shortcut.keyboard(KeyEvent.VK_L, UiUtils.ctrlButton() | KeyEvent.SHIFT_DOWN_MASK)), CREATE_DESKTOP_ENTRY(MENU_TOOLBAR, "menu.create_desktop_entry", "menu.create_desktop_entry", null, Shortcut.none()), BACK(MENU_TOOLBAR, "nav.back", "nav.back", "ui/left", Shortcut.keyboard(KeyEvent.VK_ESCAPE)), BACK_V(MENU_TOOLBAR, "nav.back", "nav.back", "ui/left", Shortcut.none()), FORWARD(MENU_TOOLBAR, "nav.forward", "nav.forward", "ui/right", Shortcut.keyboard(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK)), FORWARD_V(MENU_TOOLBAR, "nav.forward", "nav.forward", "ui/right", Shortcut.none()), QUARK(MENU_TOOLBAR, "menu.quark", "menu.quark", "ui/quark", Shortcut.none()), OPEN_DEVICE(MENU_TOOLBAR, "debugger.process_selector", "debugger.process_selector", "ui/startDebugger", Shortcut.none()), FIND_USAGE(CODE_AREA, "popup.find_usage", "popup.find_usage", null, Shortcut.keyboard(KeyEvent.VK_X)), FIND_USAGE_PLUS(CODE_AREA, "popup.usage_dialog_plus", "popup.usage_dialog_plus", null, Shortcut.keyboard(KeyEvent.VK_C)), GOTO_DECLARATION(CODE_AREA, "popup.go_to_declaration", "popup.go_to_declaration", null, Shortcut.keyboard(KeyEvent.VK_D)), CODE_COMMENT(CODE_AREA, "popup.add_comment", "popup.add_comment", null, Shortcut.keyboard(KeyEvent.VK_SEMICOLON)), CODE_COMMENT_SEARCH(CODE_AREA, "popup.search_comment", "popup.search_comment", null, Shortcut.keyboard(KeyEvent.VK_SEMICOLON, UiUtils.ctrlButton())), CODE_RENAME(CODE_AREA, "popup.rename", "popup.rename", null, Shortcut.keyboard(KeyEvent.VK_N)), FRIDA_COPY(CODE_AREA, "popup.frida", "popup.frida", null, Shortcut.keyboard(KeyEvent.VK_F)), XPOSED_COPY(CODE_AREA, "popup.xposed", "popup.xposed", null, Shortcut.keyboard(KeyEvent.VK_Y)), JSON_PRETTIFY(CODE_AREA, "popup.json_prettify", "popup.json_prettify", null, Shortcut.none()), SCRIPT_RUN(PLUGIN_SCRIPT, "script.run", "script.run", "ui/run", Shortcut.keyboard(KeyEvent.VK_F8)), SCRIPT_SAVE(PLUGIN_SCRIPT, "script.save", "script.save", "ui/menu-saveall", Shortcut.keyboard(KeyEvent.VK_S, UiUtils.ctrlButton())), SCRIPT_AUTO_COMPLETE(PLUGIN_SCRIPT, "script.auto_complete", "script.auto_complete", null, Shortcut.keyboard(KeyEvent.VK_SPACE, UiUtils.ctrlButton())), HEX_VIEWER_SHOW_INSPECTOR(HEX_VIEWER_MENU, "hex_viewer.show_inspector", "hex_viewer.show_inspector", null, Shortcut.none()), HEX_VIEWER_CHANGE_ENCODING(HEX_VIEWER_MENU, "hex_viewer.change_encoding", "hex_viewer.change_encoding", null, Shortcut.none()), HEX_VIEWER_GO_TO_ADDRESS(HEX_VIEWER_MENU, "hex_viewer.goto_address", "hex_viewer.goto_address", null, Shortcut.keyboard(KeyEvent.VK_J, UiUtils.ctrlButton())), HEX_VIEWER_FIND(HEX_VIEWER_MENU, "hex_viewer.find", "hex_viewer.find", null, Shortcut.keyboard(KeyEvent.VK_F, UiUtils.ctrlButton())); private final ActionCategory category; private final String nameRes; private final String descRes; private final String iconPath; private final Shortcut defaultShortcut; ActionModel(ActionCategory category, String nameRes, String descRes, String iconPath, Shortcut defaultShortcut) { this.category = category; this.nameRes = nameRes; this.descRes = descRes; this.iconPath = iconPath; this.defaultShortcut = defaultShortcut; } public static List<ActionModel> select(ActionCategory category) { return Arrays.stream(values()) .filter(actionModel -> actionModel.category == category) .collect(Collectors.toUnmodifiableList()); } public ActionCategory getCategory() { return category; } public String getName() { if (nameRes != null) { String name = NLS.str(nameRes); if (name().endsWith("_V")) { name = NLS.str("action.variant", name); } return name; } return null; } public String getDescription() { if (descRes != null) { return NLS.str(descRes); } return null; } public ImageIcon getIcon() { if (iconPath != null) { return UiUtils.openSvgIcon(iconPath); } return null; } public Shortcut getDefaultShortcut() { return defaultShortcut; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/RenameAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/RenameAction.java
package jadx.gui.ui.action; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JRenameNode; import jadx.gui.ui.codearea.CodeArea; import jadx.gui.ui.dialog.RenameDialog; public final class RenameAction extends JNodeAction { private static final long serialVersionUID = -4680872086148463289L; public RenameAction(CodeArea codeArea) { super(ActionModel.CODE_RENAME, codeArea); } @Override public boolean isActionEnabled(JNode node) { if (node == null) { return false; } if (node instanceof JRenameNode) { return ((JRenameNode) node).canRename(); } return false; } @Override public void runAction(JNode node) { RenameDialog.rename(getCodeArea().getMainWindow(), (JRenameNode) node); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/CodeAreaAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/CodeAreaAction.java
package jadx.gui.ui.action; import jadx.gui.ui.codearea.CodeArea; public class CodeAreaAction extends JadxGuiAction { protected transient CodeArea codeArea; public CodeAreaAction(ActionModel actionModel, CodeArea codeArea) { super(actionModel); this.codeArea = codeArea; setShortcutComponent(codeArea); } public CodeAreaAction(String id, CodeArea codeArea) { super(id); this.codeArea = codeArea; setShortcutComponent(codeArea); } public void dispose() { codeArea = null; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/JsonPrettifyAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/JsonPrettifyAction.java
package jadx.gui.ui.action; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import jadx.core.utils.GsonUtils; import jadx.gui.treemodel.JNode; import jadx.gui.ui.codearea.CodeArea; public class JsonPrettifyAction extends JNodeAction { private static final long serialVersionUID = -2682529369671695550L; private static final Gson GSON = GsonUtils.buildGson(); public JsonPrettifyAction(CodeArea codeArea) { super(ActionModel.JSON_PRETTIFY, codeArea); } @Override public void runAction(JNode node) { String originString = getCodeArea().getCodeInfo().getCodeStr(); JsonElement je = JsonParser.parseString(originString); String prettyString = GSON.toJson(je); getCodeArea().setText(prettyString); } @Override public boolean isActionEnabled(JNode node) { return true; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/CommentSearchAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/CommentSearchAction.java
package jadx.gui.ui.action; import java.awt.event.ActionEvent; import jadx.gui.ui.codearea.CodeArea; import jadx.gui.ui.dialog.SearchDialog; public class CommentSearchAction extends CodeAreaAction { private static final long serialVersionUID = -3646341661734961590L; public CommentSearchAction(CodeArea codeArea) { super(ActionModel.CODE_COMMENT_SEARCH, codeArea); } @Override public void actionPerformed(ActionEvent e) { startSearch(); } private void startSearch() { SearchDialog.searchInActiveTab(codeArea.getMainWindow(), SearchDialog.SearchPreset.COMMENT); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/JadxGuiAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/JadxGuiAction.java
package jadx.gui.ui.action; import java.awt.event.ActionEvent; import java.util.function.Consumer; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.KeyStroke; import org.jetbrains.annotations.Nullable; import jadx.gui.ui.menu.JadxMenu; import jadx.gui.utils.UiUtils; import jadx.gui.utils.shortcut.Shortcut; import jadx.gui.utils.ui.ActionHandler; public class JadxGuiAction extends ActionHandler implements IShortcutAction { private static final String COMMAND_PREFIX = "JadxGuiAction.Command."; private final ActionModel actionModel; private final String id; private JComponent shortcutComponent = null; private KeyStroke addedKeyStroke = null; private Shortcut shortcut; public JadxGuiAction(ActionModel actionModel) { this.actionModel = actionModel; this.id = actionModel.name(); updateProperties(); } public JadxGuiAction(ActionModel actionModel, Runnable action) { super(action); this.actionModel = actionModel; this.id = actionModel.name(); updateProperties(); } public JadxGuiAction(ActionModel actionModel, Consumer<ActionEvent> consumer) { super(consumer); this.actionModel = actionModel; this.id = actionModel.name(); updateProperties(); } public JadxGuiAction(String id) { this.actionModel = null; this.id = id; updateProperties(); } private void updateProperties() { if (actionModel == null) { return; } String name = actionModel.getName(); String description = actionModel.getDescription(); ImageIcon icon = actionModel.getIcon(); if (name != null) { setName(name); } if (description != null) { setShortDescription(description); } if (icon != null) { setIcon(icon); } } @Nullable public ActionModel getActionModel() { return actionModel; } @Override public void setShortcut(Shortcut shortcut) { this.shortcut = shortcut; if (shortcut != null) { setKeyBinding(shortcut.toKeyStroke()); } else { setKeyBinding(null); } } public void setShortcutComponent(JComponent component) { this.shortcutComponent = component; } @Override public JComponent getShortcutComponent() { return shortcutComponent; } @Override public void actionPerformed(ActionEvent e) { super.actionPerformed(e); } @Override public void performAction() { if (shortcutComponent != null) { if (shortcutComponent == JadxMenu.JADX_MENU_COMPONENT) { // always enabled } else if (!shortcutComponent.isShowing()) { return; } } String shortcutType = shortcut != null ? shortcut.getTypeString() : "null"; actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, COMMAND_PREFIX + shortcutType)); } public static boolean isSource(ActionEvent event) { String command = event.getActionCommand(); return command != null && command.startsWith(COMMAND_PREFIX); } @Override public void setKeyBinding(KeyStroke keyStroke) { if (shortcutComponent == null) { super.setKeyBinding(keyStroke); } else { // We just set the keyStroke for it to appear in the menu item // (grayed out in the right) super.setKeyBinding(keyStroke); if (addedKeyStroke != null) { UiUtils.removeKeyBinding(shortcutComponent, addedKeyStroke, id); } UiUtils.addKeyBinding(shortcutComponent, keyStroke, id, this::performAction); addedKeyStroke = keyStroke; } } @Override public String toString() { return "JadxGuiAction{" + id + ", component: " + shortcutComponent + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/FridaAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/FridaAction.java
package jadx.gui.ui.action; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import org.apache.commons.text.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JavaClass; import jadx.api.JavaField; import jadx.api.JavaMethod; import jadx.api.metadata.annotations.VarNode; import jadx.core.codegen.TypeGen; import jadx.core.dex.info.MethodInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.core.dex.nodes.MethodNode; import jadx.core.utils.StringUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JField; import jadx.gui.treemodel.JMethod; import jadx.gui.treemodel.JNode; import jadx.gui.ui.codearea.CodeArea; import jadx.gui.ui.dialog.MethodsDialog; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public final class FridaAction extends JNodeAction { private static final Logger LOG = LoggerFactory.getLogger(FridaAction.class); private static final long serialVersionUID = -3084073927621269039L; public FridaAction(CodeArea codeArea) { super(ActionModel.FRIDA_COPY, codeArea); } @Override public void runAction(JNode node) { try { generateFridaSnippet(node); } catch (Exception e) { LOG.error("Failed to generate Frida code snippet", e); JOptionPane.showMessageDialog(getCodeArea().getMainWindow(), e.getLocalizedMessage(), NLS.str("error_dialog.title"), JOptionPane.ERROR_MESSAGE); } } @Override public boolean isActionEnabled(JNode node) { return node instanceof JMethod || node instanceof JClass || node instanceof JField; } private void generateFridaSnippet(JNode node) { String fridaSnippet; if (node instanceof JMethod) { fridaSnippet = generateMethodSnippet((JMethod) node); copySnipped(fridaSnippet); } else if (node instanceof JField) { fridaSnippet = generateFieldSnippet((JField) node); copySnipped(fridaSnippet); } else if (node instanceof JClass) { SwingUtilities.invokeLater(() -> showMethodSelectionDialog((JClass) node)); } else { throw new JadxRuntimeException("Unsupported node type: " + (node != null ? node.getClass() : "null")); } } private void copySnipped(String fridaSnippet) { if (!StringUtils.isEmpty(fridaSnippet)) { LOG.info("Frida snippet:\n{}", fridaSnippet); UiUtils.copyToClipboard(fridaSnippet); } } private String generateMethodSnippet(JMethod jMth) { String classSnippet = generateClassSnippet(jMth.getJParent()); String methodSnippet = getMethodSnippet(jMth.getJavaMethod(), jMth.getJParent()); return String.format("%s\n%s", classSnippet, methodSnippet); } private String generateMethodSnippet(JavaMethod javaMethod, JClass jc) { return getMethodSnippet(javaMethod, jc); } private String getMethodSnippet(JavaMethod javaMethod, JClass jc) { MethodNode mth = javaMethod.getMethodNode(); MethodInfo methodInfo = mth.getMethodInfo(); String methodName; String newMethodName; if (methodInfo.isConstructor()) { methodName = "$init"; newMethodName = methodName; } else { methodName = StringEscapeUtils.escapeEcmaScript(methodInfo.getName()); newMethodName = StringEscapeUtils.escapeEcmaScript(methodInfo.getAlias()); } String overload; if (isOverloaded(mth)) { String overloadArgs = methodInfo.getArgumentsTypes().stream() .map(this::parseArgType).collect(Collectors.joining(", ")); overload = ".overload(" + overloadArgs + ")"; } else { overload = ""; } List<String> argNames = mth.collectArgNodes().stream() .map(VarNode::getName).collect(Collectors.toList()); String args = String.join(", ", argNames); String logArgs; if (argNames.isEmpty()) { logArgs = ""; } else { logArgs = ": " + argNames.stream().map(arg -> arg + "=${" + arg + "}").collect(Collectors.joining(", ")); } String shortClassName = mth.getParentClass().getAlias(); if (methodInfo.isConstructor() || methodInfo.getReturnType() == ArgType.VOID) { // no return value return shortClassName + "[\"" + methodName + "\"]" + overload + ".implementation = function (" + args + ") {\n" + " console.log(`" + shortClassName + "." + newMethodName + " is called" + logArgs + "`);\n" + " this[\"" + methodName + "\"](" + args + ");\n" + "};"; } return shortClassName + "[\"" + methodName + "\"]" + overload + ".implementation = function (" + args + ") {\n" + " console.log(`" + shortClassName + "." + newMethodName + " is called" + logArgs + "`);\n" + " let result = this[\"" + methodName + "\"](" + args + ");\n" + " console.log(`" + shortClassName + "." + newMethodName + " result=${result}`);\n" + " return result;\n" + "};"; } private String generateClassSnippet(JClass jc) { JavaClass javaClass = jc.getCls(); String rawClassName = StringEscapeUtils.escapeEcmaScript(javaClass.getRawName()); String shortClassName = javaClass.getName(); return String.format("var %s = Java.use(\"%s\");", shortClassName, rawClassName); } private void showMethodSelectionDialog(JClass jc) { JavaClass javaClass = jc.getCls(); new MethodsDialog(getCodeArea().getMainWindow(), javaClass.getMethods(), (result) -> { String fridaSnippet = generateClassAllMethodSnippet(jc, result); copySnipped(fridaSnippet); }); } private String generateClassAllMethodSnippet(JClass jc, List<JavaMethod> methodList) { StringBuilder result = new StringBuilder(); String classSnippet = generateClassSnippet(jc); result.append(classSnippet).append("\n"); for (JavaMethod javaMethod : methodList) { result.append(generateMethodSnippet(javaMethod, jc)).append("\n"); } return result.toString(); } private String generateFieldSnippet(JField jf) { JavaField javaField = jf.getJavaField(); String rawFieldName = StringEscapeUtils.escapeEcmaScript(javaField.getRawName()); String fieldName = javaField.getName(); List<MethodNode> methodNodes = javaField.getFieldNode().getParentClass().getMethods(); for (MethodNode methodNode : methodNodes) { if (methodNode.getName().equals(rawFieldName)) { rawFieldName = "_" + rawFieldName; break; } } JClass jc = jf.getRootClass(); String classSnippet = generateClassSnippet(jc); return String.format("%s\n%s = %s.%s.value;", classSnippet, fieldName, jc.getName(), rawFieldName); } public Boolean isOverloaded(MethodNode methodNode) { return methodNode.getParentClass().getMethods().stream() .anyMatch(m -> m.getName().equals(methodNode.getName()) && !Objects.equals(methodNode.getMethodInfo().getShortId(), m.getMethodInfo().getShortId())); } private String parseArgType(ArgType x) { String typeStr; if (x.isArray()) { typeStr = TypeGen.signature(x).replace("/", "."); } else { typeStr = x.toString(); } return "'" + typeStr + "'"; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/JadxAutoCompletion.java
jadx-gui/src/main/java/jadx/gui/ui/action/JadxAutoCompletion.java
package jadx.gui.ui.action; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.JComponent; import javax.swing.KeyStroke; import org.fife.ui.autocomplete.AutoCompletion; import org.fife.ui.autocomplete.CompletionProvider; import jadx.gui.utils.shortcut.Shortcut; public class JadxAutoCompletion extends AutoCompletion implements IShortcutAction { public static final String COMMAND = "JadxAutoCompletion.Command"; /** * Constructor. * * @param provider The completion provider. This cannot be <code>null</code> */ public JadxAutoCompletion(CompletionProvider provider) { super(provider); } @Override public ActionModel getActionModel() { return ActionModel.SCRIPT_AUTO_COMPLETE; } @Override public JComponent getShortcutComponent() { return getTextComponent(); } @Override public void performAction() { createAutoCompleteAction().actionPerformed( new ActionEvent(this, ActionEvent.ACTION_PERFORMED, COMMAND)); } @Override public void setShortcut(Shortcut shortcut) { if (shortcut != null && shortcut.isKeyboard()) { setTriggerKey(shortcut.toKeyStroke()); } else { setTriggerKey(KeyStroke.getKeyStroke(KeyEvent.VK_UNDEFINED, 0)); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/GoToDeclarationAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/GoToDeclarationAction.java
package jadx.gui.ui.action; import jadx.gui.treemodel.JNode; import jadx.gui.ui.codearea.CodeArea; public final class GoToDeclarationAction extends JNodeAction { private static final long serialVersionUID = -1186470538894941301L; public GoToDeclarationAction(CodeArea codeArea) { super(ActionModel.GOTO_DECLARATION, codeArea); } @Override public void runAction(JNode node) { getCodeArea().getContentPanel().getTabsController().codeJump(node); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/ActionCategory.java
jadx-gui/src/main/java/jadx/gui/ui/action/ActionCategory.java
package jadx.gui.ui.action; import jadx.gui.utils.NLS; public enum ActionCategory { MENU_TOOLBAR("action_category.menu_toolbar"), CODE_AREA("action_category.code_area"), PLUGIN_SCRIPT("action_category.plugin_script"), HEX_VIEWER_MENU("action_category.hex_viewer"); private final String nameRes; ActionCategory(String nameRes) { this.nameRes = nameRes; } public String getName() { if (nameRes != null) { return NLS.str(nameRes); } return null; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/JNodeAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/JNodeAction.java
package jadx.gui.ui.action; import java.awt.event.ActionEvent; import java.beans.PropertyChangeListener; import org.jetbrains.annotations.Nullable; import jadx.gui.treemodel.JNode; import jadx.gui.ui.codearea.CodeArea; /** * Add menu and key binding actions for JNode in code area */ public abstract class JNodeAction extends CodeAreaAction { private static final long serialVersionUID = -2600154727884853550L; private transient @Nullable JNode node; public JNodeAction(ActionModel actionModel, CodeArea codeArea) { super(actionModel, codeArea); } public JNodeAction(String id, CodeArea codeArea) { super(id, codeArea); } public abstract void runAction(JNode node); public boolean isActionEnabled(@Nullable JNode node) { return node != null; } @Override public void actionPerformed(ActionEvent e) { if (JadxGuiAction.isSource(e)) { node = codeArea.getNodeUnderCaret(); if (isActionEnabled(node)) { runAction(node); } } else { runAction(node); } } public void changeNode(@Nullable JNode node) { this.node = node; setEnabled(isActionEnabled(node)); } public CodeArea getCodeArea() { return codeArea; } @Override public void dispose() { super.dispose(); node = null; for (PropertyChangeListener changeListener : getPropertyChangeListeners()) { removePropertyChangeListener(changeListener); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/action/FindUsageAction.java
jadx-gui/src/main/java/jadx/gui/ui/action/FindUsageAction.java
package jadx.gui.ui.action; import jadx.gui.treemodel.JNode; import jadx.gui.ui.codearea.CodeArea; import jadx.gui.ui.dialog.UsageDialog; public final class FindUsageAction extends JNodeAction { private static final long serialVersionUID = 4692546569977976384L; public FindUsageAction(CodeArea codeArea) { super(ActionModel.FIND_USAGE, codeArea); } @Override public void runAction(JNode node) { UsageDialog.open(getCodeArea().getMainWindow(), node); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/ProgressPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/ProgressPanel.java
package jadx.gui.ui.panel; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import jadx.gui.jobs.ITaskProgress; import jadx.gui.ui.MainWindow; import jadx.gui.utils.Icons; import jadx.gui.utils.UiUtils; public class ProgressPanel extends JPanel { private static final long serialVersionUID = -3238438119672015733L; private final JProgressBar progressBar; private final JLabel progressLabel; private final JButton cancelButton; private final boolean showCancelButton; public ProgressPanel(final MainWindow mainWindow, boolean showCancelButton) { this.showCancelButton = showCancelButton; progressLabel = new JLabel(); progressBar = new JProgressBar(0, 100); progressBar.setIndeterminate(true); progressBar.setStringPainted(false); progressLabel.setLabelFor(progressBar); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setVisible(false); add(progressLabel); add(progressBar); Icon cancelIcon = Icons.ICON_CLOSE; cancelButton = new JButton(cancelIcon); cancelButton.setPreferredSize(new Dimension(cancelIcon.getIconWidth(), cancelIcon.getIconHeight())); cancelButton.setToolTipText("Cancel background jobs"); cancelButton.setBorderPainted(false); cancelButton.setFocusPainted(false); cancelButton.setContentAreaFilled(false); cancelButton.addActionListener(e -> mainWindow.cancelBackgroundJobs()); cancelButton.setVisible(showCancelButton); add(cancelButton); } public void reset() { cancelButton.setVisible(showCancelButton); progressBar.setIndeterminate(true); progressBar.setValue(0); progressBar.setString(""); progressBar.setStringPainted(true); } public void setProgress(ITaskProgress taskProgress) { int progress = taskProgress.progress(); int total = taskProgress.total(); if (progress == 0 || total == 0) { progressBar.setIndeterminate(true); } else { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); } setProgress(UiUtils.calcProgress(progress, total)); } } private void setProgress(int progress) { progressBar.setIndeterminate(false); progressBar.setValue(progress); progressBar.setString(progress + "%"); progressBar.setStringPainted(true); } public void setLabel(String label) { progressLabel.setText(label); } public void setIndeterminate(boolean newValue) { progressBar.setIndeterminate(newValue); } public void setCancelButtonVisible(boolean visible) { cancelButton.setVisible(visible); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/IssuesPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/IssuesPanel.java
package jadx.gui.ui.panel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import ch.qos.logback.classic.Level; import jadx.gui.logs.IssuesListener; import jadx.gui.logs.LogCollector; import jadx.gui.logs.LogOptions; import jadx.gui.ui.MainWindow; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class IssuesPanel extends JPanel { private static final long serialVersionUID = -7720576036668459218L; private static final ImageIcon ERROR_ICON = UiUtils.openSvgIcon("ui/error"); private static final ImageIcon WARN_ICON = UiUtils.openSvgIcon("ui/warning"); private final MainWindow mainWindow; private final IssuesListener issuesListener; private JLabel errorLabel; private JLabel warnLabel; public IssuesPanel(MainWindow mainWindow) { this.mainWindow = mainWindow; initUI(); this.issuesListener = new IssuesListener(this); LogCollector.getInstance().registerListener(issuesListener); } public int getErrorsCount() { return issuesListener.getErrors(); } private void initUI() { JLabel label = new JLabel(NLS.str("issues_panel.label")); errorLabel = new JLabel(ERROR_ICON); warnLabel = new JLabel(WARN_ICON); String toolTipText = NLS.str("issues_panel.tooltip"); errorLabel.setToolTipText(toolTipText); warnLabel.setToolTipText(toolTipText); errorLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { mainWindow.showLogViewer(LogOptions.allWithLevel(Level.ERROR)); } }); warnLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { mainWindow.showLogViewer(LogOptions.allWithLevel(Level.WARN)); } }); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setVisible(false); add(label); add(Box.createHorizontalGlue()); add(errorLabel); add(Box.createHorizontalGlue()); add(warnLabel); } public void onUpdate(int error, int warnings) { if (error == 0 && warnings == 0) { setVisible(false); return; } setVisible(true); errorLabel.setText(NLS.str("issues_panel.errors", error)); errorLabel.setVisible(error != 0); warnLabel.setText(NLS.str("issues_panel.warnings", warnings)); warnLabel.setVisible(warnings != 0); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/IViewStateSupport.java
jadx-gui/src/main/java/jadx/gui/ui/panel/IViewStateSupport.java
package jadx.gui.ui.panel; import jadx.gui.ui.codearea.EditorViewState; public interface IViewStateSupport { void saveEditorViewState(EditorViewState viewState); void restoreEditorViewState(EditorViewState viewState); }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/IDebugController.java
jadx-gui/src/main/java/jadx/gui/ui/panel/IDebugController.java
package jadx.gui.ui.panel; import jadx.core.dex.instructions.args.ArgType; import jadx.gui.ui.panel.JDebuggerPanel.ValueTreeNode; public interface IDebugController { boolean startDebugger(JDebuggerPanel debuggerPanel, String adbHost, int adbPort, int androidVer); boolean run(); boolean stepOver(); boolean stepInto(); boolean stepOut(); boolean pause(); boolean stop(); boolean exit(); boolean isSuspended(); boolean isDebugging(); boolean modifyRegValue(ValueTreeNode node, ArgType type, Object val); String getProcessName(); void setStateListener(StateListener l); interface StateListener { void onStateChanged(boolean suspended, boolean stopped); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/JDebuggerPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/JDebuggerPanel.java
package jadx.gui.ui.panel; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Label; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.StringUtils; import jadx.gui.device.debugger.DebugController; import jadx.gui.device.protocol.ADBDevice; import jadx.gui.treemodel.JClass; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.SmaliArea; import jadx.gui.ui.dialog.ADBDialog; import jadx.gui.ui.popupmenu.VarTreePopupMenu; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class JDebuggerPanel extends JPanel { private static final long serialVersionUID = -1111111202102181631L; private static final Logger LOG = LoggerFactory.getLogger(LogcatPanel.class); private static final ImageIcon ICON_RUN = UiUtils.openSvgIcon("debugger/execute"); private static final ImageIcon ICON_RERUN = UiUtils.openSvgIcon("debugger/rerun"); private static final ImageIcon ICON_PAUSE = UiUtils.openSvgIcon("debugger/threadFrozen"); private static final ImageIcon ICON_STOP = UiUtils.openSvgIcon("debugger/suspend"); private static final ImageIcon ICON_STOP_GRAY = UiUtils.openSvgIcon("debugger/suspendGray"); private static final ImageIcon ICON_STEP_INTO = UiUtils.openSvgIcon("debugger/traceInto"); private static final ImageIcon ICON_STEP_OVER = UiUtils.openSvgIcon("debugger/traceOver"); private static final ImageIcon ICON_STEP_OUT = UiUtils.openSvgIcon("debugger/stepOut"); private final transient MainWindow mainWindow; private final transient JList<IListElement> stackFrameList; private final transient JComboBox<IListElement> threadBox; private final transient JTextArea logger; private final transient JTree variableTree; private final transient DefaultTreeModel variableTreeModel; private final transient DefaultMutableTreeNode rootTreeNode; private final transient DefaultMutableTreeNode thisTreeNode; private final transient DefaultMutableTreeNode regTreeNode; private final transient JSplitPane rightSplitter; private final transient JSplitPane leftSplitter; private final transient IDebugController controller; private final LogcatPanel logcatPanel; private final transient VarTreePopupMenu varTreeMenu; private transient KeyEventDispatcher controllerShortCutDispatcher; public JDebuggerPanel(MainWindow mainWindow) { UiUtils.uiThreadGuard(); this.mainWindow = mainWindow; controller = new DebugController(); this.setLayout(new BorderLayout()); this.setMinimumSize(new Dimension(100, 150)); leftSplitter = new JSplitPane(); rightSplitter = new JSplitPane(); leftSplitter.setDividerLocation(mainWindow.getSettings().getDebuggerStackFrameSplitterLoc()); rightSplitter.setDividerLocation(mainWindow.getSettings().getDebuggerVarTreeSplitterLoc()); JPanel stackFramePanel = new JPanel(new BorderLayout()); threadBox = new JComboBox<>(); stackFrameList = new JList<>(); threadBox.setModel(new DefaultComboBoxModel<>()); stackFrameList.setModel(new DefaultListModel<>()); stackFramePanel.add(threadBox, BorderLayout.NORTH); stackFramePanel.add(new JScrollPane(stackFrameList), BorderLayout.CENTER); JPanel variablePanel = new JPanel(new CardLayout()); variableTree = new JTree(); variablePanel.add(new JScrollPane(variableTree)); rootTreeNode = new DefaultMutableTreeNode(); thisTreeNode = new DefaultMutableTreeNode("this"); regTreeNode = new DefaultMutableTreeNode("var"); rootTreeNode.add(thisTreeNode); rootTreeNode.add(regTreeNode); variableTreeModel = new DefaultTreeModel(rootTreeNode); variableTree.setModel(variableTreeModel); variableTree.expandPath(new TreePath(rootTreeNode.getPath())); variableTree.setCellRenderer(new DefaultTreeCellRenderer() { private static final long serialVersionUID = -1111111202103170725L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component c = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof ValueTreeNode) { if (((ValueTreeNode) value).isUpdated()) { setForeground(Color.RED); } } return c; } }); varTreeMenu = new VarTreePopupMenu(mainWindow); JTabbedPane loggerPanel = new JTabbedPane(); logger = new JTextArea(); logger.setEditable(false); logger.setLineWrap(true); JScrollPane loggerScroll = new JScrollPane(logger); loggerPanel.addTab("Debugger Log", null, loggerScroll, null); this.logcatPanel = new LogcatPanel(this); loggerPanel.addTab(NLS.str("logcat.logcat"), null, logcatPanel, null); leftSplitter.setLeftComponent(stackFramePanel); leftSplitter.setRightComponent(rightSplitter); leftSplitter.setResizeWeight(MainWindow.SPLIT_PANE_RESIZE_WEIGHT); rightSplitter.setLeftComponent(variablePanel); rightSplitter.setRightComponent(loggerPanel); rightSplitter.setResizeWeight(MainWindow.SPLIT_PANE_RESIZE_WEIGHT); JPanel headerPanel = new JPanel(new BorderLayout()); headerPanel.add(new Label(), BorderLayout.WEST); headerPanel.add(initToolBar(), BorderLayout.CENTER); JButton closeBtn = new JButton(UiUtils.openSvgIcon("ui/close")); closeBtn.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (controller.isDebugging()) { int what = JOptionPane.showConfirmDialog(mainWindow, NLS.str("debugger.cfm_dialog_msg"), NLS.str("debugger.cfm_dialog_title"), JOptionPane.OK_CANCEL_OPTION); if (what == JOptionPane.OK_OPTION) { controller.exit(); logcatPanel.exit(); } else { return; } } else { mainWindow.destroyDebuggerPanel(); } unregShortcuts(); } }); headerPanel.add(closeBtn, BorderLayout.EAST); this.add(headerPanel, BorderLayout.NORTH); this.add(leftSplitter, BorderLayout.CENTER); listenUIEvents(); } public MainWindow getMainWindow() { return mainWindow; } private void listenUIEvents() { stackFrameList.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() % 2 == 0) { stackFrameSelected(e.getPoint()); } } }); variableTree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { treeNodeRightClicked(e); } } }); } private JToolBar initToolBar() { AbstractAction stepOver = new AbstractAction(NLS.str("debugger.step_over"), ICON_STEP_OVER) { private static final long serialVersionUID = -1111111202103170726L; @Override public void actionPerformed(ActionEvent e) { controller.stepOver(); } }; stepOver.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.step_over")); AbstractAction stepInto = new AbstractAction(NLS.str("debugger.step_into"), ICON_STEP_INTO) { private static final long serialVersionUID = -1111111202103170727L; @Override public void actionPerformed(ActionEvent e) { controller.stepInto(); } }; stepInto.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.step_into")); AbstractAction stepOut = new AbstractAction(NLS.str("debugger.step_out"), ICON_STEP_OUT) { private static final long serialVersionUID = -1111111202103170728L; @Override public void actionPerformed(ActionEvent e) { controller.stepOut(); } }; stepOut.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.step_out")); AbstractAction stop = new AbstractAction(NLS.str("debugger.stop"), ICON_STOP_GRAY) { private static final long serialVersionUID = -1111111202103170728L; @Override public void actionPerformed(ActionEvent e) { controller.stop(); } }; stop.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.stop")); AbstractAction run = new AbstractAction(NLS.str("debugger.run"), ICON_RUN) { private static final long serialVersionUID = -1111111202103170728L; @Override public void actionPerformed(ActionEvent e) { if (controller.isDebugging()) { if (controller.isSuspended()) { controller.run(); } else { controller.pause(); } } } }; run.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.run")); AbstractAction rerun = new AbstractAction(NLS.str("debugger.rerun"), ICON_RERUN) { private static final long serialVersionUID = -1111111202103210433L; @Override public void actionPerformed(ActionEvent e) { if (controller.isDebugging()) { controller.stop(); } String pkgName = controller.getProcessName(); if (pkgName.isEmpty() || !ADBDialog.launchForDebugging(mainWindow, pkgName, true)) { (new ADBDialog(mainWindow)).setVisible(true); } } }; rerun.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.rerun")); controller.setStateListener(new DebugController.StateListener() { boolean isGray = true; @Override public void onStateChanged(boolean suspended, boolean stopped) { UiUtils.uiRun(() -> { if (!stopped) { if (isGray) { stop.putValue(Action.SMALL_ICON, ICON_STOP); } } else { stop.putValue(Action.SMALL_ICON, ICON_STOP_GRAY); run.putValue(Action.SMALL_ICON, ICON_RUN); run.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.run")); isGray = true; return; } if (suspended) { run.putValue(Action.SMALL_ICON, ICON_RUN); run.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.run")); } else { run.putValue(Action.SMALL_ICON, ICON_PAUSE); run.putValue(Action.SHORT_DESCRIPTION, NLS.str("debugger.pause")); } }); } }); JToolBar toolBar = new JToolBar(); toolBar.add(new Label()); toolBar.add(Box.createHorizontalGlue()); toolBar.add(rerun); toolBar.add(Box.createRigidArea(new Dimension(5, 0))); toolBar.add(stop); toolBar.add(Box.createRigidArea(new Dimension(5, 0))); toolBar.add(run); toolBar.add(Box.createRigidArea(new Dimension(5, 0))); toolBar.add(stepOver); toolBar.add(Box.createRigidArea(new Dimension(5, 0))); toolBar.add(stepInto); toolBar.add(Box.createRigidArea(new Dimension(5, 0))); toolBar.add(stepOut); toolBar.add(Box.createHorizontalGlue()); toolBar.add(new Label()); regShortcuts(); return toolBar; } private void unregShortcuts() { KeyboardFocusManager .getCurrentKeyboardFocusManager() .removeKeyEventDispatcher(controllerShortCutDispatcher); } private void regShortcuts() { controllerShortCutDispatcher = new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_PRESSED && mainWindow.getTabbedPane().getFocusedComp() instanceof SmaliArea) { if (e.getModifiersEx() == KeyEvent.SHIFT_DOWN_MASK && e.getKeyCode() == KeyEvent.VK_F8) { controller.stepOut(); return true; } switch (e.getKeyCode()) { case KeyEvent.VK_F7: controller.stepInto(); return true; case KeyEvent.VK_F8: controller.stepOver(); return true; case KeyEvent.VK_F9: controller.run(); return true; } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(controllerShortCutDispatcher); } private void treeNodeRightClicked(MouseEvent e) { TreePath path = variableTree.getPathForLocation(e.getX(), e.getY()); if (path != null) { Object node = path.getLastPathComponent(); if (node instanceof ValueTreeNode) { varTreeMenu.show((ValueTreeNode) node, e.getComponent(), e.getX(), e.getY()); } } } private void stackFrameSelected(Point p) { int loc = stackFrameList.locationToIndex(p); if (loc > -1) { IListElement ele = stackFrameList.getModel().getElementAt(loc); if (ele != null) { ele.onSelected(); } } } public boolean showDebugger(String procName, String host, int port, int androidVer, ADBDevice device, String pid) { boolean ok = controller.startDebugger(this, host, port, androidVer); if (ok) { UiUtils.uiRun(() -> { log(String.format("Attached %s %s:%d", procName, host, port)); try { logcatPanel.init(device, pid); } catch (Exception e) { log(NLS.str("logcat.error_fail_start")); LOG.error("Logcat failed to start", e); } leftSplitter.setDividerLocation(mainWindow.getSettings().getDebuggerStackFrameSplitterLoc()); rightSplitter.setDividerLocation(mainWindow.getSettings().getDebuggerVarTreeSplitterLoc()); mainWindow.showDebuggerPanel(); }); } return ok; } public IDebugController getDbgController() { return controller; } public int getLeftSplitterLocation() { return leftSplitter.getDividerLocation(); } public int getRightSplitterLocation() { return rightSplitter.getDividerLocation(); } public void loadSettings() { UiUtils.uiThreadGuard(); Font font = mainWindow.getSettings().getCodeFont(); variableTree.setFont(font.deriveFont(font.getSize() + 1.f)); variableTree.setRowHeight(-1); stackFrameList.setFont(font); threadBox.setFont(font); logger.setFont(font); } public void resetUI() { UiUtils.uiThreadGuard(); thisTreeNode.removeAllChildren(); regTreeNode.removeAllChildren(); clearFrameAndThreadList(); threadBox.updateUI(); stackFrameList.updateUI(); variableTreeModel.reload(rootTreeNode); variableTree.expandPath(new TreePath(rootTreeNode.getPath())); logger.setText(""); } public void scrollToSmaliLine(JClass cls, int pos, boolean debugMode) { SwingUtilities.invokeLater(() -> getMainWindow().getTabsController().smaliJump(cls, pos, debugMode)); } public void resetAllDebuggingInfo() { clearFrameAndThreadList(); resetRegTreeNodes(); resetThisTreeNodes(); } public void resetThisTreeNodes() { thisTreeNode.removeAllChildren(); SwingUtilities.invokeLater(() -> variableTreeModel.reload(thisTreeNode)); } public void resetRegTreeNodes() { regTreeNode.removeAllChildren(); SwingUtilities.invokeLater(() -> variableTreeModel.reload(regTreeNode)); } public void updateRegTreeNodes(List<? extends ValueTreeNode> nodes) { nodes.forEach(regTreeNode::add); } public void updateThisFieldNodes(List<? extends ValueTreeNode> nodes) { nodes.forEach(thisTreeNode::add); } public void refreshThreadBox(List<? extends IListElement> elements) { UiUtils.uiRun(() -> { if (!elements.isEmpty()) { DefaultComboBoxModel<IListElement> model = (DefaultComboBoxModel<IListElement>) threadBox.getModel(); elements.forEach(model::addElement); } threadBox.updateUI(); stackFrameList.setFont(mainWindow.getSettings().getCodeFont()); }); } public void refreshStackFrameList(List<? extends IListElement> elements) { if (elements.size() > 0) { DefaultListModel<IListElement> model = (DefaultListModel<IListElement>) stackFrameList.getModel(); elements.forEach(model::addElement); stackFrameList.setFont(mainWindow.getSettings().getCodeFont()); } SwingUtilities.invokeLater(stackFrameList::repaint); } public void refreshRegisterTree() { SwingUtilities.invokeLater(() -> { variableTreeModel.reload(regTreeNode); variableTree.expandPath(new TreePath(regTreeNode.getPath())); }); } public void refreshThisFieldTree() { SwingUtilities.invokeLater(() -> { boolean expanded = variableTree.isExpanded(new TreePath(thisTreeNode.getPath())); variableTreeModel.reload(thisTreeNode); if (expanded) { variableTree.expandPath(new TreePath(regTreeNode.getPath())); } }); } public void clearFrameAndThreadList() { ((DefaultListModel<IListElement>) stackFrameList.getModel()).removeAllElements(); ((DefaultComboBoxModel<IListElement>) threadBox.getModel()).removeAllElements(); } public void log(String msg) { StringBuilder sb = new StringBuilder(); sb.append(" > ") .append(StringUtils.getDateText()) .append(" ") .append(msg) .append("\n"); SwingUtilities.invokeLater(() -> { logger.append(sb.toString()); }); } public void updateRegTree(ValueTreeNode node) { SwingUtilities.invokeLater(() -> { variableTreeModel.reload(regTreeNode); scrollToUpdatedNode(node); }); } public void updateThisTree(ValueTreeNode node) { SwingUtilities.invokeLater(() -> { variableTreeModel.reload(thisTreeNode); scrollToUpdatedNode(node); }); } public void scrollToUpdatedNode(ValueTreeNode node) { SwingUtilities.invokeLater(() -> { TreeNode[] path = node.getPath(); variableTree.scrollPathToVisible(new TreePath(path)); }); } public abstract static class ValueTreeNode extends DefaultMutableTreeNode { private static final long serialVersionUID = -1111111202103122236L; private boolean updated; public void setUpdated(boolean updated) { this.updated = updated; } public boolean isUpdated() { return updated; } public abstract String getName(); @Nullable public abstract String getValue(); @Nullable public abstract String getType(); public abstract long getTypeID(); public abstract ValueTreeNode updateValue(String val); public abstract ValueTreeNode updateType(String val); public abstract ValueTreeNode updateTypeID(long id); @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getName()); String val = getValue(); if (val != null) { sb.append(" val: ").append(val).append(","); } String type = getType(); if (type != null) { sb.append(" type: ").append(getType()); long id = getTypeID(); if (id > 0) { sb.append("@").append(id); } } if (val == null && type == null) { sb.append(" undefined"); } return sb.toString(); } } public interface IListElement { void onSelected(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/LogcatPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/LogcatPanel.java
package jadx.gui.ui.panel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoundedRangeModel; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.JToolBar; import javax.swing.ListCellRenderer; import javax.swing.text.AttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.device.debugger.LogcatController; import jadx.gui.device.protocol.ADB; import jadx.gui.device.protocol.ADBDevice; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.NodeLabel; public class LogcatPanel extends JPanel { private static final Logger LOG = LoggerFactory.getLogger(LogcatPanel.class); StyleContext sc = StyleContext.getDefaultStyleContext(); private final AttributeSet defaultAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#6c71c4")); private final AttributeSet verboseAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#2aa198")); private final AttributeSet debugAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#859900")); private final AttributeSet infoAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#586e75")); private final AttributeSet warningAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#b58900")); private final AttributeSet errorAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#dc322f")); private final AttributeSet fatalAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#d33682")); private final AttributeSet silentAset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.decode("#002b36")); private static final ImageIcon ICON_PAUSE = UiUtils.openSvgIcon("debugger/threadFrozen"); private static final ImageIcon ICON_RUN = UiUtils.openSvgIcon("debugger/execute"); private static final ImageIcon CLEAR_LOGCAT = UiUtils.openSvgIcon("debugger/trash"); private transient JTextPane logcatPane; private final transient JDebuggerPanel debugPanel; private LogcatController logcatController; private boolean ready = false; private List<ADB.Process> procs; public LogcatPanel(JDebuggerPanel debugPanel) { this.debugPanel = debugPanel; } private List<Integer> pids; private JScrollPane logcatScroll; private int pid; private final AbstractAction pauseButton = new AbstractAction(NLS.str("logcat.pause"), ICON_PAUSE) { @Override public void actionPerformed(ActionEvent e) { toggleLogcat(); } }; private final AbstractAction clearButton = new AbstractAction(NLS.str("logcat.clear"), CLEAR_LOGCAT) { @Override public void actionPerformed(ActionEvent e) { clearLogcat(); } }; public boolean showLogcat() { this.removeAll(); List<String> pkgs = new ArrayList<>(); pids = new ArrayList<>(); JPanel procBox; for (ADB.Process proc : procs.subList(1, procs.size())) { // skipping first element because it contains the column label pkgs.add(String.format("[pid: %-6s] %s", proc.pid, proc.name)); pids.add(Integer.valueOf(proc.pid)); } String[] msgTypes = { NLS.str("logcat.default"), NLS.str("logcat.verbose"), NLS.str("logcat.debug"), NLS.str("logcat.info"), NLS.str("logcat.warn"), NLS.str("logcat.error"), NLS.str("logcat.fatal"), NLS.str("logcat.silent") }; Integer[] msgIndex = { 1, 2, 3, 4, 5, 6, 7, 8 }; this.setLayout(new BorderLayout()); logcatPane = new JTextPane(); logcatPane.setEditable(false); logcatScroll = new JScrollPane(logcatPane); JToolBar menuPanel = new JToolBar(); CheckCombo procObj = new CheckCombo(NLS.str("logcat.process"), 1, pids.toArray(new Integer[0]), pkgs.toArray(new String[0])); procBox = procObj.getContent(); procObj.selectAllBut(this.pids.indexOf(this.pid)); JPanel msgTypeBox = new CheckCombo(NLS.str("logcat.level"), 2, msgIndex, msgTypes).getContent(); menuPanel.add(procBox); menuPanel.add(Box.createRigidArea(new Dimension(5, 0))); menuPanel.add(msgTypeBox); menuPanel.add(Box.createRigidArea(new Dimension(5, 0))); menuPanel.add(pauseButton); menuPanel.add(Box.createRigidArea(new Dimension(5, 0))); menuPanel.add(clearButton); this.add(menuPanel, BorderLayout.NORTH); this.add(logcatScroll, BorderLayout.CENTER); return true; } public boolean clearLogcatArea() { logcatPane.setText(""); return true; } public boolean init(ADBDevice device, String pid) { this.pid = Integer.parseInt(pid); try { this.logcatController = new LogcatController(this, device); this.procs = device.getProcessList(); if (!this.showLogcat()) { debugPanel.log(NLS.str("logcat.error_fail_start")); } } catch (Exception e) { this.ready = false; LOG.error("Failed to start logcat", e); return false; } this.ready = true; return true; } private void toggleLogcat() { if (Objects.equals(this.logcatController.getStatus(), "running")) { this.logcatController.stopLogcat(); this.pauseButton.putValue(Action.SMALL_ICON, ICON_RUN); this.pauseButton.putValue(Action.NAME, NLS.str("logcat.start")); } else if (Objects.equals(this.logcatController.getStatus(), "stopped")) { this.logcatController.startLogcat(); this.pauseButton.putValue(Action.SMALL_ICON, ICON_PAUSE); this.pauseButton.putValue(Action.NAME, NLS.str("logcat.pause")); } } private void clearLogcat() { boolean running = false; if (Objects.equals(this.logcatController.getStatus(), "running")) { this.logcatController.stopLogcat(); running = true; } this.logcatController.clearLogcat(); clearLogcatArea(); this.debugPanel.log(this.logcatController.getStatus()); if (running) { this.logcatController.startLogcat(); } } public boolean isReady() { return this.ready; } private boolean isAtBottom(JScrollBar scrollbar) { BoundedRangeModel model = scrollbar.getModel(); return (model.getExtent() + model.getValue()) == model.getMaximum(); } public void log(LogcatController.LogcatInfo logcatInfo) { boolean atBottom = false; int len = logcatPane.getDocument().getLength(); JScrollBar scrollbar = logcatScroll.getVerticalScrollBar(); if (isAtBottom(scrollbar)) { atBottom = true; } StringBuilder sb = new StringBuilder(); sb.append(" > ") .append(logcatInfo.getTimestamp()) .append(" [pid: ") .append(logcatInfo.getPid()) .append("] ") .append(logcatInfo.getMsgTypeString()) .append(": ") .append(logcatInfo.getMsg()) .append("\n"); try { switch (logcatInfo.getMsgType()) { case 0: // Unknown break; case 1: // Default logcatPane.getDocument().insertString(len, sb.toString(), defaultAset); break; case 2: // Verbose logcatPane.getDocument().insertString(len, sb.toString(), verboseAset); break; case 3: // Debug logcatPane.getDocument().insertString(len, sb.toString(), debugAset); break; case 4: // Info logcatPane.getDocument().insertString(len, sb.toString(), infoAset); break; case 5: // Warn logcatPane.getDocument().insertString(len, sb.toString(), warningAset); break; case 6: // Error logcatPane.getDocument().insertString(len, sb.toString(), errorAset); break; case 7: // Fatal logcatPane.getDocument().insertString(len, sb.toString(), fatalAset); break; case 8: // Silent logcatPane.getDocument().insertString(len, sb.toString(), silentAset); break; default: logcatPane.getDocument().insertString(len, sb.toString(), null); break; } } catch (Exception e) { LOG.error("Failed to write logcat message", e); } if (atBottom) { EventQueue.invokeLater(() -> scrollbar.setValue(scrollbar.getMaximum())); } } public void exit() { logcatController.exit(); clearLogcatArea(); this.logcatController.clearEvents(); } class CheckCombo implements ActionListener { private final String[] ids; private final int type; private final String label; private final Integer[] index; private JComboBox<CheckComboStore> combo; public CheckCombo(String label, int type, Integer[] index, String[] ids) { this.ids = ids; this.type = type; this.label = label; this.index = index; } public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); CheckComboStore store = (CheckComboStore) cb.getSelectedItem(); CheckComboRenderer ccr = (CheckComboRenderer) cb.getRenderer(); store.state = !store.state; ccr.checkBox.setSelected(store.state); switch (this.type) { case 1: // process logcatController.getFilter().togglePid(store.index, store.state); logcatController.reload(); break; case 2: // label logcatController.getFilter().toggleMsgType((byte) store.index, store.state); logcatController.reload(); break; default: LOG.error("Invalid Logcat Filter Type"); break; } } public JPanel getContent() { JLabel label = NodeLabel.noHtml(this.label + ": "); CheckComboStore[] stores = new CheckComboStore[ids.length]; for (int j = 0; j < ids.length; j++) { stores[j] = new CheckComboStore(index[j], ids[j], Boolean.TRUE); } combo = new JComboBox<>(stores); combo.setRenderer(new CheckComboRenderer()); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.weightx = 0; c.gridwidth = 1; c.insets = new Insets(0, 1, 0, 1); panel.add(label, c); c.weightx = 1; c.gridwidth = GridBagConstraints.REMAINDER; c.anchor = GridBagConstraints.WEST; c.insets = new Insets(0, 1, 0, 1); panel.add(combo, c); combo.addActionListener(this); combo.addMouseListener(new FilterClickListener(this)); return panel; } public void toggleAll(boolean checked) { for (int i = 0; i < combo.getItemCount(); i++) { CheckComboStore ccs = combo.getItemAt(i); ccs.state = checked; switch (type) { case 1: // process logcatController.getFilter().togglePid(ccs.index, checked); break; case 2: // level logcatController.getFilter().toggleMsgType((byte) ccs.index, checked); break; default: LOG.error("Invalid Logcat Toggle Filter Encountered"); break; } } logcatController.reload(); } public void selectAllBut(int ind) { for (int i = 0; i < combo.getItemCount(); i++) { CheckComboStore ccs = combo.getItemAt(i); if (i != ind) { ccs.state = false; } else { ccs.state = true; } switch (type) { case 1: // process logcatController.getFilter().togglePid(ccs.index, ccs.state); break; case 2: // level logcatController.getFilter().toggleMsgType((byte) ccs.index, ccs.state); break; default: LOG.error("Invalid Logcat selectAllBut filter encountered"); break; } } logcatController.reload(); } } private static class CheckComboRenderer implements ListCellRenderer { private final JCheckBox checkBox = new JCheckBox(); public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { CheckComboStore store = (CheckComboStore) value; checkBox.setText(store.id); checkBox.setSelected(store.state); return checkBox; } } static class CheckComboStore { String id; Boolean state; int index; public CheckComboStore(int index, String id, Boolean state) { this.id = id; this.state = state; this.index = index; } } class FilterClickListener extends MouseAdapter { CheckCombo combo; public FilterClickListener(CheckCombo combo) { this.combo = combo; } public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { doPop(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { doPop(e); } } private void doPop(MouseEvent e) { FilterPopup menu = new FilterPopup(combo); menu.show(e.getComponent(), e.getX(), e.getY()); } } class FilterPopup extends JPopupMenu { CheckCombo combo; JMenuItem selectAll; JMenuItem unselectAll; JMenuItem selectAttached; public FilterPopup(CheckCombo combo) { this.combo = combo; selectAll = new JMenuItem(NLS.str("logcat.select_all")); selectAll.addActionListener(actionEvent -> combo.toggleAll(true)); unselectAll = new JMenuItem(NLS.str("logcat.unselect_all")); unselectAll.addActionListener(actionEvent -> combo.toggleAll(false)); if (combo.type == 1) { selectAttached = new JMenuItem(NLS.str("logcat.select_attached")); selectAttached.addActionListener(actionEvent -> combo.selectAllBut(pids.indexOf(pid))); add(selectAttached); } add(selectAll); add(unselectAll); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/SimpleCodePanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/SimpleCodePanel.java
package jadx.gui.ui.panel; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rtextarea.RTextScrollPane; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.LineNumbersMode; import jadx.gui.treemodel.CodeNode; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.utils.NLS; // The code panel class is used to display the code of the selected node. public class SimpleCodePanel extends JPanel { private static final long serialVersionUID = -4073178549744330905L; private static final Logger LOG = LoggerFactory.getLogger(SimpleCodePanel.class); private final RSyntaxTextArea codeArea; private final RTextScrollPane codeScrollPane; private final JLabel titleLabel; public SimpleCodePanel(MainWindow mainWindow) { JadxSettings settings = mainWindow.getSettings(); setLayout(new BorderLayout(5, 5)); setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); // Set the minimum size to ensure the panel is not completely minimized setMinimumSize(new Dimension(300, 400)); setPreferredSize(new Dimension(800, 600)); // The title label titleLabel = new JLabel(NLS.str("usage_dialog_plus.code_view")); titleLabel.setFont(settings.getCodeFont()); titleLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 10, 5)); // The code area codeArea = AbstractCodeArea.getDefaultArea(mainWindow); codeArea.setText("// " + NLS.str("usage_dialog_plus.select_node")); codeScrollPane = new RTextScrollPane(codeArea); codeScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); codeScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); add(titleLabel, BorderLayout.NORTH); add(codeScrollPane, BorderLayout.CENTER); applySettings(settings); } private void applySettings(JadxSettings settings) { codeScrollPane.setLineNumbersEnabled(settings.getLineNumbersMode() != LineNumbersMode.DISABLE); codeScrollPane.getGutter().setLineNumberFont(settings.getCodeFont()); codeArea.setFont(settings.getCodeFont()); } public void showCode(JNode node, String codeLine) { if (node != null) { titleLabel.setText(NLS.str("usage_dialog_plus.code_for", node.makeLongString())); codeArea.setSyntaxEditingStyle(node.getSyntaxName()); // Get the complete code String contextCode = getContextCode(node, codeLine); codeArea.setText(contextCode); // Highlight the key line and scroll to that position scrollToCodeLine(codeArea, codeLine); // If it is a CodeNode, we can get a more precise position if (node instanceof CodeNode) { CodeNode codeNode = (CodeNode) node; int pos = codeNode.getPos(); if (pos > 0) { // Try to use the position information to more accurately locate try { String text = codeArea.getText(); int lineNum = 0; int curPos = 0; // Calculate the line number corresponding to the position for (int i = 0; i < text.length() && curPos <= pos; i++) { if (text.charAt(i) == '\n') { lineNum++; } curPos++; } if (lineNum > 0) { // Scroll to the calculated line number int finalLineNum = lineNum; SwingUtilities.invokeLater(() -> { try { Rectangle2D lineRect = codeArea .modelToView2D(codeArea.getLineStartOffset(finalLineNum)); if (lineRect != null) { JScrollPane scrollPane = (JScrollPane) codeArea.getParent().getParent(); Rectangle viewRect = scrollPane.getViewport().getViewRect(); int y = (int) (lineRect.getY() - (viewRect.height - lineRect.getHeight()) / 2); if (y < 0) { y = 0; } scrollPane.getViewport().setViewPosition(new Point(0, y)); } } catch (Exception e) { // Fall back to using string matching scrollToCodeLine(codeArea, codeLine); } }); } } catch (Exception e) { // Fall back to using string matching scrollToCodeLine(codeArea, codeLine); } } else { // If there is no position information, use string matching scrollToCodeLine(codeArea, codeLine); } } else { // Not a CodeNode, use string matching scrollToCodeLine(codeArea, codeLine); } } else { titleLabel.setText(NLS.str("usage_dialog_plus.code_view")); codeArea.setText("// " + NLS.str("usage_dialog_plus.select_node")); } } private String getContextCode(JNode node, String codeLine) { // Always try to get the complete code if (node instanceof CodeNode) { CodeNode codeNode = (CodeNode) node; JNode usageJNode = codeNode.getJParent(); if (usageJNode != null) { // Try to get the complete code of the method or class String fullCode = getFullNodeCode(usageJNode); if (fullCode != null && !fullCode.isEmpty()) { return fullCode; } } } // If you cannot get more context, at least add some empty lines and comments return "// Unable to get complete context, only display related lines\n\n" + codeLine; } private String getFullNodeCode(JNode node) { if (node != null) { // Get the code information of the node ICodeInfo codeInfo = node.getCodeInfo(); if (codeInfo != null && !codeInfo.equals(ICodeInfo.EMPTY)) { return codeInfo.getCodeStr(); } // If it is a class node, try to get the class code if (node instanceof JClass) { JClass jClass = (JClass) node; return jClass.getCodeInfo().getCodeStr(); } } return null; } private void scrollToCodeLine(RSyntaxTextArea textArea, String lineToHighlight) { // Try to find and highlight a specific line in the code and scroll to that position try { String fullText = textArea.getText(); int lineIndex = fullText.indexOf(lineToHighlight); if (lineIndex >= 0) { // Ensure the text area has updated the layout textArea.revalidate(); // Highlight the code line textArea.setCaretPosition(lineIndex); int endIndex = lineIndex + lineToHighlight.length(); textArea.select(lineIndex, endIndex); textArea.getCaret().setSelectionVisible(true); // Use SwingUtilities.invokeLater to ensure the scroll is executed after the UI is updated SwingUtilities.invokeLater(() -> { try { // Get the line number int lineNum = textArea.getLineOfOffset(lineIndex); // Ensure the line is centered in the view Rectangle2D lineRect = textArea.modelToView2D(textArea.getLineStartOffset(lineNum)); if (lineRect != null) { // Calculate the center point of the view JScrollPane scrollPane = (JScrollPane) textArea.getParent().getParent(); Rectangle viewRect = scrollPane.getViewport().getViewRect(); int y = (int) (lineRect.getY() - (viewRect.height - lineRect.getHeight()) / 2); if (y < 0) { y = 0; } // Scroll to the calculated position scrollPane.getViewport().setViewPosition(new Point(0, y)); } } catch (Exception e) { LOG.debug("Error scrolling to line: {}", e.getMessage()); } }); } else { LOG.debug("Could not find line to highlight: {}", lineToHighlight); } } catch (Exception e) { LOG.debug("Error highlighting line: {}", e.getMessage()); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/ContentPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/ContentPanel.java
package jadx.gui.ui.panel; import javax.swing.JPanel; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.settings.JadxSettings; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.ui.tab.TabsController; public abstract class ContentPanel extends JPanel { private static final Logger LOG = LoggerFactory.getLogger(ContentPanel.class); private static final long serialVersionUID = 3237031760631677822L; protected TabbedPane tabbedPane; protected JNode node; protected ContentPanel(TabbedPane panel, JNode node) { tabbedPane = panel; this.node = node; } public abstract void loadSettings(); public TabbedPane getTabbedPane() { return tabbedPane; } public TabsController getTabsController() { return tabbedPane.getTabsController(); } public MainWindow getMainWindow() { return tabbedPane.getMainWindow(); } public JNode getNode() { return node; } public void scrollToPos(int pos) { LOG.warn("ContentPanel.scrollToPos method not implemented, class: {}", getClass().getSimpleName()); } /** * Allows to show a tool tip on the tab e.g. for displaying a long path of the * selected entry inside the APK file. * <p> * If <code>null</code> is returned no tool tip will be displayed. */ @Nullable public String getTabTooltip() { JClass jClass = getNode().getRootClass(); if (jClass != null) { return jClass.getFullName(); } return getNode().getName(); } public JadxSettings getSettings() { return tabbedPane.getMainWindow().getSettings(); } public boolean supportsQuickTabs() { return getNode().supportsQuickTabs(); } public void dispose() { tabbedPane = null; node = null; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/ImagePanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/ImagePanel.java
package jadx.gui.ui.panel; import java.awt.BorderLayout; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import javax.imageio.ImageIO; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import hu.kazocsaba.imageviewer.ImageViewer; import jadx.api.ResourceFile; import jadx.api.ResourcesLoader; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.xmlgen.ResContainer; import jadx.gui.treemodel.JResource; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.tab.TabbedPane; public class ImagePanel extends ContentPanel { private static final long serialVersionUID = 4071356367073142688L; public ImagePanel(TabbedPane panel, JResource res) { super(panel, res); setLayout(new BorderLayout()); try { BufferedImage img = loadImage(res); ImageViewer imageViewer = new ImageViewer(img); add(imageViewer.getComponent()); } catch (Exception e) { RSyntaxTextArea textArea = AbstractCodeArea.getDefaultArea(panel.getMainWindow()); textArea.setText("Image load error:\n" + Utils.getStackTrace(e)); add(textArea); } } private BufferedImage loadImage(JResource res) { ResourceFile resFile = res.getResFile(); ResContainer resContainer = resFile.loadContent(); ResContainer.DataType dataType = resContainer.getDataType(); if (dataType == ResContainer.DataType.DECODED_DATA) { try { return ImageIO.read(new ByteArrayInputStream(resContainer.getDecodedData())); } catch (Exception e) { throw new JadxRuntimeException("Failed to load image", e); } } else if (dataType == ResContainer.DataType.RES_LINK) { try { return ResourcesLoader.decodeStream(resFile, (size, is) -> ImageIO.read(is)); } catch (Exception e) { throw new JadxRuntimeException("Failed to load image", e); } } else { throw new JadxRuntimeException("Unsupported resource image data type: " + resFile); } } @Override public void loadSettings() { // no op } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/HtmlPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/HtmlPanel.java
package jadx.gui.ui.panel; import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JEditorPane; import javax.swing.JScrollPane; import jadx.gui.settings.JadxSettings; import jadx.gui.treemodel.JNode; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.ui.ZoomActions; public final class HtmlPanel extends ContentPanel { private static final long serialVersionUID = -6251262855835426245L; private final JHtmlPane textArea; public HtmlPanel(TabbedPane panel, JNode jnode) { super(panel, jnode); setLayout(new BorderLayout()); textArea = new JHtmlPane(); loadSettings(); loadContent(jnode); textArea.setEditable(false); JScrollPane sp = new JScrollPane(textArea); add(sp); ZoomActions.register(textArea, panel.getMainWindow().getSettings(), this::loadSettings); } @Override public void loadSettings() { JadxSettings settings = getMainWindow().getSettings(); textArea.setFont(settings.getUiFont()); } public void loadContent(JNode jnode) { textArea.setText(jnode.getCodeInfo().getCodeStr()); textArea.setCaretPosition(0); // otherwise the start view will be the last line } public JEditorPane getHtmlArea() { return textArea; } private static final class JHtmlPane extends JEditorPane { private static final long serialVersionUID = 6886040384052136157L; public JHtmlPane() { setContentType("text/html"); } @Override public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); try { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paint(g2d); } finally { g2d.dispose(); } } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/FontPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/FontPanel.java
package jadx.gui.ui.panel; import java.awt.BorderLayout; import java.awt.Font; import java.awt.FontFormatException; import java.io.ByteArrayInputStream; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import jadx.api.ResourceFile; import jadx.api.ResourcesLoader; import jadx.core.utils.Utils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.core.xmlgen.ResContainer; import jadx.gui.treemodel.JResource; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.NLS; public class FontPanel extends ContentPanel { private static final long serialVersionUID = 695370628262996993L; private static final String DEFAULT_PREVIEW_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" + "abcdefghijklmnopqrstuvwxyz\n" + "1234567890!@#$%^&*()_-=+[]{}<,.>"; public FontPanel(TabbedPane panel, JResource res) { super(panel, res); setLayout(new BorderLayout()); RSyntaxTextArea textArea = AbstractCodeArea.getDefaultArea(panel.getMainWindow()); add(textArea, BorderLayout.CENTER); try { Font selectedFont = loadFont(res); if (selectedFont.canDisplay(DEFAULT_PREVIEW_STRING.codePointAt(0))) { textArea.setFont(selectedFont); textArea.setText(DEFAULT_PREVIEW_STRING); } else { textArea.setText(NLS.str("message.unable_preview_font")); } } catch (Exception e) { textArea.setText("Font load error:\n" + Utils.getStackTrace(e)); } } private Font loadFont(JResource res) { ResourceFile resFile = res.getResFile(); ResContainer resContainer = resFile.loadContent(); ResContainer.DataType dataType = resContainer.getDataType(); if (dataType == ResContainer.DataType.DECODED_DATA) { try { return Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(resContainer.getDecodedData())).deriveFont(12f); } catch (Exception e) { throw new JadxRuntimeException("Failed to load font", e); } } else if (dataType == ResContainer.DataType.RES_LINK) { try { return ResourcesLoader.decodeStream(resFile, (size, is) -> { try { return Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(12f); } catch (FontFormatException e) { throw new JadxRuntimeException("Failed to load font", e); } }); } catch (Exception e) { throw new JadxRuntimeException("Failed to load font", e); } } else { throw new JadxRuntimeException("Unsupported resource font data type: " + resFile); } } @Override public void loadSettings() { // no op } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/panel/UndisplayedStringsPanel.java
jadx-gui/src/main/java/jadx/gui/ui/panel/UndisplayedStringsPanel.java
package jadx.gui.ui.panel; import java.awt.BorderLayout; import java.awt.Font; import javax.swing.BorderFactory; import org.drjekyll.fontchooser.FontChooser; import org.drjekyll.fontchooser.model.FontSelectionModel; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rtextarea.RTextScrollPane; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.LineNumbersMode; import jadx.gui.settings.ui.font.FontChooserHack; import jadx.gui.ui.codearea.AbstractCodeArea; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.ui.treenodes.UndisplayedStringsNode; public class UndisplayedStringsPanel extends ContentPanel { private static final long serialVersionUID = 695370628262996993L; private final RSyntaxTextArea textPane; private final RTextScrollPane codeScrollPane; public UndisplayedStringsPanel(TabbedPane panel, UndisplayedStringsNode node) { super(panel, node); setLayout(new BorderLayout()); textPane = AbstractCodeArea.getDefaultArea(panel.getMainWindow()); JadxSettings settings = getSettings(); Font selectedFont = settings.getCodeFont(); FontChooser fontChooser = new FontChooser(); fontChooser.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); fontChooser.setSelectedFont(selectedFont); FontChooserHack.hidePreview(fontChooser); fontChooser.addChangeListener(event -> { FontSelectionModel model = (FontSelectionModel) event.getSource(); settings.setCodeFont(model.getSelectedFont()); getMainWindow().loadSettings(); }); codeScrollPane = new RTextScrollPane(textPane); add(codeScrollPane, BorderLayout.CENTER); add(fontChooser, BorderLayout.EAST); applySettings(); showData(node.makeDescString()); } private void applySettings() { codeScrollPane.setLineNumbersEnabled(getSettings().getLineNumbersMode() != LineNumbersMode.DISABLE); codeScrollPane.getGutter().setLineNumberFont(getSettings().getCodeFont()); textPane.setFont(getSettings().getCodeFont()); } private void showData(String data) { textPane.setText(data); textPane.setCaretPosition(0); } @Override public void loadSettings() { applySettings(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/cellrenders/MethodsListRenderer.java
jadx-gui/src/main/java/jadx/gui/ui/cellrenders/MethodsListRenderer.java
package jadx.gui.ui.cellrenders; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListCellRenderer; import jadx.api.JavaMethod; import jadx.gui.utils.UiUtils; public class MethodsListRenderer extends JPanel implements ListCellRenderer<JavaMethod> { private final JCheckBox checkBox; private final JLabel label; public MethodsListRenderer() { setLayout(new BorderLayout(5, 0)); checkBox = new JCheckBox(); label = new JLabel(); setBorder(BorderFactory.createEmptyBorder(1, 5, 1, 5)); add(checkBox, BorderLayout.WEST); add(label, BorderLayout.CENTER); setOpaque(true); checkBox.setOpaque(false); label.setOpaque(false); } @Override public Component getListCellRendererComponent(JList<? extends JavaMethod> list, JavaMethod value, int index, boolean isSelected, boolean cellHasFocus) { label.setText(UiUtils.typeFormatHtml(MethodRenderHelper.makeBaseString(value), value.getReturnType())); label.setIcon(MethodRenderHelper.getIcon(value)); checkBox.setSelected(isSelected); setBackground(isSelected ? list.getSelectionBackground() : list.getBackground()); setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); label.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground()); return this; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/cellrenders/MethodRenderHelper.java
jadx-gui/src/main/java/jadx/gui/ui/cellrenders/MethodRenderHelper.java
package jadx.gui.ui.cellrenders; import java.util.Iterator; import javax.swing.Icon; import javax.swing.ImageIcon; import jadx.api.JavaMethod; import jadx.core.dex.info.AccessInfo; import jadx.core.dex.instructions.args.ArgType; import jadx.gui.utils.Icons; import jadx.gui.utils.OverlayIcon; import jadx.gui.utils.UiUtils; public class MethodRenderHelper { private static final ImageIcon ICON_METHOD_ABSTRACT = UiUtils.openSvgIcon("nodes/abstractMethod"); private static final ImageIcon ICON_METHOD_PRIVATE = UiUtils.openSvgIcon("nodes/privateMethod"); private static final ImageIcon ICON_METHOD_PROTECTED = UiUtils.openSvgIcon("nodes/protectedMethod"); private static final ImageIcon ICON_METHOD_PUBLIC = UiUtils.openSvgIcon("nodes/publicMethod"); private static final ImageIcon ICON_METHOD_CONSTRUCTOR = UiUtils.openSvgIcon("nodes/constructorMethod"); private static final ImageIcon ICON_METHOD_SYNC = UiUtils.openSvgIcon("nodes/methodReference"); public static Icon getIcon(JavaMethod mth) { AccessInfo accessFlags = mth.getAccessFlags(); Icon icon = Icons.METHOD; if (accessFlags.isAbstract()) { icon = ICON_METHOD_ABSTRACT; } if (accessFlags.isConstructor()) { icon = ICON_METHOD_CONSTRUCTOR; } if (accessFlags.isPublic()) { icon = ICON_METHOD_PUBLIC; } if (accessFlags.isPrivate()) { icon = ICON_METHOD_PRIVATE; } if (accessFlags.isProtected()) { icon = ICON_METHOD_PROTECTED; } if (accessFlags.isSynchronized()) { icon = ICON_METHOD_SYNC; } OverlayIcon overIcon = new OverlayIcon(icon); if (accessFlags.isFinal()) { overIcon.add(Icons.FINAL); } if (accessFlags.isStatic()) { overIcon.add(Icons.STATIC); } return overIcon; } public static String makeBaseString(JavaMethod mth) { if (mth.isClassInit()) { return "{...}"; } StringBuilder base = new StringBuilder(); if (mth.isConstructor()) { base.append(mth.getDeclaringClass().getName()); } else { base.append(mth.getName()); } base.append('('); for (Iterator<ArgType> it = mth.getArguments().iterator(); it.hasNext();) { base.append(UiUtils.typeStr(it.next())); if (it.hasNext()) { base.append(", "); } } base.append(')'); return base.toString(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/cellrenders/PathHighlightTreeCellRenderer.java
jadx-gui/src/main/java/jadx/gui/ui/cellrenders/PathHighlightTreeCellRenderer.java
package jadx.gui.ui.cellrenders; import java.awt.Color; import java.awt.Component; import javax.swing.BorderFactory; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import jadx.gui.treemodel.JNode; import jadx.gui.utils.UiUtils; public class PathHighlightTreeCellRenderer extends DefaultTreeCellRenderer { private final boolean isDarkTheme; public PathHighlightTreeCellRenderer() { super(); Color themeBackground = UIManager.getColor("Panel.background"); isDarkTheme = UiUtils.isDarkTheme(themeBackground); } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component comp = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; Object userObject = node.getUserObject(); // Calculate the node level int level = node.getLevel(); // Set different colors according to the level float hue = (level * 0.1f) % 1.0f; // Hue cycle Color levelColor = Color.getHSBColor(hue, 0.1f, 0.95f); // Check if it is on the selected path boolean onSelectionPath = false; TreePath selectionPath = tree.getSelectionPath(); if (selectionPath != null) { // Check if the current node is on the selected path (whether it is part of the selected path) Object[] selectedPathNodes = selectionPath.getPath(); for (Object pathNode : selectedPathNodes) { if (pathNode == node) { onSelectionPath = true; break; } } } if (onSelectionPath && !selected) { // If it is on the selected path but not the selected node, use a special foreground setForeground(isDarkTheme ? Color.decode("#70AEFF") : Color.decode("#0033B3")); } else if (!selected) { // Only apply the background color when it is not selected setBackground(levelColor); // Normal border setBorder(BorderFactory.createEmptyBorder(2, level * 2 + 1, 2, 1)); } else { // The selected node also adds a border setBorder(BorderFactory.createEmptyBorder(2, level * 2 + 1, 2, 1)); } if (userObject instanceof JNode) { JNode jNode = (JNode) userObject; setText(jNode.makeLongString()); setIcon(jNode.getIcon()); setToolTipText(jNode.getTooltip()); } return comp; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/CodeContentPanel.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/CodeContentPanel.java
package jadx.gui.ui.codearea; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Point; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.gui.treemodel.JNode; import jadx.gui.ui.panel.IViewStateSupport; import jadx.gui.ui.tab.TabbedPane; public final class CodeContentPanel extends AbstractCodeContentPanel implements IViewStateSupport { private static final long serialVersionUID = 5310536092010045565L; private static final Logger LOG = LoggerFactory.getLogger(CodeContentPanel.class); private final CodePanel codePanel; public CodeContentPanel(TabbedPane panel, JNode jnode) { super(panel, jnode); setLayout(new BorderLayout()); codePanel = new CodePanel(new CodeArea(this, jnode)); add(codePanel, BorderLayout.CENTER); codePanel.load(); } @Override public void loadSettings() { codePanel.loadSettings(); updateUI(); } SearchBar getSearchBar() { return codePanel.getSearchBar(); } @Override public AbstractCodeArea getCodeArea() { return codePanel.getCodeArea(); } @Override public Component getChildrenComponent() { return getCodeArea(); } @Override public String getTabTooltip() { String s = node.getName(); JNode n = (JNode) node.getParent(); while (n != null) { String name = n.getName(); if (name == null) { break; } s = name + '/' + s; n = (JNode) n.getParent(); } return '/' + s; } @Override public void saveEditorViewState(EditorViewState viewState) { int caretPos = codePanel.getCodeArea().getCaretPosition(); Point viewPoint = codePanel.getCodeScrollPane().getViewport().getViewPosition(); viewState.setCaretPos(caretPos); viewState.setViewPoint(viewPoint); } @Override public void restoreEditorViewState(EditorViewState viewState) { try { codePanel.getCodeScrollPane().getViewport().setViewPosition(viewState.getViewPoint()); codePanel.getCodeArea().setCaretPosition(viewState.getCaretPos()); } catch (Exception e) { LOG.error("Failed to restore view state", e); } } @Override public void dispose() { codePanel.dispose(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/ClassCodeContentPanel.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/ClassCodeContentPanel.java
package jadx.gui.ui.codearea; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import javax.swing.JCheckBox; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.border.EmptyBorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.DecompilationMode; import jadx.gui.jobs.BackgroundExecutor; import jadx.gui.treemodel.JClass; import jadx.gui.ui.codearea.mode.JCodeMode; import jadx.gui.ui.panel.IViewStateSupport; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.NLS; import static com.formdev.flatlaf.FlatClientProperties.TABBED_PANE_TRAILING_COMPONENT; /** * Displays one class with two different view: * * <ul> * <li>Java source code of the selected class (default)</li> * <li>Smali source code of the selected class</li> * </ul> */ public final class ClassCodeContentPanel extends AbstractCodeContentPanel implements IViewStateSupport { private static final Logger LOG = LoggerFactory.getLogger(ClassCodeContentPanel.class); private static final long serialVersionUID = -7229931102504634591L; private final transient CodePanel javaCodePanel; private final transient CodePanel smaliCodePanel; private final transient JTabbedPane areaTabbedPane; private boolean splitView = false; public ClassCodeContentPanel(TabbedPane panel, JClass jCls) { super(panel, jCls); javaCodePanel = new CodePanel(new CodeArea(this, jCls)); smaliCodePanel = new CodePanel(new SmaliArea(this, jCls)); areaTabbedPane = buildTabbedPane(jCls, false); addCustomControls(areaTabbedPane); initView(); javaCodePanel.load(); } private void initView() { removeAll(); setLayout(new BorderLayout()); setBorder(new EmptyBorder(0, 0, 0, 0)); if (splitView) { JTabbedPane splitPaneView = buildTabbedPane(((JClass) node), true); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, areaTabbedPane, splitPaneView); add(splitPane); splitPane.setDividerLocation(0.5); splitPaneView.setSelectedIndex(1); } else { add(areaTabbedPane); } invalidate(); } private JTabbedPane buildTabbedPane(JClass jCls, boolean split) { JTabbedPane areaTabbedPane = new JTabbedPane(JTabbedPane.BOTTOM); areaTabbedPane.setBorder(new EmptyBorder(0, 0, 0, 0)); areaTabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); if (split) { areaTabbedPane.add(new CodePanel(new CodeArea(this, jCls)), NLS.str("tabs.code")); areaTabbedPane.add(new CodePanel(new SmaliArea(this, jCls)), NLS.str("tabs.smali")); } else { areaTabbedPane.add(javaCodePanel, NLS.str("tabs.code")); areaTabbedPane.add(smaliCodePanel, NLS.str("tabs.smali")); } areaTabbedPane.add(new CodePanel(new CodeArea(this, new JCodeMode(jCls, DecompilationMode.SIMPLE))), "Simple"); areaTabbedPane.add(new CodePanel(new CodeArea(this, new JCodeMode(jCls, DecompilationMode.FALLBACK))), "Fallback"); areaTabbedPane.addChangeListener(e -> { CodePanel selectedPanel = (CodePanel) areaTabbedPane.getSelectedComponent(); // TODO: to run background load extract ui update to other method selectedPanel.load(); // execInBackground(selectedPanel::load); }); return areaTabbedPane; } private void addCustomControls(JTabbedPane tabbedPane) { JCheckBox splitCheckBox = new JCheckBox("Split view", splitView); splitCheckBox.addItemListener(e -> { splitView = splitCheckBox.isSelected(); this.initView(); }); JToolBar trailing = new JToolBar(); trailing.setFloatable(false); trailing.setBorder(null); // trailing.add(Box.createHorizontalGlue()); trailing.addSeparator(new Dimension(50, 1)); trailing.add(splitCheckBox); tabbedPane.putClientProperty(TABBED_PANE_TRAILING_COMPONENT, trailing); } private void execInBackground(Runnable runnable) { BackgroundExecutor bgExec = this.tabbedPane.getMainWindow().getBackgroundExecutor(); bgExec.execute("Loading", runnable); } @Override public void loadSettings() { javaCodePanel.loadSettings(); smaliCodePanel.loadSettings(); updateUI(); } @Override public AbstractCodeArea getCodeArea() { return javaCodePanel.getCodeArea(); } @Override public Component getChildrenComponent() { return getCodeArea(); } public CodePanel getJavaCodePanel() { return javaCodePanel; } public void switchPanel() { boolean toSmali = areaTabbedPane.getSelectedComponent() == javaCodePanel; areaTabbedPane.setSelectedComponent(toSmali ? smaliCodePanel : javaCodePanel); } public AbstractCodeArea getCurrentCodeArea() { return ((CodePanel) areaTabbedPane.getSelectedComponent()).getCodeArea(); } public AbstractCodeArea getSmaliCodeArea() { return smaliCodePanel.getCodeArea(); } public void showSmaliPane() { areaTabbedPane.setSelectedComponent(smaliCodePanel); } @Override public void saveEditorViewState(EditorViewState viewState) { CodePanel codePanel = (CodePanel) areaTabbedPane.getSelectedComponent(); int caretPos = codePanel.getCodeArea().getCaretPosition(); Point viewPoint = codePanel.getCodeScrollPane().getViewport().getViewPosition(); String subPath = codePanel == javaCodePanel ? "java" : "smali"; viewState.setSubPath(subPath); viewState.setCaretPos(caretPos); viewState.setViewPoint(viewPoint); } @Override public void restoreEditorViewState(EditorViewState viewState) { boolean isJava = viewState.getSubPath().equals("java"); CodePanel activePanel = isJava ? javaCodePanel : smaliCodePanel; areaTabbedPane.setSelectedComponent(activePanel); try { activePanel.getCodeScrollPane().getViewport().setViewPosition(viewState.getViewPoint()); } catch (Exception e) { LOG.debug("Failed to restore view position: {}", viewState.getViewPoint(), e); } int caretPos = viewState.getCaretPos(); try { AbstractCodeArea codeArea = activePanel.getCodeArea(); int codeLen = codeArea.getDocument().getLength(); if (caretPos >= 0 && caretPos < codeLen) { codeArea.setCaretPosition(caretPos); } } catch (Exception e) { LOG.debug("Failed to restore caret position: {}", caretPos, e); } } @Override public void dispose() { javaCodePanel.dispose(); smaliCodePanel.dispose(); for (Component component : areaTabbedPane.getComponents()) { if (component instanceof CodePanel) { ((CodePanel) component).dispose(); } } super.dispose(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/CodeArea.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/CodeArea.java
package jadx.gui.ui.codearea; import java.awt.Point; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Objects; import javax.swing.JPopupMenu; import javax.swing.event.PopupMenuEvent; import org.fife.ui.rsyntaxtextarea.RSyntaxDocument; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenTypes; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.JavaClass; import jadx.api.JavaNode; import jadx.api.metadata.ICodeAnnotation; import jadx.gui.JadxWrapper; import jadx.gui.jobs.IBackgroundTask; import jadx.gui.jobs.LoadTask; import jadx.gui.jobs.TaskWithExtraOnFinish; import jadx.gui.settings.JadxProject; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JLoadableNode; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JResource; import jadx.gui.ui.MainWindow; import jadx.gui.ui.action.*; import jadx.gui.ui.codearea.mode.JCodeMode; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.utils.CaretPositionFix; import jadx.gui.utils.DefaultPopupMenuListener; import jadx.gui.utils.JNodeCache; import jadx.gui.utils.JumpPosition; import jadx.gui.utils.UiUtils; import jadx.gui.utils.shortcut.ShortcutsController; /** * The {@link AbstractCodeArea} implementation used for displaying Java code and text based * resources (e.g. AndroidManifest.xml) */ public final class CodeArea extends AbstractCodeArea { private static final Logger LOG = LoggerFactory.getLogger(CodeArea.class); private static final long serialVersionUID = 6312736869579635796L; private @Nullable ICodeInfo cachedCodeInfo; private @Nullable MouseHoverHighlighter mouseHoverHighlighter; private final ShortcutsController shortcutsController; CodeArea(ContentPanel contentPanel, JNode node) { super(contentPanel, node); this.shortcutsController = getMainWindow().getShortcutsController(); setSyntaxEditingStyle(node.getSyntaxName()); boolean isJavaCode = isCodeNode(); if (isJavaCode) { ((RSyntaxDocument) getDocument()).setSyntaxStyle(new JadxTokenMaker(this)); } if (node instanceof JResource && node.makeString().endsWith(".json")) { addMenuForJsonFile(); } setHyperlinksEnabled(true); setCodeFoldingEnabled(true); setLinkScanningMask(InputEvent.CTRL_DOWN_MASK); CodeLinkGenerator codeLinkGenerator = new CodeLinkGenerator(this); setLinkGenerator(codeLinkGenerator); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.isControlDown() || jumpOnDoubleClick(e)) { navToDecl(e.getPoint()); } } }); if (isJavaCode) { mouseHoverHighlighter = new MouseHoverHighlighter(this, codeLinkGenerator); addMouseMotionListener(mouseHoverHighlighter); } } @Override public void loadSettings() { super.loadSettings(); if (mouseHoverHighlighter != null) { mouseHoverHighlighter.loadSettings(); } } public boolean isCodeNode() { return node instanceof JClass || node instanceof JCodeMode; } private boolean jumpOnDoubleClick(MouseEvent e) { return e.getClickCount() == 2 && getMainWindow().getSettings().isJumpOnDoubleClick(); } private void navToDecl(Point point) { int offs = viewToModel2D(point); JNode node = getJNodeAtOffset(adjustOffsetForWordToken(offs)); if (node != null) { contentPanel.getTabsController().codeJump(node); } } @Override public ICodeInfo getCodeInfo() { if (cachedCodeInfo == null) { if (isDisposed()) { LOG.debug("CodeArea used after dispose!"); return ICodeInfo.EMPTY; } cachedCodeInfo = Objects.requireNonNull(node.getCodeInfo()); } return cachedCodeInfo; } @Override public IBackgroundTask getLoadTask() { if (node instanceof JLoadableNode) { IBackgroundTask loadTask = ((JLoadableNode) node).getLoadTask(); if (loadTask != null) { return new TaskWithExtraOnFinish(loadTask, () -> { setText(getCodeInfo().getCodeStr()); setCaretPosition(0); setLoaded(); }); } } return new LoadTask<>( () -> getCodeInfo().getCodeStr(), code -> { setText(code); setCaretPosition(0); setLoaded(); }); } @Override public void refresh() { cachedCodeInfo = null; setText(getCodeInfo().getCodeStr()); } @Override protected JPopupMenu createPopupMenu() { JPopupMenu popup = super.createPopupMenu(); if (node instanceof JClass) { appendCodeMenuItems(popup); } return popup; } private void appendCodeMenuItems(JPopupMenu popupMenu) { ShortcutsController shortcutsController = getMainWindow().getShortcutsController(); JNodePopupBuilder popup = new JNodePopupBuilder(this, popupMenu, shortcutsController); popup.addSeparator(); popup.add(new FindUsageAction(this)); popup.add(new UsageDialogPlusAction(this)); popup.add(new GoToDeclarationAction(this)); popup.add(new CommentAction(this)); popup.add(new CommentSearchAction(this)); popup.add(new RenameAction(this)); popup.addSeparator(); popup.add(new FridaAction(this)); popup.add(new XposedAction(this)); getMainWindow().getWrapper().getGuiPluginsContext().appendPopupMenus(this, popup); // move caret on mouse right button click popupMenu.addPopupMenuListener(new DefaultPopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { CodeArea codeArea = CodeArea.this; if (codeArea.getSelectedText() == null) { int offset = UiUtils.getOffsetAtMousePosition(codeArea); if (offset >= 0) { codeArea.setCaretPosition(offset); } } } }); } private void addMenuForJsonFile() { ShortcutsController shortcutsController = getMainWindow().getShortcutsController(); JNodePopupBuilder popup = new JNodePopupBuilder(this, getPopupMenu(), shortcutsController); popup.addSeparator(); popup.add(new JsonPrettifyAction(this)); } /** * Search start of word token at specified offset * * @return -1 if no word token found */ public int adjustOffsetForWordToken(int offset) { Token token = getWordTokenAtOffset(offset); if (token == null) { return -1; } int type = token.getType(); if (isCodeNode()) { if (type == TokenTypes.IDENTIFIER || type == TokenTypes.FUNCTION) { return token.getOffset(); } if (type == TokenTypes.ANNOTATION && token.length() > 1) { return token.getOffset() + 1; } if (type == TokenTypes.RESERVED_WORD && token.length() == 6 && token.getLexeme().equals("static")) { // maybe a class init method return token.getOffset(); } } else if (type == TokenTypes.MARKUP_TAG_ATTRIBUTE_VALUE) { return token.getOffset() + 1; // skip quote at start (") } return -1; } /** * Search node by offset in {@code jCls} code and return its definition position * (useful for jumps from usage) */ @Nullable public JumpPosition getDefPosForNodeAtOffset(int offset) { if (offset == -1) { return null; } JavaNode foundNode = getJavaNodeAtOffset(offset); if (foundNode == null) { return null; } if (foundNode == node.getJavaNode()) { // current node return new JumpPosition(node); } JNode jNode = convertJavaNode(foundNode); return new JumpPosition(jNode); } private JNode convertJavaNode(JavaNode javaNode) { JNodeCache nodeCache = getMainWindow().getCacheObject().getNodeCache(); return nodeCache.makeFrom(javaNode); } @Nullable public JNode getNodeUnderCaret() { int caretPos = getCaretPosition(); return getJNodeAtOffset(adjustOffsetForWordToken(caretPos)); } @Nullable public JNode getEnclosingNodeUnderCaret() { int caretPos = getCaretPosition(); int start = adjustOffsetForWordToken(caretPos); if (start == -1) { start = caretPos; } return getEnclosingJNodeAtOffset(start); } @Nullable public JNode getNodeUnderMouse() { Point pos = UiUtils.getMousePosition(this); return getJNodeAtOffset(adjustOffsetForWordToken(viewToModel2D(pos))); } @Nullable public JNode getEnclosingNodeUnderMouse() { Point pos = UiUtils.getMousePosition(this); return getEnclosingJNodeAtOffset(adjustOffsetForWordToken(viewToModel2D(pos))); } @Nullable public JNode getEnclosingJNodeAtOffset(int offset) { JavaNode javaNode = getEnclosingJavaNode(offset); if (javaNode != null) { return convertJavaNode(javaNode); } return null; } @Nullable public JNode getJNodeAtOffset(int offset) { JavaNode javaNode = getJavaNodeAtOffset(offset); if (javaNode != null) { return convertJavaNode(javaNode); } return null; } /** * Search referenced java node by offset in {@code jCls} code */ public JavaNode getJavaNodeAtOffset(int offset) { if (offset == -1) { return null; } try { return getJadxWrapper().getDecompiler().getJavaNodeAtPosition(getCodeInfo(), offset); } catch (Exception e) { LOG.error("Can't get java node by offset: {}", offset, e); } return null; } public JavaNode getClosestJavaNode(int offset) { if (offset == -1) { return null; } try { return getJadxWrapper().getDecompiler().getClosestJavaNode(getCodeInfo(), offset); } catch (Exception e) { LOG.error("Can't get java node by offset: {}", offset, e); return null; } } public JavaNode getEnclosingJavaNode(int offset) { if (offset == -1) { return null; } try { return getJadxWrapper().getDecompiler().getEnclosingNode(getCodeInfo(), offset); } catch (Exception e) { LOG.error("Can't get java node by offset: {}", offset, e); return null; } } public @Nullable JavaClass getJavaClassIfAtPos(int pos) { try { ICodeInfo codeInfo = getCodeInfo(); if (!codeInfo.hasMetadata()) { return null; } ICodeAnnotation ann = codeInfo.getCodeMetadata().getAt(pos); if (ann == null) { return null; } switch (ann.getAnnType()) { case CLASS: return (JavaClass) getJadxWrapper().getDecompiler().getJavaNodeByCodeAnnotation(codeInfo, ann); case METHOD: // use class from constructor call JavaNode node = getJadxWrapper().getDecompiler().getJavaNodeByCodeAnnotation(codeInfo, ann); return node != null ? node.getDeclaringClass() : null; default: return null; } } catch (Exception e) { LOG.error("Can't get java node by offset: {}", pos, e); return null; } } public void refreshClass() { if (node instanceof JClass) { JClass cls = node.getRootClass(); try { CaretPositionFix caretFix = new CaretPositionFix(this); caretFix.save(); cachedCodeInfo = cls.reload(getMainWindow().getCacheObject()); ClassCodeContentPanel codeContentPanel = (ClassCodeContentPanel) this.contentPanel; codeContentPanel.getTabbedPane().refresh(cls); codeContentPanel.getJavaCodePanel().refresh(caretFix); } catch (Exception e) { LOG.error("Failed to reload class: {}", cls.getFullName(), e); } } } public MainWindow getMainWindow() { return contentPanel.getMainWindow(); } public JadxWrapper getJadxWrapper() { return getMainWindow().getWrapper(); } public JadxProject getProject() { return getMainWindow().getProject(); } @Override public void dispose() { shortcutsController.unbindActionsForComponent(this); super.dispose(); cachedCodeInfo = null; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/JadxTokenMaker.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/JadxTokenMaker.java
package jadx.gui.ui.codearea; import java.util.Set; import javax.swing.text.Segment; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenImpl; import org.fife.ui.rsyntaxtextarea.TokenTypes; import org.fife.ui.rsyntaxtextarea.modes.JavaTokenMaker; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JavaClass; import jadx.api.JavaNode; import static jadx.api.plugins.utils.Utils.constSet; public final class JadxTokenMaker extends JavaTokenMaker { private static final Logger LOG = LoggerFactory.getLogger(JadxTokenMaker.class); private final CodeArea codeArea; public JadxTokenMaker(CodeArea codeArea) { this.codeArea = codeArea; } @Override public Token getTokenList(Segment text, int initialTokenType, int startOffset) { if (codeArea.isDisposed()) { return new TokenImpl(); } try { Token tokens = super.getTokenList(text, initialTokenType, startOffset); if (tokens != null && tokens.getType() != TokenTypes.NULL) { processTokens(tokens); } return tokens; } catch (Throwable e) { // JavaTokenMaker throws 'java.lang.Error' if failed to parse input string LOG.error("Process tokens failed for text: {}", text, e); return new TokenImpl(); } } private void processTokens(Token tokens) { Token prev = null; Token current = tokens; while (current != null) { if (prev != null) { switch (current.getType()) { case TokenTypes.RESERVED_WORD: fixContextualKeyword(current); break; case TokenTypes.IDENTIFIER: current = mergeLongClassNames(prev, current, false); break; case TokenTypes.ANNOTATION: current = mergeLongClassNames(prev, current, true); break; } } prev = current; current = current.getNextToken(); } } private static final Set<String> CONTEXTUAL_KEYWORDS = constSet( "exports", "module", "non-sealed", "open", "opens", "permits", "provides", "record", "requires", "sealed", "to", "transitive", "uses", "var", "with", "yield"); private static void fixContextualKeyword(Token token) { String lexeme = token.getLexeme(); // TODO: create new string every call, better to avoid if (lexeme != null && CONTEXTUAL_KEYWORDS.contains(lexeme)) { token.setType(TokenTypes.IDENTIFIER); } } @NotNull private Token mergeLongClassNames(Token prev, Token current, boolean annotation) { int offset = current.getTextOffset(); if (annotation) { offset++; } JavaClass javaCls = codeArea.getJavaClassIfAtPos(offset); if (javaCls != null) { String name = javaCls.getName(); String lexeme = current.getLexeme(); if (annotation && lexeme.length() > 1) { lexeme = lexeme.substring(1); } if (!lexeme.equals(name) && isClassNameStart(javaCls, lexeme)) { // try to replace long class name with one token Token replace = concatTokensUntil(current, name); if (replace != null && prev instanceof TokenImpl) { TokenImpl impl = ((TokenImpl) prev); impl.setNextToken(replace); current = replace; } } } return current; } private boolean isClassNameStart(JavaNode javaNode, String lexeme) { if (javaNode.getFullName().startsWith(lexeme)) { // full class name return true; } if (javaNode.getTopParentClass().getName().startsWith(lexeme)) { // inner class references from parent class return true; } return false; } @Nullable private Token concatTokensUntil(Token start, String endText) { StringBuilder sb = new StringBuilder(); Token current = start; while (current != null && current.getType() != TokenTypes.NULL) { String text = current.getLexeme(); if (text != null) { sb.append(text); if (text.equals(endText)) { char[] line = sb.toString().toCharArray(); TokenImpl token = new TokenImpl(line, 0, line.length - 1, start.getOffset(), start.getType(), start.getLanguageIndex()); token.setNextToken(current.getNextToken()); return token; } } current = current.getNextToken(); } return null; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/UsageDialogPlusAction.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/UsageDialogPlusAction.java
package jadx.gui.ui.codearea; import jadx.gui.treemodel.JNode; import jadx.gui.ui.action.ActionModel; import jadx.gui.ui.action.JNodeAction; import jadx.gui.ui.dialog.UsageDialogPlus; public final class UsageDialogPlusAction extends JNodeAction { private static final long serialVersionUID = 4692546569977976384L; public UsageDialogPlusAction(CodeArea codeArea) { super(ActionModel.FIND_USAGE_PLUS, codeArea); } @Override public void runAction(JNode node) { UsageDialogPlus.open(getCodeArea().getMainWindow(), node); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/JNodePopupBuilder.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/JNodePopupBuilder.java
package jadx.gui.ui.codearea; import javax.swing.JPopupMenu; import javax.swing.event.PopupMenuListener; import jadx.gui.ui.action.JNodeAction; import jadx.gui.ui.action.JadxGuiAction; import jadx.gui.utils.shortcut.ShortcutsController; public class JNodePopupBuilder { private final JPopupMenu menu; private final JNodePopupListener popupListener; private final ShortcutsController shortcutsController; public JNodePopupBuilder(CodeArea codeArea, JPopupMenu popupMenu, ShortcutsController shortcutsController) { this.shortcutsController = shortcutsController; menu = popupMenu; popupListener = new JNodePopupListener(codeArea); popupMenu.addPopupMenuListener(popupListener); } public void addSeparator() { menu.addSeparator(); } public void add(JNodeAction nodeAction) { // We set the shortcut immediately for two reasons // - there might be multiple instances of this action with // same ActionModel across different codeAreas, while // ShortcutController only supports one instance // - This action will be recreated when shortcuts are changed, // so no need to bind it if (nodeAction.getActionModel() != null) { shortcutsController.bindImmediate(nodeAction); } menu.add(nodeAction); popupListener.addActions(nodeAction); } public void add(JadxGuiAction action) { if (action.getActionModel() != null) { shortcutsController.bindImmediate(action); } menu.add(action); if (action instanceof PopupMenuListener) { menu.addPopupMenuListener((PopupMenuListener) action); } } public JPopupMenu getMenu() { return menu; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/SearchBar.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/SearchBar.java
package jadx.gui.ui.codearea; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.border.EmptyBorder; import javax.swing.text.BadLocationException; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rtextarea.SearchContext; import org.fife.ui.rtextarea.SearchEngine; import org.fife.ui.rtextarea.SearchResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.formdev.flatlaf.FlatClientProperties; import jadx.core.utils.StringUtils; import jadx.gui.utils.Icons; import jadx.gui.utils.NLS; import jadx.gui.utils.TextStandardActions; public class SearchBar extends JToolBar { private static final long serialVersionUID = 1836871286618633003L; private static final Logger LOG = LoggerFactory.getLogger(SearchBar.class); private static final int MAX_RESULT_COUNT = 999; private final RSyntaxTextArea rTextArea; private final JTextField searchField; private final JLabel resultCountLabel; private final JToggleButton markAllCB; private final JToggleButton regexCB; private final JToggleButton wholeWordCB; private final JToggleButton matchCaseCB; private boolean notFound; public SearchBar(RSyntaxTextArea textArea) { rTextArea = textArea; JLabel findLabel = new JLabel(NLS.str("search.find") + ':'); add(findLabel); searchField = new JTextField(30); searchField.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); searchField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_ENTER: // skip break; case KeyEvent.VK_ESCAPE: toggle(); break; default: search(0); break; } } }); searchField.addActionListener(e -> search(1)); TextStandardActions.attach(searchField); add(searchField); ActionListener forwardListener = e -> search(1); resultCountLabel = new JLabel(); resultCountLabel.setBorder(new EmptyBorder(0, 10, 0, 10)); resultCountLabel.setForeground(Color.GRAY); add(resultCountLabel); setResultCount(0); matchCaseCB = new JToggleButton(); matchCaseCB.setIcon(Icons.ICON_MATCH); matchCaseCB.setSelectedIcon(Icons.ICON_MATCH_SELECTED); matchCaseCB.setToolTipText(NLS.str("search.match_case")); matchCaseCB.addActionListener(forwardListener); add(matchCaseCB); wholeWordCB = new JToggleButton(); wholeWordCB.setIcon(Icons.ICON_WORDS); wholeWordCB.setSelectedIcon(Icons.ICON_WORDS_SELECTED); wholeWordCB.setToolTipText(NLS.str("search.whole_word")); wholeWordCB.addActionListener(forwardListener); add(wholeWordCB); regexCB = new JToggleButton(); regexCB.setIcon(Icons.ICON_REGEX); regexCB.setSelectedIcon(Icons.ICON_REGEX_SELECTED); regexCB.setToolTipText(NLS.str("search.regex")); regexCB.addActionListener(forwardListener); add(regexCB); JButton prevButton = new JButton(); prevButton.setIcon(Icons.ICON_UP); prevButton.setToolTipText(NLS.str("search.previous")); prevButton.addActionListener(e -> search(-1)); prevButton.setBorderPainted(false); add(prevButton); JButton nextButton = new JButton(); nextButton.setIcon(Icons.ICON_DOWN); nextButton.setToolTipText(NLS.str("search.next")); nextButton.addActionListener(e -> search(1)); nextButton.setBorderPainted(false); add(nextButton); markAllCB = new JToggleButton(); markAllCB.setIcon(Icons.ICON_MARK); markAllCB.setSelectedIcon(Icons.ICON_MARK_SELECTED); markAllCB.setToolTipText(NLS.str("search.mark_all")); markAllCB.addActionListener(forwardListener); add(markAllCB); JButton closeButton = new JButton(); closeButton.setIcon(Icons.ICON_CLOSE); closeButton.addActionListener(e -> toggle()); closeButton.setBorderPainted(false); add(closeButton); setFloatable(false); setVisible(false); } /* * Replicates IntelliJ's search bar behavior * 1.1. If the user has selected text, use that as the search text * 1.2. Otherwise, use the previous search text (or empty if none) * 2. Select all text in the search bar and give it focus */ public void showAndFocus() { setVisible(true); String selectedText = rTextArea.getSelectedText(); if (!StringUtils.isEmpty(selectedText)) { searchField.setText(selectedText); } searchField.selectAll(); searchField.requestFocus(); } public void toggle() { boolean visible = !isVisible(); setVisible(visible); if (visible) { String preferText = rTextArea.getSelectedText(); if (!StringUtils.isEmpty(preferText)) { searchField.setText(preferText); } searchField.selectAll(); searchField.requestFocus(); } else { rTextArea.requestFocus(); } } private void search(int direction) { String searchText = searchField.getText(); if (searchText == null || searchText.isEmpty() || rTextArea.getText() == null) { setResultCount(0); return; } boolean forward = direction >= 0; boolean matchCase = matchCaseCB.isSelected(); boolean regex = regexCB.isSelected(); boolean wholeWord = wholeWordCB.isSelected(); SearchContext context = new SearchContext(); context.setSearchFor(searchText); context.setMatchCase(matchCase); context.setRegularExpression(regex); context.setSearchForward(forward); context.setWholeWord(wholeWord); context.setSearchWrap(true); // We enable Mark All even if the corresponding toggle button is off, // this is a bit hackish, but it's the only way to count matches through SearchEngine context.setMarkAll(true); // TODO hack: move cursor before previous search for not jump to next occurrence if (direction == 0 && !notFound) { try { int caretPos = rTextArea.getCaretPosition(); int lineNum = rTextArea.getLineOfOffset(caretPos) - 1; if (lineNum > 1) { rTextArea.setCaretPosition(rTextArea.getLineStartOffset(lineNum)); } } catch (BadLocationException e) { LOG.error("Caret move error", e); } } SearchResult result = SearchEngine.find(rTextArea, context); setResultCount(result.getMarkedCount()); // Clear the highlighted results if Mark All is disabled if (!markAllCB.isSelected()) { context.setMarkAll(false); SearchEngine.markAll(rTextArea, context); } notFound = !result.wasFound(); if (notFound) { searchField.putClientProperty("JComponent.outline", "error"); } else { searchField.putClientProperty("JComponent.outline", ""); } searchField.repaint(); } private void setResultCount(int count) { boolean exceedsLimit = count > MAX_RESULT_COUNT; String plusSign = exceedsLimit ? "+" : ""; count = exceedsLimit ? MAX_RESULT_COUNT : count; resultCountLabel.setText(NLS.str("search.results", plusSign, count)); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/EditorViewState.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/EditorViewState.java
package jadx.gui.ui.codearea; import java.awt.Point; import jadx.gui.treemodel.JNode; public class EditorViewState { public static final Point ZERO = new Point(0, 0); private final JNode node; private int caretPos; private Point viewPoint; private String subPath; private boolean active; private boolean pinned; private boolean bookmarked; private boolean hidden; private boolean previewTab; public EditorViewState(JNode node) { this(node, "", 0, EditorViewState.ZERO); } public EditorViewState(JNode node, String subPath, int caretPos, Point viewPoint) { this.node = node; this.subPath = subPath; this.caretPos = caretPos; this.viewPoint = viewPoint; } public JNode getNode() { return node; } public int getCaretPos() { return caretPos; } public void setCaretPos(int caretPos) { this.caretPos = caretPos; } public Point getViewPoint() { return viewPoint; } public void setViewPoint(Point viewPoint) { this.viewPoint = viewPoint; } public String getSubPath() { return subPath; } public void setSubPath(String subPath) { this.subPath = subPath; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public boolean isPinned() { return pinned; } public void setPinned(boolean pinned) { this.pinned = pinned; } public boolean isBookmarked() { return bookmarked; } public void setBookmarked(boolean bookmarked) { this.bookmarked = bookmarked; } public boolean isHidden() { return hidden; } public boolean isPreviewTab() { return previewTab; } public void setPreviewTab(boolean previewTab) { this.previewTab = previewTab; } public void setHidden(boolean hidden) { this.hidden = hidden; } @Override public String toString() { return "EditorViewState{node=" + node + ", caretPos=" + caretPos + ", viewPoint=" + viewPoint + ", subPath='" + subPath + '\'' + ", active=" + active + '}'; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/CommentAction.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/CommentAction.java
package jadx.gui.ui.codearea; import java.awt.event.ActionEvent; import java.util.Objects; import javax.swing.event.PopupMenuEvent; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenTypes; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.api.JavaMethod; import jadx.api.JavaNode; import jadx.api.data.ICodeComment; import jadx.api.data.impl.JadxCodeComment; import jadx.api.data.impl.JadxCodeData; import jadx.api.data.impl.JadxCodeRef; import jadx.api.data.impl.JadxNodeRef; import jadx.api.metadata.ICodeAnnotation; import jadx.api.metadata.ICodeAnnotation.AnnType; import jadx.api.metadata.ICodeMetadata; import jadx.api.metadata.ICodeNodeRef; import jadx.api.metadata.annotations.InsnCodeOffset; import jadx.api.metadata.annotations.NodeDeclareRef; import jadx.gui.JadxWrapper; import jadx.gui.settings.JadxProject; import jadx.gui.treemodel.JClass; import jadx.gui.ui.action.ActionModel; import jadx.gui.ui.action.CodeAreaAction; import jadx.gui.ui.action.JadxGuiAction; import jadx.gui.ui.dialog.CommentDialog; import jadx.gui.utils.DefaultPopupMenuListener; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public class CommentAction extends CodeAreaAction implements DefaultPopupMenuListener { private static final long serialVersionUID = 4753838562204629112L; private static final Logger LOG = LoggerFactory.getLogger(CommentAction.class); private final boolean enabled; private @Nullable ICodeComment actionComment; private boolean updateComment; public CommentAction(CodeArea codeArea) { super(ActionModel.CODE_COMMENT, codeArea); this.enabled = codeArea.getNode() instanceof JClass; } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { if (enabled && updateCommentAction(UiUtils.getOffsetAtMousePosition(codeArea))) { setNameAndDesc(updateComment ? NLS.str("popup.update_comment") : NLS.str("popup.add_comment")); setEnabled(true); } else { setEnabled(false); } } @Override public void popupMenuCanceled(PopupMenuEvent e) { actionComment = null; setEnabled(false); } private boolean updateCommentAction(int pos) { ICodeComment codeComment = getCommentRef(pos); if (codeComment == null) { actionComment = null; return false; } ICodeComment exitsComment = searchForExistComment(codeComment); if (exitsComment != null) { actionComment = exitsComment; updateComment = true; } else { actionComment = codeComment; updateComment = false; } return true; } @Override public void actionPerformed(ActionEvent e) { if (!enabled) { return; } if (JadxGuiAction.isSource(e)) { updateCommentAction(codeArea.getCaretPosition()); } if (actionComment == null) { UiUtils.showMessageBox(codeArea.getMainWindow(), NLS.str("msg.cant_add_comment")); return; } CommentDialog.show(codeArea, actionComment, updateComment); } private @Nullable ICodeComment searchForExistComment(ICodeComment blankComment) { try { JadxProject project = codeArea.getProject(); JadxCodeData codeData = project.getCodeData(); if (codeData == null || codeData.getComments().isEmpty()) { return null; } for (ICodeComment comment : codeData.getComments()) { if (Objects.equals(comment.getNodeRef(), blankComment.getNodeRef()) && Objects.equals(comment.getCodeRef(), blankComment.getCodeRef())) { return comment; } } } catch (Exception e) { LOG.error("Error searching for exists comment", e); } return null; } /** * Check if possible insert comment at current line. * * @return blank code comment object (comment string empty) */ @Nullable private ICodeComment getCommentRef(int pos) { if (pos == -1) { return null; } try { JadxWrapper wrapper = codeArea.getJadxWrapper(); ICodeInfo codeInfo = codeArea.getCodeInfo(); ICodeMetadata metadata = codeInfo.getCodeMetadata(); int lineStartPos = codeArea.getLineStartFor(pos); // add method line comment by instruction offset ICodeAnnotation offsetAnn = metadata.searchUp(pos, lineStartPos, AnnType.OFFSET); if (offsetAnn instanceof InsnCodeOffset) { JavaNode node = wrapper.getJavaNodeByRef(metadata.getNodeAt(pos)); if (node instanceof JavaMethod) { int rawOffset = ((InsnCodeOffset) offsetAnn).getOffset(); JadxNodeRef nodeRef = JadxNodeRef.forMth((JavaMethod) node); return new JadxCodeComment(nodeRef, JadxCodeRef.forInsn(rawOffset), ""); } } // check for definition at this line ICodeNodeRef nodeDef = metadata.searchUp(pos, (off, ann) -> { if (lineStartPos <= off && ann.getAnnType() == AnnType.DECLARATION) { ICodeNodeRef defRef = ((NodeDeclareRef) ann).getNode(); if (defRef.getAnnType() != AnnType.VAR) { return defRef; } } return null; }); if (nodeDef != null) { JadxNodeRef nodeRef = JadxNodeRef.forJavaNode(wrapper.getJavaNodeByRef(nodeDef)); return new JadxCodeComment(nodeRef, ""); } // check if at comment above node definition if (isCommentLine(pos)) { ICodeNodeRef nodeRef = metadata.searchDown(pos, (off, ann) -> { if (off > pos && ann.getAnnType() == AnnType.DECLARATION) { return ((NodeDeclareRef) ann).getNode(); } return null; }); if (nodeRef != null) { JavaNode defNode = wrapper.getJavaNodeByRef(nodeRef); return new JadxCodeComment(JadxNodeRef.forJavaNode(defNode), ""); } } } catch (Exception e) { LOG.error("Failed to add comment at: {}", pos, e); } return null; } /** * Check if all tokens are 'comment' in line at 'pos' */ private boolean isCommentLine(int pos) { try { int line = codeArea.getLineOfOffset(pos); Token lineTokens = codeArea.getTokenListForLine(line); boolean commentFound = false; for (Token t = lineTokens; t != null; t = t.getNextToken()) { if (t.isComment()) { commentFound = true; } else { switch (t.getType()) { case TokenTypes.WHITESPACE: case TokenTypes.NULL: // allowed tokens break; default: return false; } } } return commentFound; } catch (Exception e) { LOG.warn("Failed to check for comment line", e); return false; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/SourceLineFormatter.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/SourceLineFormatter.java
package jadx.gui.ui.codearea; import org.fife.ui.rtextarea.LineNumberFormatter; import jadx.api.ICodeInfo; public class SourceLineFormatter implements LineNumberFormatter { private final ICodeInfo codeInfo; private final int maxLength; public SourceLineFormatter(ICodeInfo codeInfo) { this.codeInfo = codeInfo; this.maxLength = calcMaxLength(codeInfo); } @Override public String format(int lineNumber) { Integer sourceLine = codeInfo.getCodeMetadata().getLineMapping().get(lineNumber); if (sourceLine == null) { return ""; } return String.valueOf(sourceLine); } @Override public int getMaxLength(int maxLineNumber) { return maxLength; } private static int calcMaxLength(ICodeInfo codeInfo) { int maxLine = codeInfo.getCodeMetadata().getLineMapping() .values().stream() .mapToInt(Integer::intValue) .max().orElse(1); return getNumberLength(maxLine); } public static int getNumberLength(int num) { return num < 10 ? 1 : 1 + (int) Math.log10(num); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/JNodePopupListener.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/JNodePopupListener.java
package jadx.gui.ui.codearea; import java.util.ArrayList; import java.util.List; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import jadx.gui.treemodel.JNode; import jadx.gui.ui.action.JNodeAction; public final class JNodePopupListener implements PopupMenuListener { private final CodeArea codeArea; private final List<JNodeAction> actions = new ArrayList<>(); public JNodePopupListener(CodeArea codeArea) { this.codeArea = codeArea; } public void addActions(JNodeAction action) { actions.add(action); } private void updateNode(JNode node) { for (JNodeAction action : actions) { action.changeNode(node); } } @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { updateNode(codeArea.getNodeUnderMouse()); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { // this event can be called just before running action, so can't reset node here } @Override public void popupMenuCanceled(PopupMenuEvent e) { updateNode(null); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/BinaryContentPanel.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/BinaryContentPanel.java
package jadx.gui.ui.codearea; import java.awt.BorderLayout; import java.awt.Component; import java.nio.charset.StandardCharsets; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ResourcesLoader; import jadx.api.resources.ResourceContentType; import jadx.gui.jobs.BackgroundExecutor; import jadx.gui.jobs.IBackgroundTask; import jadx.gui.jobs.TaskWithExtraOnFinish; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.LineNumbersMode; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.JResource; import jadx.gui.ui.hexviewer.HexPreviewPanel; import jadx.gui.ui.tab.TabbedPane; import jadx.gui.utils.UiUtils; public class BinaryContentPanel extends AbstractCodeContentPanel { private static final Logger LOG = LoggerFactory.getLogger(BinaryContentPanel.class); private final transient CodePanel textCodePanel; private final transient HexPreviewPanel hexPreviewPanel; private final transient JTabbedPane areaTabbedPane; public BinaryContentPanel(TabbedPane panel, JNode jnode, boolean supportsText) { super(panel, jnode); setLayout(new BorderLayout()); setBorder(new EmptyBorder(0, 0, 0, 0)); if (supportsText) { textCodePanel = new CodePanel(new CodeArea(this, jnode)); } else { textCodePanel = null; } hexPreviewPanel = new HexPreviewPanel(getSettings()); hexPreviewPanel.getInspector().setVisible(false); areaTabbedPane = buildTabbedPane(); add(areaTabbedPane); SwingUtilities.invokeLater(this::loadSelectedPanel); } private void loadHexView() { if (hexPreviewPanel.isDataLoaded()) { return; } UiUtils.notUiThreadGuard(); byte[] bytes = getNodeBytes(); UiUtils.uiRunAndWait(() -> hexPreviewPanel.setData(bytes)); } private byte[] getNodeBytes() { JNode binaryNode = getNode(); if (binaryNode instanceof JResource) { JResource jResource = (JResource) binaryNode; try { return ResourcesLoader.decodeStream(jResource.getResFile(), (size, is) -> is.readAllBytes()); } catch (Exception e) { LOG.error("Failed to directly load resource binary data {}: {}", jResource.getName(), e.getMessage()); } } return binaryNode.getCodeInfo().getCodeStr().getBytes(StandardCharsets.US_ASCII); } private JTabbedPane buildTabbedPane() { JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.BOTTOM); tabbedPane.setBorder(new EmptyBorder(0, 0, 0, 0)); tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); if (textCodePanel != null) { tabbedPane.add(textCodePanel, "Text"); } tabbedPane.add(hexPreviewPanel, "Hex"); tabbedPane.addChangeListener(e -> { getMainWindow().toggleHexViewMenu(); loadSelectedPanel(); }); return tabbedPane; } private void loadSelectedPanel() { BackgroundExecutor bgExec = getMainWindow().getBackgroundExecutor(); Component codePanel = getSelectedPanel(); if (codePanel instanceof CodeArea) { CodeArea codeArea = (CodeArea) codePanel; codeArea.load(); } else { bgExec.startLoading(this::loadHexView); } } @Override public AbstractCodeArea getCodeArea() { if (textCodePanel != null) { return textCodePanel.getCodeArea(); } else { return null; } } @Override public void scrollToPos(int pos) { UiUtils.uiThreadGuard(); BackgroundExecutor bgExec = getMainWindow().getBackgroundExecutor(); if (getNode().getContentType() == ResourceContentType.CONTENT_TEXT) { areaTabbedPane.setSelectedComponent(textCodePanel); AbstractCodeArea codeArea = textCodePanel.getCodeArea(); if (codeArea.isLoaded()) { codeArea.scrollToPos(pos); } else { IBackgroundTask loadTask = codeArea.getLoadTask(); bgExec.execute(new TaskWithExtraOnFinish(loadTask, () -> codeArea.scrollToPos(pos))); } } else { areaTabbedPane.setSelectedComponent(hexPreviewPanel); bgExec.startLoading(this::loadHexView, () -> hexPreviewPanel.scrollToOffset(pos)); } } @Override public Component getChildrenComponent() { return getSelectedPanel(); } @Override public void loadSettings() { if (textCodePanel != null) { textCodePanel.loadSettings(); } updateUI(); } @Override public JadxSettings getSettings() { JadxSettings settings = super.getSettings(); settings.setLineNumbersMode(LineNumbersMode.NORMAL); return settings; } private Component getSelectedPanel() { Component selectedComponent = areaTabbedPane.getSelectedComponent(); Component selectedPanel; if (selectedComponent instanceof CodePanel) { selectedPanel = ((CodePanel) selectedComponent).getCodeArea(); } else if (selectedComponent instanceof JSplitPane) { selectedPanel = ((JSplitPane) selectedComponent).getLeftComponent(); } else if (selectedComponent instanceof HexPreviewPanel) { selectedPanel = selectedComponent; } else { throw new RuntimeException("tabbedPane.getSelectedComponent returned a Component " + "of unexpected type " + selectedComponent); } return selectedPanel; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/SmaliArea.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/SmaliArea.java
package jadx.gui.ui.codearea; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.Icon; import javax.swing.JCheckBoxMenuItem; import javax.swing.KeyStroke; import javax.swing.text.BadLocationException; import javax.swing.text.EditorKit; import javax.swing.text.JTextComponent; import org.fife.ui.rsyntaxtextarea.FoldingAwareIconRowHeader; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaEditorKit; import org.fife.ui.rsyntaxtextarea.RSyntaxTextAreaUI; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; import org.fife.ui.rsyntaxtextarea.Style; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.fife.ui.rsyntaxtextarea.SyntaxScheme; import org.fife.ui.rtextarea.Gutter; import org.fife.ui.rtextarea.GutterIconInfo; import org.fife.ui.rtextarea.IconRowHeader; import org.fife.ui.rtextarea.RTextArea; import org.fife.ui.rtextarea.RTextAreaUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.gui.device.debugger.BreakpointManager; import jadx.gui.device.debugger.DbgUtils; import jadx.gui.jobs.IBackgroundTask; import jadx.gui.jobs.LoadTask; import jadx.gui.settings.JadxSettings; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; import jadx.gui.treemodel.TextNode; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; public final class SmaliArea extends AbstractCodeArea { private static final Logger LOG = LoggerFactory.getLogger(SmaliArea.class); private static final long serialVersionUID = 1334485631870306494L; private static final Icon ICON_BREAKPOINT = UiUtils.openSvgIcon("debugger/db_set_breakpoint"); private static final Icon ICON_BREAKPOINT_DISABLED = UiUtils.openSvgIcon("debugger/db_disabled_breakpoint"); private static final Color BREAKPOINT_LINE_COLOR = Color.decode("#ad103c"); private static final Color DEBUG_LINE_COLOR = Color.decode("#9c1138"); private final JNode textNode; private final JCheckBoxMenuItem cbUseSmaliV2; private boolean curVersion = false; private SmaliModel model; SmaliArea(ContentPanel contentPanel, JClass node) { super(contentPanel, node); this.textNode = new TextNode(node.getName()); setCodeFoldingEnabled(true); cbUseSmaliV2 = new JCheckBoxMenuItem(NLS.str("popup.bytecode_col"), shouldUseSmaliPrinterV2()); cbUseSmaliV2.setAction(new AbstractAction(NLS.str("popup.bytecode_col")) { private static final long serialVersionUID = -1111111202103170737L; @Override public void actionPerformed(ActionEvent e) { JadxSettings settings = getContentPanel().getMainWindow().getSettings(); settings.setSmaliAreaShowBytecode(!settings.isSmaliAreaShowBytecode()); contentPanel.getTabbedPane().getTabs().forEach(v -> { if (v instanceof ClassCodeContentPanel) { switchModel(); ((ClassCodeContentPanel) v).getSmaliCodeArea().refresh(); } }); settings.sync(); } }); getPopupMenu().add(cbUseSmaliV2); switchModel(); } @Override public IBackgroundTask getLoadTask() { return new LoadTask<>( () -> model.loadCode(), code -> { curVersion = shouldUseSmaliPrinterV2(); model.loadUI(code); setCaretPosition(0); setLoaded(); }); } @Override public ICodeInfo getCodeInfo() { return ICodeInfo.EMPTY; } @Override public void refresh() { load(); } @Override public JNode getNode() { // this area contains only smali without other node attributes return textNode; } public JClass getJClass() { return (JClass) node; } private void switchModel() { if (model != null) { model.unload(); } curVersion = shouldUseSmaliPrinterV2(); model = curVersion ? new DebugModel() : new NormalModel(this); setUnLoaded(); load(); } public void scrollToDebugPos(int pos) { // don't sync when it's set programmatically. getContentPanel().getMainWindow().getSettings().setSmaliAreaShowBytecode(true); cbUseSmaliV2.setState(shouldUseSmaliPrinterV2()); if (!(model instanceof DebugModel)) { switchModel(); refresh(); } model.togglePosHighlight(pos); } @Override public Font getFont() { if (model == null || isDisposed()) { return super.getFont(); } return model.getFont(); } @Override public Font getFontForTokenType(int type) { return getFont(); } private boolean shouldUseSmaliPrinterV2() { return getContentPanel().getMainWindow().getSettings().isSmaliAreaShowBytecode(); } private abstract class SmaliModel { abstract String loadCode(); abstract void loadUI(String code); abstract void unload(); Font getFont() { return SmaliArea.super.getFont(); } Font getFontForTokenType(int type) { return SmaliArea.super.getFontForTokenType(type); } void setBreakpoint(int off) { } void togglePosHighlight(int pos) { } } private class NormalModel extends SmaliModel { public NormalModel(SmaliArea smaliArea) { getContentPanel().getMainWindow().getEditorThemeManager().apply(smaliArea); setSyntaxEditingStyle(SYNTAX_STYLE_SMALI); } @Override public String loadCode() { return getJClass().getSmali(); } @Override public void loadUI(String code) { setText(code); } @Override public void unload() { } } private class DebugModel extends SmaliModel { private KeyStroke bpShortcut; private Gutter gutter; private Object runningHighlightTag = null; // running line private final SmaliV2Style smaliV2Style = new SmaliV2Style(SmaliArea.this); private final Map<Integer, BreakpointLine> bpMap = new HashMap<>(); private final PropertyChangeListener schemeListener = evt -> { if (smaliV2Style.refreshTheme()) { setSyntaxScheme(smaliV2Style); } }; public DebugModel() { loadV2Style(); setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_ASSEMBLER_6502); addPropertyChangeListener(SYNTAX_SCHEME_PROPERTY, schemeListener); regBreakpointEvents(); } @Override String loadCode() { return DbgUtils.getSmaliCode(((JClass) node).getCls().getClassNode()); } @Override void loadUI(String code) { if (gutter == null) { gutter = RSyntaxUtilities.getGutter(SmaliArea.this); gutter.setBookmarkingEnabled(true); gutter.setIconRowHeaderInheritsGutterBackground(true); Font baseFont = SmaliArea.super.getFont(); gutter.setLineNumberFont(baseFont.deriveFont(baseFont.getSize2D() - 1.0f)); } setText(code); loadV2Style(); loadBreakpoints(); } @Override public void unload() { removePropertyChangeListener(schemeListener); removeLineHighlight(runningHighlightTag); UiUtils.removeKeyBinding(SmaliArea.this, bpShortcut, "set a break point"); BreakpointManager.removeListener((JClass) node); bpMap.forEach((k, v) -> v.remove()); } @Override public Font getFont() { return smaliV2Style.getFont(); } @Override public Font getFontForTokenType(int type) { return smaliV2Style.getFont(); } private void loadV2Style() { setSyntaxScheme(smaliV2Style); } private void regBreakpointEvents() { bpShortcut = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0); UiUtils.addKeyBinding(SmaliArea.this, bpShortcut, "set break point", new AbstractAction() { private static final long serialVersionUID = -1111111202103170738L; @Override public void actionPerformed(ActionEvent e) { setBreakpoint(getCaretPosition()); } }); BreakpointManager.addListener((JClass) node, this::setBreakpointDisabled); } private void loadBreakpoints() { List<Integer> posList = BreakpointManager.getPositions((JClass) node); for (Integer integer : posList) { setBreakpoint(integer); } } @Override public void setBreakpoint(int pos) { int line; try { line = getLineOfOffset(pos); } catch (BadLocationException e) { LOG.error("Failed to get line by offset: {}", pos, e); return; } BreakpointLine bpLine = bpMap.remove(line); if (bpLine == null) { bpLine = new BreakpointLine(line); bpLine.setDisabled(false); bpMap.put(line, bpLine); if (!BreakpointManager.set((JClass) node, line)) { bpLine.setDisabled(true); } } else { BreakpointManager.remove((JClass) node, line); bpLine.remove(); } } @Override public void togglePosHighlight(int pos) { if (runningHighlightTag != null) { removeLineHighlight(runningHighlightTag); } try { int line = getLineOfOffset(pos); runningHighlightTag = addLineHighlight(line, DEBUG_LINE_COLOR); } catch (BadLocationException e) { LOG.error("Failed to get line by offset: {}", pos, e); } } private void setBreakpointDisabled(int pos) { try { int line = getLineOfOffset(pos); bpMap.computeIfAbsent(line, k -> new BreakpointLine(line)).setDisabled(true); } catch (BadLocationException e) { LOG.error("Failed to get line by offset: {}", pos, e); } } private class SmaliV2Style extends SyntaxScheme { public SmaliV2Style(SmaliArea smaliArea) { super(true); smaliArea.getContentPanel().getMainWindow().getEditorThemeManager().apply(smaliArea); updateTheme(); } public Font getFont() { return getContentPanel().getMainWindow().getSettings().getSmaliFont(); } public boolean refreshTheme() { boolean refresh = getSyntaxScheme() != this; if (refresh) { updateTheme(); } return refresh; } private void updateTheme() { Style[] mainStyles = getSyntaxScheme().getStyles(); Style[] styles = new Style[mainStyles.length]; for (int i = 0; i < mainStyles.length; i++) { Style mainStyle = mainStyles[i]; if (mainStyle == null) { styles[i] = new Style(); } else { // font will be hijacked by getFont & getFontForTokenType, // so it doesn't need to be set here. styles[i] = new Style(mainStyle.foreground, mainStyle.background, null); } } setStyles(styles); } @Override public void restoreDefaults(Font baseFont) { restoreDefaults(baseFont, true); } @Override public void restoreDefaults(Font baseFont, boolean fontStyles) { // Note: it's a hook for continuing using the editor theme, better don't remove it. } } private class BreakpointLine { Object highlightTag; GutterIconInfo iconInfo; boolean disabled; final int line; BreakpointLine(int line) { this.line = line; this.disabled = true; } void remove() { safeRemoveTrackingIcon(iconInfo); if (!this.disabled) { removeLineHighlight(highlightTag); } } void setDisabled(boolean disabled) { if (disabled) { if (!this.disabled) { safeRemoveTrackingIcon(iconInfo); removeLineHighlight(highlightTag); try { iconInfo = gutter.addLineTrackingIcon(line, ICON_BREAKPOINT_DISABLED); } catch (BadLocationException e) { LOG.error("Failed to add line tracking icon", e); } } } else { if (this.disabled) { safeRemoveTrackingIcon(this.iconInfo); try { iconInfo = gutter.addLineTrackingIcon(line, ICON_BREAKPOINT); highlightTag = addLineHighlight(line, BREAKPOINT_LINE_COLOR); } catch (BadLocationException e) { LOG.error("Failed to remove line tracking icon", e); } } } this.disabled = disabled; } } private void safeRemoveTrackingIcon(GutterIconInfo iconInfo) { if (gutter != null && iconInfo != null) { gutter.removeTrackingIcon(iconInfo); } } } @Override protected RTextAreaUI createRTextAreaUI() { // IconRowHeader won't fire an event when people click on it for adding/removing icons, // so our poor breakpoints won't be set if we don't hijack IconRowHeader. return new RSyntaxTextAreaUI(this) { @Override public EditorKit getEditorKit(JTextComponent tc) { return new RSyntaxTextAreaEditorKit() { private static final long serialVersionUID = -1111111202103170740L; @Override public IconRowHeader createIconRowHeader(RTextArea textArea) { return new FoldingAwareIconRowHeader((RSyntaxTextArea) textArea) { private static final long serialVersionUID = -1111111202103170739L; @Override public void mousePressed(MouseEvent e) { int offs = textArea.viewToModel2D(e.getPoint()); if (offs > -1) { model.setBreakpoint(offs); } } }; } }; } }; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/MouseHoverHighlighter.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/MouseHoverHighlighter.java
package jadx.gui.ui.codearea; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.text.Caret; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rtextarea.SmartHighlightPainter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JavaNode; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.utils.JNodeCache; class MouseHoverHighlighter extends MouseMotionAdapter { private static final Logger LOG = LoggerFactory.getLogger(MouseHoverHighlighter.class); private final CodeArea codeArea; private final CodeLinkGenerator codeLinkGenerator; private final SmartHighlightPainter highlighter; private Object tag; private int highlightedTokenOffset = -1; public MouseHoverHighlighter(CodeArea codeArea, CodeLinkGenerator codeLinkGenerator) { this.codeArea = codeArea; this.codeLinkGenerator = codeLinkGenerator; this.highlighter = new SmartHighlightPainter(); loadSettings(); } public void loadSettings() { highlighter.setPaint(codeArea.getMarkOccurrencesColor()); } @Override public void mouseMoved(MouseEvent e) { if (!addHighlight(e)) { removeHighlight(); } } private boolean addHighlight(MouseEvent e) { if (e.getModifiersEx() != 0) { return false; } Caret caret = codeArea.getCaret(); if (caret.getDot() != caret.getMark()) { // selection in action, highlight will interfere with selection return false; } try { Token token = codeArea.viewToToken(e.getPoint()); if (token == null) { return false; } int tokenOffset = token.getOffset(); if (tokenOffset == highlightedTokenOffset) { // don't repaint highlight return true; } JavaNode nodeAtOffset = codeLinkGenerator.getNodeAtOffset(tokenOffset); if (nodeAtOffset == null) { return false; } removeHighlight(); tag = codeArea.getHighlighter().addHighlight(tokenOffset, token.getEndOffset(), this.highlighter); highlightedTokenOffset = tokenOffset; updateToolTip(nodeAtOffset); return true; } catch (Exception exc) { LOG.error("Mouse hover highlight error", exc); return false; } } private void removeHighlight() { if (tag != null) { codeArea.getHighlighter().removeHighlight(tag); tag = null; highlightedTokenOffset = -1; updateToolTip(null); } } private void updateToolTip(JavaNode node) { MainWindow mainWindow = codeArea.getMainWindow(); if (node == null || mainWindow.getSettings().isDisableTooltipOnHover()) { codeArea.setToolTipText(null); return; } JNodeCache nodeCache = mainWindow.getCacheObject().getNodeCache(); JNode jNode = nodeCache.makeFrom(node); codeArea.setToolTipText(jNode.getTooltip()); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/CodePanel.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/CodePanel.java
package jadx.gui.ui.codearea; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JPopupMenu.Separator; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import javax.swing.event.PopupMenuEvent; import org.fife.ui.rtextarea.LineNumberFormatter; import org.fife.ui.rtextarea.LineNumberList; import org.fife.ui.rtextarea.RTextScrollPane; import jadx.api.ICodeInfo; import jadx.core.utils.StringUtils; import jadx.gui.settings.JadxSettings; import jadx.gui.settings.LineNumbersMode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.dialog.SearchDialog; import jadx.gui.utils.CaretPositionFix; import jadx.gui.utils.DefaultPopupMenuListener; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.MousePressedHandler; /** * A panel combining a {@link SearchBar} and a scollable {@link CodeArea} */ public class CodePanel extends JPanel { private static final long serialVersionUID = 1117721869391885865L; private final SearchBar searchBar; private final AbstractCodeArea codeArea; private final RTextScrollPane codeScrollPane; private boolean useSourceLines; public CodePanel(AbstractCodeArea codeArea) { this.codeArea = codeArea; this.searchBar = new SearchBar(codeArea); this.codeScrollPane = new RTextScrollPane(codeArea); setLayout(new BorderLayout()); setBorder(new EmptyBorder(0, 0, 0, 0)); add(searchBar, BorderLayout.NORTH); add(codeScrollPane, BorderLayout.CENTER); initLinesModeSwitch(); KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_F, UiUtils.ctrlButton()); UiUtils.addKeyBinding(codeArea, key, "SearchAction", new AbstractAction() { private static final long serialVersionUID = 71338030532869694L; @Override public void actionPerformed(ActionEvent e) { searchBar.showAndFocus(); } }); JMenuItem searchItem = new JMenuItem(); JMenuItem globalSearchItem = new JMenuItem(); AbstractAction searchAction = new AbstractAction(NLS.str("popup.search", "")) { @Override public void actionPerformed(ActionEvent e) { searchBar.toggle(); } }; AbstractAction globalSearchAction = new AbstractAction(NLS.str("popup.search_global", "")) { @Override public void actionPerformed(ActionEvent e) { MainWindow mainWindow = codeArea.getContentPanel().getMainWindow(); SearchDialog.searchText(mainWindow, codeArea.getSelectedText()); } }; searchItem.setAction(searchAction); globalSearchItem.setAction(globalSearchAction); Separator separator = new Separator(); JPopupMenu popupMenu = codeArea.getPopupMenu(); popupMenu.addPopupMenuListener(new DefaultPopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { String preferText = codeArea.getSelectedText(); if (!StringUtils.isEmpty(preferText)) { if (preferText.length() >= 23) { preferText = preferText.substring(0, 20) + " ..."; } searchAction.putValue(Action.NAME, NLS.str("popup.search", preferText)); globalSearchAction.putValue(Action.NAME, NLS.str("popup.search_global", preferText)); popupMenu.add(separator); popupMenu.add(globalSearchItem); popupMenu.add(searchItem); } else { popupMenu.remove(separator); popupMenu.remove(globalSearchItem); popupMenu.remove(searchItem); } } }); } public void loadSettings() { codeArea.loadSettings(); initLineNumbers(); } public void load() { codeArea.load(); initLineNumbers(); } private synchronized void initLineNumbers() { codeScrollPane.getGutter().setLineNumberFont(getSettings().getCodeFont()); LineNumbersMode mode = getLineNumbersMode(); if (mode == LineNumbersMode.DISABLE) { codeScrollPane.setLineNumbersEnabled(false); return; } useSourceLines = mode == LineNumbersMode.DEBUG; applyLineFormatter(); codeScrollPane.setLineNumbersEnabled(true); } private static final LineNumberFormatter SIMPLE_LINE_FORMATTER = new LineNumberFormatter() { @Override public String format(int lineNumber) { return Integer.toString(lineNumber); } @Override public int getMaxLength(int maxLineNumber) { return SourceLineFormatter.getNumberLength(maxLineNumber); } }; private synchronized void applyLineFormatter() { LineNumberFormatter linesFormatter = useSourceLines ? new SourceLineFormatter(codeArea.getCodeInfo()) : SIMPLE_LINE_FORMATTER; codeScrollPane.getGutter().setLineNumberFormatter(linesFormatter); } private LineNumbersMode getLineNumbersMode() { LineNumbersMode mode = getSettings().getLineNumbersMode(); boolean canShowDebugLines = canShowDebugLines(); if (mode == LineNumbersMode.AUTO) { mode = canShowDebugLines ? LineNumbersMode.DEBUG : LineNumbersMode.NORMAL; } else if (mode == LineNumbersMode.DEBUG && !canShowDebugLines) { // nothing to show => hide lines view mode = LineNumbersMode.DISABLE; } return mode; } private boolean canShowDebugLines() { if (codeArea instanceof SmaliArea) { return false; } ICodeInfo codeInfo = codeArea.getCodeInfo(); if (!codeInfo.hasMetadata()) { return false; } Map<Integer, Integer> lineMapping = codeInfo.getCodeMetadata().getLineMapping(); if (lineMapping.isEmpty()) { return false; } Set<Integer> uniqueDebugLines = new HashSet<>(lineMapping.values()); return uniqueDebugLines.size() > 3; } private void initLinesModeSwitch() { MousePressedHandler lineModeSwitch = new MousePressedHandler(ev -> { useSourceLines = !useSourceLines; applyLineFormatter(); }); for (Component gutterComp : codeScrollPane.getGutter().getComponents()) { if (gutterComp instanceof LineNumberList) { gutterComp.addMouseListener(lineModeSwitch); } } } public SearchBar getSearchBar() { return searchBar; } public AbstractCodeArea getCodeArea() { return codeArea; } public JScrollPane getCodeScrollPane() { return codeScrollPane; } public void refresh(CaretPositionFix caretFix) { JViewport viewport = getCodeScrollPane().getViewport(); Point viewPosition = viewport.getViewPosition(); codeArea.refresh(); initLineNumbers(); SwingUtilities.invokeLater(() -> { viewport.setViewPosition(viewPosition); caretFix.restore(); }); } private JadxSettings getSettings() { return this.codeArea.getContentPanel().getTabbedPane() .getMainWindow().getSettings(); } public void dispose() { codeArea.dispose(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/CodeLinkGenerator.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/CodeLinkGenerator.java
package jadx.gui.ui.codearea; import java.util.Objects; import javax.swing.event.HyperlinkEvent; import org.fife.ui.rsyntaxtextarea.LinkGenerator; import org.fife.ui.rsyntaxtextarea.LinkGeneratorResult; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.JavaNode; import jadx.gui.treemodel.JNode; import jadx.gui.utils.JumpPosition; public class CodeLinkGenerator implements LinkGenerator { private static final Logger LOG = LoggerFactory.getLogger(CodeLinkGenerator.class); private final CodeArea codeArea; private final JNode jNode; public CodeLinkGenerator(CodeArea codeArea) { this.codeArea = codeArea; this.jNode = codeArea.getNode(); } public JavaNode getNodeAtOffset(int offset) { try { if (!codeArea.getCodeInfo().hasMetadata()) { return null; } int sourceOffset = codeArea.adjustOffsetForWordToken(offset); if (sourceOffset == -1) { return null; } return codeArea.getJavaNodeAtOffset(offset); } catch (Exception e) { LOG.error("getNodeAtOffset error", e); return null; } } @Override public LinkGeneratorResult isLinkAtOffset(RSyntaxTextArea textArea, int offset) { try { if (!codeArea.getCodeInfo().hasMetadata()) { return null; } int sourceOffset = codeArea.adjustOffsetForWordToken(offset); if (sourceOffset == -1) { return null; } JumpPosition defPos = getJumpBySourceOffset(sourceOffset); if (defPos == null) { return null; } return new LinkGeneratorResult() { @Override public HyperlinkEvent execute() { return new HyperlinkEvent(defPos, HyperlinkEvent.EventType.ACTIVATED, null, defPos.getNode().makeLongString()); } @Override public int getSourceOffset() { return sourceOffset; } }; } catch (Exception e) { LOG.error("isLinkAtOffset error", e); return null; } } @Nullable private JumpPosition getJumpBySourceOffset(int sourceOffset) { final JumpPosition defPos = codeArea.getDefPosForNodeAtOffset(sourceOffset); if (defPos == null) { return null; } if (Objects.equals(defPos.getNode().getRootClass(), jNode) && defPos.getPos() == sourceOffset) { // ignore self jump return null; } return defPos; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/AbstractCodeContentPanel.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/AbstractCodeContentPanel.java
package jadx.gui.ui.codearea; import java.awt.Component; import org.jetbrains.annotations.Nullable; import jadx.gui.treemodel.JNode; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.ui.tab.TabbedPane; /** * The abstract base class for a content panel that show text based code or a.g. a resource */ public abstract class AbstractCodeContentPanel extends ContentPanel { private static final long serialVersionUID = 4685846894279064422L; protected AbstractCodeContentPanel(TabbedPane panel, JNode jnode) { super(panel, jnode); } public abstract @Nullable AbstractCodeArea getCodeArea(); public abstract Component getChildrenComponent(); public void scrollToPos(int pos) { AbstractCodeArea codeArea = getCodeArea(); if (codeArea != null) { codeArea.requestFocus(); codeArea.scrollToPos(pos); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/AbstractCodeArea.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/AbstractCodeArea.java
package jadx.gui.ui.codearea; import java.awt.Component; import java.awt.Dimension; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.DefaultCaret; import org.fife.ui.rsyntaxtextarea.AbstractTokenMakerFactory; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenMakerFactory; import org.fife.ui.rsyntaxtextarea.TokenTypes; import org.fife.ui.rtextarea.Gutter; import org.fife.ui.rtextarea.SearchContext; import org.fife.ui.rtextarea.SearchEngine; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.api.ICodeInfo; import jadx.core.utils.StringUtils; import jadx.core.utils.exceptions.JadxRuntimeException; import jadx.gui.jobs.IBackgroundTask; import jadx.gui.settings.JadxSettings; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JEditableNode; import jadx.gui.treemodel.JNode; import jadx.gui.ui.MainWindow; import jadx.gui.ui.action.JNodeAction; import jadx.gui.ui.panel.ContentPanel; import jadx.gui.utils.DefaultPopupMenuListener; import jadx.gui.utils.JumpPosition; import jadx.gui.utils.NLS; import jadx.gui.utils.UiUtils; import jadx.gui.utils.ui.DocumentUpdateListener; import jadx.gui.utils.ui.ZoomActions; public abstract class AbstractCodeArea extends RSyntaxTextArea { private static final long serialVersionUID = -3980354865216031972L; private static final Logger LOG = LoggerFactory.getLogger(AbstractCodeArea.class); public static final String SYNTAX_STYLE_SMALI = "text/smali"; static { TokenMakerFactory tokenMakerFactory = TokenMakerFactory.getDefaultInstance(); if (tokenMakerFactory instanceof AbstractTokenMakerFactory) { AbstractTokenMakerFactory atmf = (AbstractTokenMakerFactory) tokenMakerFactory; atmf.putMapping(SYNTAX_STYLE_SMALI, "jadx.gui.ui.codearea.SmaliTokenMaker"); // use simple token maker instead default PlainTextTokenMaker to avoid parse errors atmf.putMapping(SYNTAX_STYLE_NONE, "jadx.gui.ui.codearea.SimpleTokenMaker"); } else { throw new JadxRuntimeException("Unexpected TokenMakerFactory instance: " + tokenMakerFactory.getClass()); } SmaliFoldParser.register(); } protected ContentPanel contentPanel; protected JNode node; private final AtomicBoolean loaded = new AtomicBoolean(false); public AbstractCodeArea(ContentPanel contentPanel, JNode node) { this.contentPanel = contentPanel; this.node = Objects.requireNonNull(node); setMarkOccurrences(false); setFadeCurrentLineHighlight(true); setAntiAliasingEnabled(true); applyEditableProperties(node); loadSettings(); JadxSettings settings = contentPanel.getMainWindow().getSettings(); setLineWrap(settings.isCodeAreaLineWrap()); ZoomActions.register(this, settings, this::loadSettings); if (node instanceof JEditableNode) { JEditableNode editableNode = (JEditableNode) node; addSaveActions(editableNode); addChangeUpdates(editableNode); } else { addCaretActions(); addFastCopyAction(); } } private void applyEditableProperties(JNode node) { boolean editable = node.isEditable(); setEditable(editable); if (editable) { setCloseCurlyBraces(true); setCloseMarkupTags(true); setAutoIndentEnabled(true); setClearWhitespaceLinesEnabled(true); } } @Override protected JPopupMenu createPopupMenu() { JPopupMenu menu = new JPopupMenu(); if (node.isEditable()) { menu.add(createPopupMenuItem(getAction(UNDO_ACTION))); menu.add(createPopupMenuItem(getAction(REDO_ACTION))); menu.addSeparator(); menu.add(createPopupMenuItem(cutAction)); menu.add(createPopupMenuItem(copyAction)); menu.add(createPopupMenuItem(getAction(PASTE_ACTION))); menu.add(createPopupMenuItem(getAction(DELETE_ACTION))); menu.addSeparator(); menu.add(createPopupMenuItem(getAction(SELECT_ALL_ACTION))); } else { menu.add(createPopupMenuItem(copyAction)); menu.add(createPopupMenuItem(getAction(SELECT_ALL_ACTION))); } appendFoldingMenu(menu); appendWrapLineMenu(menu); return menu; } @Override protected void appendFoldingMenu(JPopupMenu popup) { // append code folding popup menu entry only if enabled if (isCodeFoldingEnabled()) { super.appendFoldingMenu(popup); } } private void appendWrapLineMenu(JPopupMenu popupMenu) { JadxSettings settings = contentPanel.getMainWindow().getSettings(); popupMenu.addSeparator(); JCheckBoxMenuItem wrapItem = new JCheckBoxMenuItem(NLS.str("popup.line_wrap"), getLineWrap()); wrapItem.setAction(new AbstractAction(NLS.str("popup.line_wrap")) { @Override public void actionPerformed(ActionEvent e) { boolean wrap = !getLineWrap(); settings.setCodeAreaLineWrap(wrap); settings.sync(); contentPanel.getTabbedPane().getTabs().forEach(v -> { if (v instanceof AbstractCodeContentPanel) { AbstractCodeArea codeArea = ((AbstractCodeContentPanel) v).getCodeArea(); setCodeAreaLineWrap(codeArea, wrap); if (v instanceof ClassCodeContentPanel) { codeArea = ((ClassCodeContentPanel) v).getSmaliCodeArea(); setCodeAreaLineWrap(codeArea, wrap); } } }); } }); popupMenu.add(wrapItem); popupMenu.addPopupMenuListener(new DefaultPopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { wrapItem.setState(getLineWrap()); } }); } private void setCodeAreaLineWrap(AbstractCodeArea codeArea, boolean wrap) { codeArea.setLineWrap(wrap); if (codeArea.isVisible()) { codeArea.repaint(); } } private void addCaretActions() { Caret caret = getCaret(); if (caret instanceof DefaultCaret) { ((DefaultCaret) caret).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); } this.addFocusListener(new FocusListener() { // fix caret missing bug. // when lost focus set visible to false, // and when regained set back to true will force // the caret to be repainted. @Override public void focusGained(FocusEvent e) { caret.setVisible(true); } @Override public void focusLost(FocusEvent e) { caret.setVisible(false); } }); addCaretListener(new CaretListener() { int lastPos = -1; String lastText = ""; @Override public void caretUpdate(CaretEvent e) { int pos = getCaretPosition(); if (lastPos != pos) { lastPos = pos; lastText = highlightCaretWord(lastText, pos); } } }); } /** * Ctrl+C will copy highlighted word */ private void addFastCopyAction() { addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_C && UiUtils.isCtrlDown(e)) { if (StringUtils.isEmpty(getSelectedText())) { UiUtils.copyToClipboard(getWordUnderCaret()); } } } }); } private void addSaveActions(JEditableNode node) { addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_S && UiUtils.isCtrlDown(e)) { node.save(AbstractCodeArea.this.getText()); node.setChanged(false); } } }); } private void addChangeUpdates(JEditableNode editableNode) { getDocument().addDocumentListener(new DocumentUpdateListener(ev -> { if (loaded.get()) { editableNode.setChanged(true); } })); } private String highlightCaretWord(String lastText, int pos) { String text = getWordByPosition(pos); if (StringUtils.isEmpty(text)) { highlightAllMatches(null); lastText = ""; } else if (!lastText.equals(text)) { highlightAllMatches(text); lastText = text; } return lastText; } @Nullable public String getWordUnderCaret() { return getWordByPosition(getCaretPosition()); } public @Nullable String getWordByPosition(int offset) { Token token = getWordTokenAtOffset(offset); if (token == null) { return null; } String str = token.getLexeme(); int len = str.length(); if (len > 2 && str.startsWith("\"") && str.endsWith("\"")) { return str.substring(1, len - 1); } return str; } /** * Return any word token (not whitespace or special symbol) at offset. * Select the previous token if the cursor at word end (current token already is whitespace) */ public @Nullable Token getWordTokenAtOffset(int offset) { try { int line = this.getLineOfOffset(offset); Token lineTokens = this.getTokenListForLine(line); Token token = null; Token prevToken = null; for (Token t = lineTokens; t != null && t.isPaintable(); t = t.getNextToken()) { if (t.containsPosition(offset)) { token = t; break; } prevToken = t; } if (token == null) { return null; } if (isWordToken(token)) { return token; } if (isWordToken(prevToken)) { return prevToken; } return null; } catch (Exception e) { LOG.error("Failed to get token at pos: {}", offset, e); return null; } } public static boolean isWordToken(@Nullable Token token) { if (token == null) { return false; } switch (token.getType()) { case TokenTypes.NULL: case TokenTypes.WHITESPACE: case TokenTypes.SEPARATOR: case TokenTypes.OPERATOR: case TokenTypes.FUNCTION: return false; case TokenTypes.IDENTIFIER: if (token.length() == 1) { char ch = token.charAt(0); return ch != ';' && ch != '.' && ch != ','; } return true; default: return true; } } public abstract ICodeInfo getCodeInfo(); public void load() { if (isLoaded()) { return; } IBackgroundTask loadTask = getLoadTask(); contentPanel.getMainWindow().getBackgroundExecutor().execute(loadTask); } /** * Implement in this method the code that loads and sets the content to be displayed * Call `setLoaded()` on load finish. */ public abstract IBackgroundTask getLoadTask(); public void setLoaded() { this.loaded.set(true); discardAllEdits(); // disable 'undo' action to empty state (before load) } public void setUnLoaded() { this.loaded.set(false); } public boolean isLoaded() { return loaded.get(); } /** * Implement in this method the code that reloads node from cache and sets the new content to be * displayed */ public abstract void refresh(); public static RSyntaxTextArea getDefaultArea(MainWindow mainWindow) { RSyntaxTextArea area = new RSyntaxTextArea(); area.setEditable(false); area.setCodeFoldingEnabled(false); area.setAntiAliasingEnabled(true); loadCommonSettings(mainWindow, area); return area; } public static void loadCommonSettings(MainWindow mainWindow, RSyntaxTextArea area) { JadxSettings settings = mainWindow.getSettings(); mainWindow.getEditorThemeManager().apply(area); area.setFont(settings.getCodeFont()); Gutter gutter = RSyntaxUtilities.getGutter(area); if (gutter != null) { gutter.setLineNumberFont(settings.getCodeFont()); } } public void loadSettings() { loadCommonSettings(contentPanel.getMainWindow(), this); } public void scrollToPos(int pos) { try { setCaretPosition(pos); centerCurrentLine(); forceCurrentLineHighlightRepaint(); } catch (Exception e) { LOG.warn("Can't scroll to position {}", pos, e); } } @SuppressWarnings("deprecation") public void centerCurrentLine() { JViewport viewport = (JViewport) SwingUtilities.getAncestorOfClass(JViewport.class, this); if (viewport == null) { return; } try { Rectangle r = modelToView(getCaretPosition()); if (r == null) { return; } int extentHeight = viewport.getExtentSize().height; Dimension viewSize = viewport.getViewSize(); if (viewSize == null) { return; } int viewHeight = viewSize.height; int y = Math.max(0, r.y - extentHeight / 2); y = Math.min(y, viewHeight - extentHeight); viewport.setViewPosition(new Point(0, y)); } catch (BadLocationException e) { LOG.debug("Can't center current line", e); } } /** * @param str - if null -> reset current highlights */ private void highlightAllMatches(@Nullable String str) { try { SearchContext context = new SearchContext(str); context.setMarkAll(true); context.setMatchCase(true); context.setWholeWord(true); SearchEngine.markAll(this, context); } catch (Throwable e) { // syntax parsing can fail for incorrect code LOG.debug("Search highlight failed", e); } } public @Nullable JumpPosition getCurrentPosition() { int pos = getCaretPosition(); if (pos == 0) { return null; } return new JumpPosition(node, pos); } public int getLineStartFor(int pos) throws BadLocationException { return getLineStartOffset(getLineOfOffset(pos)); } public String getLineAt(int pos) throws BadLocationException { return getLineText(getLineOfOffset(pos) + 1); } public String getLineText(int line) throws BadLocationException { int lineNum = line - 1; int startOffset = getLineStartOffset(lineNum); int endOffset = getLineEndOffset(lineNum); return getText(startOffset, endOffset - startOffset); } public ContentPanel getContentPanel() { return contentPanel; } public JNode getNode() { return node; } @Nullable public JClass getJClass() { if (node instanceof JClass) { return (JClass) node; } return null; } public boolean isDisposed() { return node == null; } public void dispose() { // clear internals try { setIgnoreRepaint(true); setText(""); setEnabled(false); setSyntaxEditingStyle(SYNTAX_STYLE_NONE); setLinkGenerator(null); for (MouseListener mouseListener : getMouseListeners()) { removeMouseListener(mouseListener); } for (MouseMotionListener mouseMotionListener : getMouseMotionListeners()) { removeMouseMotionListener(mouseMotionListener); } JPopupMenu popupMenu = getPopupMenu(); for (PopupMenuListener popupMenuListener : popupMenu.getPopupMenuListeners()) { popupMenu.removePopupMenuListener(popupMenuListener); } for (Component component : popupMenu.getComponents()) { if (component instanceof JMenuItem) { Action action = ((JMenuItem) component).getAction(); if (action instanceof JNodeAction) { ((JNodeAction) action).dispose(); } } } popupMenu.removeAll(); } catch (Throwable e) { LOG.debug("Error on code area dispose", e); } // code area reference can still be used somewhere in UI objects, // reset node reference to allow to GC jadx objects tree node = null; contentPanel = null; } @Override public Dimension getPreferredSize() { try { return super.getPreferredSize(); } catch (Exception e) { LOG.warn("Failed to calculate preferred size for code area", e); // copied from javax.swing.JTextArea.getPreferredSize (super call above) // as a fallback for returned null size Dimension d = new Dimension(400, 400); Insets insets = getInsets(); if (getColumns() != 0) { d.width = Math.max(d.width, getColumns() * getColumnWidth() + insets.left + insets.right); } if (getRows() != 0) { d.height = Math.max(d.height, getRows() * getRowHeight() + insets.top + insets.bottom); } return d; } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/SmaliFoldParser.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/SmaliFoldParser.java
package jadx.gui.ui.codearea; import java.util.ArrayList; import java.util.List; import java.util.NavigableSet; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.folding.Fold; import org.fife.ui.rsyntaxtextarea.folding.FoldParser; import org.fife.ui.rsyntaxtextarea.folding.FoldParserManager; import org.fife.ui.rsyntaxtextarea.folding.FoldType; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SmaliFoldParser implements FoldParser { private static final Logger LOG = LoggerFactory.getLogger(SmaliFoldParser.class); private static final Pattern CLASS_LINE_PATTERN = Pattern.compile("^\\.class\\b", Pattern.MULTILINE); private static final Pattern ENDMETHOD_LINE_PATTERN = Pattern.compile("^\\.end method\\b", Pattern.MULTILINE); private static final Pattern STARTMETHOD_LINE_PATTERN = Pattern.compile("^\\.method\\b", Pattern.MULTILINE); public static void register() { FoldParserManager.get().addFoldParserMapping(AbstractCodeArea.SYNTAX_STYLE_SMALI, new SmaliFoldParser()); } private SmaliFoldParser() { } @Override public List<Fold> getFolds(RSyntaxTextArea textArea) { List<Fold> classFolds = new ArrayList<>(); String text = textArea.getText(); List<Integer> classStartOffsets = getClassStartOffsets(text); NavigableSet<Integer> startMethodStartOffsets = getStartMethodStartOffsets(text); NavigableSet<Integer> endMethodEndOffsets = getEndMethodEndOffsets(text); for (int i = 0; i < classStartOffsets.size(); i++) { // Start offset of .class int startOffset = classStartOffsets.get(i); int classLimit; if (i < classStartOffsets.size() - 1) { classLimit = classStartOffsets.get(i + 1); } else { classLimit = text.length(); } // Get the last ".end method" before next .class or end of file Integer endOffset = endMethodEndOffsets.floor(classLimit); if (endOffset != null) { Fold classFold = createFold(textArea, startOffset, endOffset); if (classFold != null) { classFolds.add(classFold); // Start looking for .method after .class definition Integer startMethodStartOffset = startMethodStartOffsets.ceiling(startOffset); while (startMethodStartOffset != null && startMethodStartOffset < endOffset) { Integer endMethodEndOffset = endMethodEndOffsets.ceiling(startMethodStartOffset); if (endMethodEndOffset != null) { addFold(classFold, startMethodStartOffset, endMethodEndOffset); } // Look for next .method starting from last .end method startMethodStartOffset = startMethodStartOffsets.ceiling(endMethodEndOffset); } } } } return classFolds; } private static @Nullable Fold createFold(RSyntaxTextArea textArea, int startOffset, int endOffset) { try { Fold fold = new Fold(FoldType.CODE, textArea, startOffset); fold.setEndOffset(endOffset); return fold; } catch (Exception e) { LOG.error("Failed to create code fold", e); return null; } } private static void addFold(Fold parent, int startOffset, int endOffset) { try { Fold fold = parent.createChild(FoldType.CODE, startOffset); fold.setEndOffset(endOffset); } catch (Exception e) { LOG.error("Failed to add code fold", e); } } private List<Integer> getClassStartOffsets(String text) { List<Integer> startOffsets = new ArrayList<>(); Matcher matcher = CLASS_LINE_PATTERN.matcher(text); while (matcher.find()) { int startOffset = matcher.start(); startOffsets.add(startOffset); } return startOffsets; } private NavigableSet<Integer> getStartMethodStartOffsets(String text) { NavigableSet<Integer> startOffsets = new TreeSet<>(); Matcher matcher = STARTMETHOD_LINE_PATTERN.matcher(text); while (matcher.find()) { int startOffset = matcher.start(); startOffsets.add(startOffset); } return startOffsets; } private NavigableSet<Integer> getEndMethodEndOffsets(String text) { NavigableSet<Integer> endOffsets = new TreeSet<>(); Matcher matcher = ENDMETHOD_LINE_PATTERN.matcher(text); while (matcher.find()) { int endOffset = matcher.end(); endOffsets.add(endOffset); } return endOffsets; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/SmaliTokenMaker.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/SmaliTokenMaker.java
/* The following code was generated by JFlex */ package jadx.gui.ui.codearea; import java.io.*; import javax.swing.text.Segment; import org.fife.ui.rsyntaxtextarea.*; /** * SmaliTokenMaker * MartinKay@qq.com */ @SuppressWarnings("checkstyle:all") public class SmaliTokenMaker extends AbstractJFlexCTokenMaker { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int EOL_COMMENT = 1; public static final int YYINITIAL = 0; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\21\1\10\1\0\1\21\1\17\22\0\1\77\1\54\1\15" + "\1\20\1\1\1\35\1\35\1\7\1\37\1\37\1\35\1\40\1\35" + "\1\25\1\23\1\41\1\4\1\66\1\16\1\72\1\71\1\6\1\67" + "\1\6\1\76\1\3\1\45\1\50\1\55\1\54\1\56\1\35\1\36" + "\1\5\1\53\1\53\1\53\1\5\1\53\2\1\1\52\1\52\1\1" + "\1\47\6\1\1\52\2\1\1\51\3\1\1\52\1\37\1\11\1\37" + "\1\17\1\2\1\0\1\31\1\14\1\60\1\61\1\24\1\30\1\62" + "\1\42\1\44\1\70\1\73\1\32\1\65\1\13\1\63\1\43\1\74" + "\1\27\1\33\1\26\1\12\1\57\1\46\1\22\1\64\1\75\1\34" + "\1\17\1\34\1\35\uff81\0"; /** * Translates characters to character classes */ private static final char[] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int[] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\2\0\2\1\2\2\1\3\1\4\3\1\1\5\1\6" + "\1\7\12\1\1\10\1\11\1\12\4\1\2\13\1\12" + "\5\1\1\14\1\15\3\14\1\0\1\16\1\0\2\16" + "\1\3\1\17\1\0\1\3\5\1\2\5\1\20\1\21" + "\12\0\1\1\1\10\23\1\1\12\5\1\6\0\1\13" + "\1\0\15\1\5\0\1\21\1\0\1\22\1\3\1\23" + "\2\3\1\17\1\3\5\1\1\24\1\1\1\5\1\25" + "\1\5\20\0\35\1\7\0\10\1\1\0\2\1\5\0" + "\1\3\2\0\1\1\1\0\1\1\1\5\22\0\1\26" + "\1\27\3\1\1\0\7\1\1\24\1\1\1\0\2\1" + "\1\0\6\1\1\0\2\1\11\0\4\1\1\0\3\1" + "\1\24\2\0\1\1\1\24\2\0\1\30\1\0\1\3" + "\6\0\1\1\1\5\6\0\1\31\13\0\2\1\3\0" + "\2\1\1\0\3\1\3\0\2\1\1\0\6\1\1\0" + "\2\1\1\24\5\0\3\1\1\24\1\0\2\1\3\0" + "\1\1\5\0\1\3\6\0\1\5\7\0\1\31\4\0" + "\1\31\1\1\1\24\4\0\1\1\1\0\2\1\10\0" + "\1\1\1\0\3\1\1\0\2\1\1\24\3\0\1\32" + "\2\1\2\0\1\1\1\0\2\1\3\0\1\24\1\1" + "\23\0\1\1\7\0\2\1\10\0\1\24\1\1\1\24" + "\1\0\2\1\1\0\1\1\11\0\1\1\1\0\1\1" + "\2\0\1\1\22\0\1\24\3\0\1\1\12\0\1\1" + "\1\0\1\1\15\0\1\1\1\0\1\1\25\0\1\1" + "\22\0\1\1\10\0\1\24\26\0\1\24\2\0\1\1" + "\35\0\1\24\3\0\1\24\6\0\1\24\50\0\1\26"; private static int[] zzUnpackAction() { int[] result = new int[701]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int[] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int[] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\100\0\200\0\300\0\u0100\0\u0140\0\u0180\0\200" + "\0\u01c0\0\u0200\0\u0240\0\u0280\0\200\0\u02c0\0\u0300\0\u0340" + "\0\u0380\0\u03c0\0\u0400\0\u0440\0\u0480\0\u04c0\0\u0500\0\u0540" + "\0\200\0\200\0\u0580\0\u05c0\0\u0600\0\u0640\0\u0680\0\300" + "\0\u06c0\0\u0700\0\u0740\0\u0780\0\u07c0\0\u0800\0\u0840\0\u0880" + "\0\200\0\u08c0\0\u0900\0\u0940\0\u0980\0\u09c0\0\u0a00\0\u0a40" + "\0\u0a80\0\u0ac0\0\200\0\u0b00\0\u0b40\0\u0b80\0\u0bc0\0\u0c00" + "\0\u0c40\0\u0c80\0\u0cc0\0\u0d00\0\200\0\u0d40\0\u0d80\0\u0dc0" + "\0\u0e00\0\u0e40\0\u0e80\0\u0ec0\0\u0f00\0\u0f40\0\u0f80\0\u0fc0" + "\0\u1000\0\u1040\0\u1080\0\u10c0\0\u1100\0\u1140\0\u1180\0\u11c0" + "\0\u1200\0\u1240\0\u1280\0\u12c0\0\u1300\0\u1340\0\u1380\0\u13c0" + "\0\u1400\0\u1440\0\u1480\0\u14c0\0\u1500\0\u1540\0\u1580\0\u15c0" + "\0\u1600\0\u1640\0\u1680\0\u16c0\0\u1700\0\u1740\0\u1780\0\u17c0" + "\0\u1800\0\200\0\u1840\0\u06c0\0\u1880\0\u18c0\0\u1900\0\u1940" + "\0\u1980\0\u19c0\0\u1a00\0\u1a40\0\u1a80\0\u1ac0\0\u1b00\0\u1b40" + "\0\u1b80\0\u1bc0\0\u1c00\0\u1c40\0\u1c80\0\u1cc0\0\u1d00\0\u0a80" + "\0\u1d40\0\200\0\u1d80\0\u1dc0\0\u0b00\0\u1e00\0\u1e40\0\u1e80" + "\0\u1ec0\0\u1f00\0\u1f40\0\300\0\u1f80\0\u1fc0\0\200\0\u2000" + "\0\u2040\0\u2080\0\u20c0\0\u2100\0\u2140\0\u2180\0\u21c0\0\u2200" + "\0\u2240\0\u2280\0\u22c0\0\u2300\0\u2340\0\u2380\0\u23c0\0\u2400" + "\0\u2440\0\u2480\0\u24c0\0\u2500\0\u2540\0\u2580\0\u25c0\0\u2600" + "\0\u2640\0\u2680\0\u26c0\0\u2700\0\u2740\0\u2780\0\u27c0\0\u2800" + "\0\u2840\0\u2880\0\u28c0\0\u2900\0\u2940\0\u2980\0\u29c0\0\u2a00" + "\0\u2a40\0\u2a80\0\u2ac0\0\u2b00\0\u2b40\0\u2b80\0\u2bc0\0\u2c00" + "\0\u2c40\0\u2c80\0\u2cc0\0\u2d00\0\u2d40\0\u2d80\0\u2dc0\0\u2e00" + "\0\u2e40\0\u2e80\0\u2ec0\0\u2f00\0\u2f40\0\u2f80\0\u2fc0\0\u3000" + "\0\u3040\0\u3080\0\u30c0\0\u3100\0\u3140\0\u3180\0\u31c0\0\u3200" + "\0\u3240\0\u3280\0\u32c0\0\u3300\0\u3340\0\u3380\0\u33c0\0\u3400" + "\0\u3440\0\u3480\0\u34c0\0\u3500\0\u3540\0\u3580\0\u35c0\0\u3600" + "\0\u3640\0\u3680\0\u36c0\0\u3700\0\u3740\0\300\0\300\0\u3780" + "\0\u37c0\0\u3800\0\u3840\0\u3880\0\u38c0\0\u3900\0\u3940\0\u3980" + "\0\u39c0\0\u3a00\0\u3a40\0\u3a80\0\u3ac0\0\u3b00\0\u3b40\0\u3b80" + "\0\u3bc0\0\u3c00\0\u3c40\0\u3c80\0\u3cc0\0\u3d00\0\u3d40\0\u3d80" + "\0\u3dc0\0\u3e00\0\u3e40\0\u3e80\0\u3ec0\0\u3f00\0\u3f40\0\u3f80" + "\0\u3fc0\0\u4000\0\u4040\0\u4080\0\u40c0\0\u4100\0\u4140\0\u4180" + "\0\u41c0\0\u4200\0\u4240\0\u4280\0\u42c0\0\u4300\0\u4340\0\u4380" + "\0\u43c0\0\u4400\0\u4440\0\u4480\0\u44c0\0\u4500\0\u4540\0\u4580" + "\0\u45c0\0\u4600\0\u4640\0\u4680\0\u46c0\0\u4700\0\u4740\0\u4780" + "\0\u47c0\0\u4800\0\200\0\u4840\0\u4880\0\u48c0\0\u4900\0\u4940" + "\0\u4980\0\u49c0\0\u4a00\0\u4a40\0\u4a80\0\u4ac0\0\u4b00\0\u4b40" + "\0\u4b80\0\u4bc0\0\u4c00\0\u4c40\0\u4c80\0\u4cc0\0\u4d00\0\u4d40" + "\0\u4d80\0\u4dc0\0\u4e00\0\u4e40\0\u4e80\0\u4ec0\0\u4f00\0\u4f40" + "\0\u4f80\0\u4fc0\0\u5000\0\u5040\0\u5080\0\u50c0\0\u5100\0\u5140" + "\0\u5180\0\u51c0\0\u5200\0\u5240\0\u5280\0\u52c0\0\u5300\0\u5340" + "\0\u5380\0\u53c0\0\u5400\0\u5440\0\u5480\0\u54c0\0\u5500\0\u5540" + "\0\u5580\0\u55c0\0\u5600\0\u5640\0\u4400\0\u5680\0\u56c0\0\u5700" + "\0\u5740\0\u5780\0\u57c0\0\u5800\0\u5840\0\u5880\0\u58c0\0\u5900" + "\0\u5940\0\u5980\0\u59c0\0\u5a00\0\u5a40\0\u4a80\0\u5a80\0\u5ac0" + "\0\u5b00\0\u5b40\0\u5b80\0\u5bc0\0\u5c00\0\u5c40\0\u5c80\0\u5cc0" + "\0\u5d00\0\u5d40\0\u5d80\0\u5dc0\0\u5e00\0\u5e40\0\u5e80\0\u5ec0" + "\0\u5f00\0\u5f40\0\u5f80\0\u5fc0\0\u6000\0\u6040\0\u6080\0\u60c0" + "\0\u6100\0\u6140\0\u6180\0\u61c0\0\u6200\0\200\0\u6240\0\u6280" + "\0\u62c0\0\u6300\0\u6340\0\u6380\0\u63c0\0\u6400\0\u6440\0\u6480" + "\0\u64c0\0\u6500\0\u6540\0\u6580\0\u65c0\0\u6600\0\u6640\0\u6680" + "\0\u66c0\0\u6700\0\u6740\0\u6780\0\u67c0\0\u6800\0\u6840\0\u6880" + "\0\u68c0\0\u6900\0\u6940\0\u6980\0\u69c0\0\u6a00\0\u6a40\0\u6a80" + "\0\u6ac0\0\u6b00\0\u6b40\0\u6b80\0\u6bc0\0\u6c00\0\u6c40\0\u6c80" + "\0\u6cc0\0\u6d00\0\u6d40\0\u6d80\0\u6dc0\0\u6e00\0\u6e40\0\u6e80" + "\0\u6ec0\0\u6f00\0\u6f40\0\u6f80\0\u6fc0\0\u7000\0\u7040\0\u7080" + "\0\u70c0\0\u7100\0\u7140\0\u7180\0\u71c0\0\u7200\0\u7240\0\u7280" + "\0\u72c0\0\u7300\0\u7340\0\u7380\0\u73c0\0\u7400\0\u7440\0\u7480" + "\0\u74c0\0\u7500\0\u7540\0\u7580\0\u75c0\0\u7600\0\u7640\0\u7680" + "\0\u76c0\0\u7700\0\u7740\0\u7780\0\u77c0\0\u7800\0\u7840\0\u7880" + "\0\u78c0\0\u7900\0\u7940\0\u7980\0\u79c0\0\u7a00\0\u7a40\0\u7a80" + "\0\u7ac0\0\u7b00\0\u7b40\0\u7b80\0\u7bc0\0\u7c00\0\u7c40\0\u7c80" + "\0\u7cc0\0\u7d00\0\u7d40\0\u7d80\0\u7dc0\0\u7e00\0\u7e40\0\u7e80" + "\0\u7ec0\0\u7f00\0\u7f40\0\u7f80\0\u7fc0\0\u8000\0\u8040\0\u8080" + "\0\u80c0\0\u8100\0\u8140\0\u8180\0\u81c0\0\u8200\0\u8240\0\u8280" + "\0\u82c0\0\u8300\0\u8340\0\u8380\0\u83c0\0\u8400\0\u8440\0\u8480" + "\0\u84c0\0\u8500\0\u8540\0\u8580\0\u85c0\0\u8600\0\u8640\0\u8680" + "\0\u86c0\0\u8700\0\u8740\0\u8780\0\u87c0\0\u8800\0\u8840\0\u8880" + "\0\u88c0\0\u8900\0\u8940\0\u8980\0\u89c0\0\u8a00\0\u8a40\0\u8a80" + "\0\u8ac0\0\u8b00\0\u8b40\0\u8b80\0\u8bc0\0\u8c00\0\u8c40\0\u8c80" + "\0\u8cc0\0\u8d00\0\u8d40\0\u8d80\0\u8dc0\0\u8e00\0\u8e40\0\u8e80" + "\0\u8ec0\0\u8f00\0\u8f40\0\u8f80\0\u8fc0\0\u9000\0\u9040\0\u9080" + "\0\u90c0\0\u9100\0\u9140\0\u9180\0\u91c0\0\u9200\0\u9240\0\u9280" + "\0\u92c0\0\u9300\0\u9340\0\u9380\0\u93c0\0\u9400\0\u9440\0\u9480" + "\0\u94c0\0\u9500\0\u9540\0\u9580\0\u95c0\0\u9600\0\u9640\0\u9680" + "\0\u96c0\0\u9700\0\u9740\0\u9780\0\u97c0\0\u9800\0\u9840\0\u9880" + "\0\u98c0\0\u9900\0\u9940\0\u9980\0\u99c0\0\u9a00\0\u9a40\0\u9a80" + "\0\u9ac0\0\u9b00\0\u9b40\0\u9b80\0\u9bc0\0\u9c00\0\u9c40\0\u9c80" + "\0\u9cc0\0\u9d00\0\u9d40\0\u9d80\0\u9dc0\0\u9e00\0\u9e40\0\u9e80" + "\0\u9ec0\0\u9f00\0\u9f40\0\u9f80\0\u9fc0\0\ua000\0\ua040\0\ua080" + "\0\ua0c0\0\ua100\0\ua140\0\ua180\0\ua1c0\0\ua200\0\ua240\0\ua280" + "\0\ua2c0\0\ua300\0\ua340\0\ua380\0\ua3c0\0\ua400\0\ua440\0\ua480" + "\0\ua4c0\0\ua500\0\ua540\0\ua580\0\ua5c0\0\ua600\0\ua640\0\ua680" + "\0\ua6c0\0\ua700\0\ua740\0\ua780\0\ua7c0\0\ua800\0\ua840\0\ua880" + "\0\ua8c0\0\ua900\0\ua940\0\ua980\0\200"; private static int[] zzUnpackRowMap() { int[] result = new int[701]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int[] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int[] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\3\2\4\1\5\1\6\1\4\1\5\1\7\1\10" + "\1\3\1\11\1\12\1\13\1\14\1\5\1\3\1\15" + "\1\16\1\17\1\20\1\21\1\22\1\23\1\24\1\25" + "\1\26\1\27\1\30\1\31\1\3\1\32\1\31\1\3" + "\1\32\1\4\1\33\1\34\1\35\1\4\1\36\1\37" + "\1\40\2\41\3\32\1\42\1\43\1\44\1\45\1\46" + "\1\4\1\47\2\5\1\4\2\5\3\4\1\5\1\16" + "\10\50\1\51\17\50\1\52\11\50\1\53\3\50\1\54" + "\31\50\101\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\1\0\3\56" + "\2\5\1\56\1\5\2\0\4\56\1\0\1\5\1\0" + "\1\56\1\0\1\56\1\57\1\60\1\0\6\56\2\0" + "\1\56\3\0\3\56\1\0\2\56\1\0\3\56\3\0" + "\7\56\2\5\1\56\2\5\3\56\1\5\1\0\3\56" + "\2\5\1\56\1\5\2\0\4\56\1\0\1\5\1\0" + "\1\56\1\0\1\61\1\57\1\60\1\0\6\56\2\0" + "\1\56\3\0\3\56\1\0\2\56\1\0\3\56\3\0" + "\7\56\2\5\1\56\2\5\3\56\1\5\1\0\7\62" + "\1\63\1\64\1\65\66\62\1\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\5\4\1\66\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\2\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\67\1\0\3\4\1\70" + "\2\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\4\4\1\71\13\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\1\4" + "\1\72\4\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\1\0\10\14\1\73\1\74\3\14\1\75" + "\62\14\21\0\1\16\55\0\1\16\1\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\6\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\4\4\1\46\13\4\4\0\2\76\1\0\1\76" + "\7\0\1\76\5\0\1\77\2\0\1\100\1\101\1\102" + "\1\103\1\104\7\0\1\105\1\106\13\0\1\107\4\0" + "\1\110\2\76\1\0\2\76\3\0\1\76\2\0\6\4" + "\2\0\1\55\1\4\1\111\1\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\57\0\1\112\22\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\1\4\1\113\4\4\6\0\1\114" + "\2\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\115\1\0\5\4\1\116\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\3\4\1\117\1\120\1\4\6\0\2\4\1\121" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\1\4\1\122\1\123\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\1\4\1\124\4\4\6\0" + "\1\4\1\125\1\4\1\0\2\4\1\0\3\4\3\0" + "\2\4\1\126\1\127\14\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\4\4\1\130\13\4\2\0\6\4\2\0\1\55\1\131" + "\2\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\1\132\5\4\6\0\1\133\1\134\1\4\1\0\2\4" + "\1\0\3\4\3\0\3\4\1\127\1\4\1\135\12\4" + "\2\0\2\4\2\136\1\4\1\136\2\0\1\55\1\137" + "\2\4\1\0\1\136\3\0\1\4\1\0\1\4\1\0" + "\1\4\1\140\1\4\1\141\2\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\7\4\2\136\1\4\2\136" + "\3\4\1\136\2\0\6\4\2\0\1\55\1\4\1\142" + "\1\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\2\4\1\143\3\4\6\0\1\4\1\125\1\4\1\0" + "\2\4\1\0\3\4\3\0\3\4\1\127\14\4\27\0" + "\1\144\2\0\1\145\11\0\1\146\14\0\1\147\1\0" + "\1\150\16\0\6\36\2\0\1\55\3\36\1\0\1\36" + "\3\0\1\36\1\0\1\36\1\0\6\36\5\0\1\151" + "\3\36\1\0\2\36\1\152\3\36\3\0\20\36\26\0" + "\1\153\53\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\1\4\1\36\1\152\1\4\2\154\3\0\20\4" + "\2\0\2\4\2\136\1\4\1\136\2\0\1\55\3\4" + "\1\0\1\136\3\0\1\4\1\0\1\4\1\0\3\4" + "\1\155\2\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\4\4\1\156\2\4\2\136\1\4\2\136\3\4" + "\1\136\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\1\157" + "\2\4\1\0\2\4\1\0\3\4\3\0\4\4\1\160" + "\1\4\1\161\11\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\162\1\0\6\4" + "\6\0\2\4\1\163\1\0\2\4\1\0\3\4\3\0" + "\4\4\1\164\13\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\6\4" + "\6\0\3\4\1\0\2\4\1\0\3\4\3\0\4\4" + "\1\165\13\4\2\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\1\4\1\166" + "\4\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\1\167\2\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\6\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\4\4\1\170" + "\13\4\1\0\10\50\1\0\17\50\1\0\11\50\1\0" + "\3\50\1\0\31\50\26\0\1\171\15\0\1\172\61\0" + "\1\173\117\0\1\174\43\0\1\175\65\0\7\56\2\0" + "\4\56\1\0\1\56\1\0\1\56\1\0\1\56\1\0" + "\1\56\1\0\6\56\2\0\1\56\3\0\3\56\1\0" + "\2\56\1\0\3\56\3\0\20\56\4\0\2\76\1\0" + "\1\76\7\0\1\76\47\0\2\76\1\0\2\76\3\0" + "\1\76\1\0\3\56\2\176\1\56\1\176\2\0\4\56" + "\1\0\1\176\1\0\1\56\1\0\1\56\1\0\1\56" + "\1\177\6\56\2\0\1\56\1\0\1\177\1\0\3\56" + "\1\0\2\56\1\0\3\56\3\0\7\56\2\176\1\56" + "\2\176\3\56\1\176\1\0\3\56\4\200\2\0\3\56" + "\1\200\1\0\1\200\1\0\1\56\1\0\1\56\1\0" + "\1\200\1\0\2\56\2\200\2\56\2\0\1\56\3\0" + "\3\56\1\0\2\56\1\0\2\56\1\200\3\0\1\56" + "\2\200\4\56\2\200\1\56\2\200\3\56\1\200\1\0" + "\7\201\1\202\1\0\67\201\7\0\1\202\70\0\4\201" + "\1\203\1\201\1\204\1\205\1\0\1\62\1\206\3\62" + "\1\203\7\201\3\62\35\201\1\203\1\204\1\201\1\204" + "\1\203\5\201\1\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\6\4\6\0" + "\1\207\2\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\6\4\6\0\3\4\1\0" + "\1\210\1\4\1\0\3\4\3\0\3\4\1\211\14\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\1\212\5\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\1\213\5\4\6\0\1\4\1\214\1\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\6\4\6\0\2\4\1\215\1\0\2\4" + "\1\0\3\4\3\0\20\4\1\0\11\73\1\216\3\73" + "\1\217\66\73\1\14\1\73\2\14\1\0\1\14\1\220" + "\4\14\7\73\3\14\35\73\2\14\1\73\2\14\5\73" + "\3\56\2\76\1\56\1\76\2\0\4\56\1\0\1\76" + "\1\0\1\56\1\0\1\56\1\0\1\60\1\0\6\56" + "\2\0\1\56\3\0\3\56\1\0\2\56\1\0\3\56" + "\3\0\7\56\2\76\1\56\2\76\3\56\1\76\14\0" + "\1\221\110\0\1\222\117\0\1\223\46\0\1\224\13\0" + "\1\225\114\0\1\226\16\0\1\227\26\0\1\230\30\0" + "\1\231\17\0\1\232\43\0\1\233\1\0\1\234\133\0" + "\1\235\43\0\1\236\1\237\71\0\1\240\54\0\6\4" + "\2\0\1\55\1\241\2\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\2\112\2\0\1\112" + "\4\0\3\112\5\0\1\112\1\0\1\112\1\0\6\112" + "\6\0\3\112\1\0\2\112\1\0\3\112\1\0\11\112" + "\2\0\1\112\2\0\3\112\3\0\6\4\2\0\1\55" + "\1\242\2\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\3\4\1\243\2\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\1\4\1\244\4\4\6\0\3\4\1\0\2\4\1\0" + "\3\4\3\0\20\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\1\245" + "\5\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\6\4\1\246\11\4\2\0\6\4\2\0\1\55\1\247" + "\2\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\4\4\1\250\1\4" + "\6\0\3\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\4\4\1\251\13\4\2\0" + "\6\4\2\0\1\55\1\4\1\252\1\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\4\4\1\253\1\4" + "\6\0\3\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\1\4\1\254\1\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\6\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\2\4\1\166" + "\15\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\5\4\1\255\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\1\4\1\256\4\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\1\257\2\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\2\4\1\246\15\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\257\1\0\6\4" + "\6\0\3\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\1\4\1\260\1\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\6\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\2\4\1\261\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\1\4\1\262\1\4\1\263\2\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\1\4\1\264\2\4\1\264\1\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\1\257\2\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\3\4\1\265\2\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\1\4\1\266\1\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\2\4" + "\2\136\1\4\1\136\2\0\1\55\3\4\1\0\1\136" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\7\4\2\136\1\4" + "\2\136\3\4\1\136\2\0\6\4\2\0\1\55\2\4" + "\1\267\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\2\4" + "\1\270\1\0\2\4\1\0\3\4\3\0\4\4\1\271" + "\13\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\1\4\1\272\16\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\1\273\4\4\1\274\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\1\275\17\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\276\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\30\0\1\277\77\0" + "\1\300\103\0\1\301\75\0\1\302\31\0\1\303\77\0" + "\1\304\15\0\6\151\3\0\3\151\1\0\1\151\3\0" + "\1\151\1\0\1\151\1\0\6\151\5\0\4\151\1\0" + "\2\151\1\152\3\151\3\0\20\151\57\0\1\32\22\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\1\4\1\305\4\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\4\4\1\306\1\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\307" + "\1\0\6\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\2\0\6\4\2\0\1\55\1\4\1\310" + "\1\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\1\4" + "\1\311\1\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\1\4\1\312\16\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\1\246\17\4\2\0\6\4\2\0" + "\1\55\1\313\2\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\6\4\6\0\3\4\1\0\2\4\1\0" + "\3\4\3\0\20\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\1\314" + "\5\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\315\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\4\4\1\246\1\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\1\4\1\316\1\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\1\317\17\4\44\0\1\320\66\0" + "\1\321\73\0\1\322\117\0\1\323\34\0\4\324\5\0" + "\1\324\1\0\1\324\5\0\1\324\3\0\2\324\21\0" + "\1\324\4\0\2\324\4\0\2\324\1\0\2\324\3\0" + "\1\324\1\0\3\56\2\176\1\56\1\176\2\0\4\56" + "\1\0\1\176\1\0\1\56\1\0\1\56\1\0\1\56" + "\1\0\6\56\2\0\1\56\3\0\3\56\1\0\2\56" + "\1\0\3\56\3\0\7\56\2\176\1\56\2\176\3\56" + "\1\176\4\0\2\176\1\0\1\176\7\0\1\176\47\0" + "\2\176\1\0\2\176\3\0\1\176\1\0\7\201\1\63" + "\1\0\73\201\1\204\1\201\1\204\1\202\1\0\5\201" + "\1\204\47\201\2\204\1\201\2\204\11\201\1\62\1\201" + "\1\62\1\202\1\0\5\201\1\62\47\201\2\62\1\201" + "\2\62\10\201\4\325\1\63\1\0\3\201\1\325\1\201" + "\1\325\5\201\1\325\3\201\2\325\21\201\1\325\4\201" + "\2\325\4\201\2\325\1\201\2\325\3\201\1\325\1\201" + "\1\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\1\4\1\264\4\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\326\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\327" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\2\4" + "\1\330\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\331\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\2\4\1\332\15\4\1\0\10\73\1\0\72\73\4\333" + "\2\73\1\216\2\73\1\333\1\217\1\333\5\73\1\333" + "\3\73\2\333\21\73\1\333\4\73\2\333\4\73\2\333" + "\1\73\2\333\3\73\1\333\1\73\61\0\1\334\51\0" + "\1\335\26\0\1\336\41\0\1\337\66\0\1\340\113\0" + "\1\341\63\0\1\342\144\0\1\343\62\0\1\344\65\0" + "\1\345\60\0\1\346\150\0\1\347\43\0\1\350\30\0" + "\1\351\62\0\1\352\62\0\1\353\102\0\1\354\74\0" + "\1\355\52\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\6\4\1\356\11\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\357\1\0\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\1\4\1\360\1\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\4\4\1\361\13\4\2\0\6\4\2\0\1\55\1\362" + "\2\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\363\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\2\4\1\364\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\5\4\1\242\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\2\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\3\4\1\365" + "\2\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\3\4\1\366\2\4" + "\6\0\3\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\4\4\1\367\1\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\4\4\1\370\13\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\1\371\5\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\3\4\1\372\2\4\6\0\3\4\1\0\2\4\1\0" + "\3\4\3\0\20\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\1\373" + "\5\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\3\4\1\374\14\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\375\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\6\4\6\0\2\4\1\376\1\0\2\4\1\0" + "\3\4\3\0\20\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\1\377" + "\5\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\u0100\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\1\4\1\u0101\4\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\1\u0102\5\4\6\0\3\4\1\0\2\4\1\0" + "\3\4\3\0\20\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\4\4" + "\1\377\1\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\2\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\6\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\1\u0103\17\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\1\u0104\5\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\6\4\6\0\3\4\1\0\2\4\1\0" + "\3\4\3\0\14\4\1\u0105\3\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\u0106" + "\1\u0107\6\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\2\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\1\u0108\5\4" + "\6\0\3\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\4\4\1\u0109\13\4\14\0" + "\1\u010a\10\0\1\u010b\5\0\1\u010c\27\0\1\u010c\101\0" + "\1\u010d\42\0\1\u010e\116\0\1\u010f\57\0\1\u0110\64\0" + "\1\u0111\112\0\1\u0112\52\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\3\4" + "\1\u0113\2\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\2\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\3\4\1\u0114" + "\2\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\6\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\1\4\1\u0115\16\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\5\4\1\u0116\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\u0117\4\4\1\u0118\1\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\3\4\1\u0118\14\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\4\4\1\u0119\1\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\2\4\1\u011a\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\4\4\1\u011b\13\4\33\0\1\u011c\11\0\1\u011d\34\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\2\4\1\u011e\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\u011f" + "\1\0\6\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\46\0\1\u0120\56\0\1\320\116\0\1\u0121" + "\57\0\1\u0122\57\0\4\u0123\5\0\1\u0123\1\0\1\u0123" + "\5\0\1\u0123\3\0\2\u0123\21\0\1\u0123\4\0\2\u0123" + "\4\0\2\u0123\1\0\2\u0123\3\0\1\u0123\1\0\3\201" + "\4\u0124\1\63\1\0\3\201\1\u0124\1\201\1\u0124\5\201" + "\1\u0124\3\201\2\u0124\21\201\1\u0124\4\201\2\u0124\4\201" + "\2\u0124\1\201\2\u0124\3\201\1\u0124\1\201\31\0\1\u0125" + "\12\0\1\u0126\63\0\1\u0127\1\0\1\u0128\11\0\1\u0129" + "\14\0\1\u012a\17\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\0\6\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\1\u012b\17\4" + "\33\0\1\u0128\11\0\1\u0129\34\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\3\4\1\u012b\14\4\1\0\3\73\4\u012c\2\73\1\216" + "\2\73\1\u012c\1\217\1\u012c\5\73\1\u012c\3\73\2\u012c" + "\21\73\1\u012c\4\73\2\u012c\4\73\2\u012c\1\73\2\u012c" + "\3\73\1\u012c\1\73\77\0\1\u012d\26\0\1\u012e\115\0" + "\1\u012f\65\0\1\u0130\130\0\1\u0131\45\0\1\u0132\72\0" + "\1\u0133\104\0\1\u0134\72\0\1\u0135\102\0\1\u0136\77\0" + "\1\u0137\102\0\1\u0138\76\0\1\u0139\141\0\1\u013a\36\0" + "\1\u013b\125\0\1\u013c\52\0\1\u013d\106\0\1\u013e\36\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\5\4\1\u013f\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\6\4\6\0\3\4\1\0\1\214\1\4\1\0" + "\3\4\3\0\20\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\4\1\0\1\4" + "\1\u0140\4\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\31\0\1\u0141\1\0\1\u011c\11\0\1\u011d" + "\14\0\1\u0142\17\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\u0143\6\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\1\u0144\5\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\4\4\1\356\1\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\u0145\1\u0146" + "\6\4\6\0\3\4\1\0\2\4\1\0\3\4\3\0" + "\20\4\2\0\6\4\2\0\1\55\3\4\1\0\1\4" + "\3\0\1\4\1\0\1\4\1\0\1\u0147\5\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\2\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\1\4\1\u0148\4\4\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\6\4\6\0\3\4\1\0\2\4\1\0" + "\3\4\3\0\5\4\1\u0149\12\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\u014a\6\4\6\0\3\4\1\0\2\4\1\0\3\4" + "\3\0\20\4\2\0\6\4\2\0\1\55\3\4\1\0" + "\1\4\3\0\1\4\1\0\1\4\1\u014b\6\4\6\0" + "\3\4\1\0\2\4\1\0\3\4\3\0\20\4\31\0" + "\1\u0141\1\0\1\u011c\11\0\1\u014c\14\0\1\u0142\17\0" + "\6\4\2\0\1\55\3\4\1\0\1\4\3\0\1\4" + "\1\0\1\4\1\0\6\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\1\4\1\u014d\16\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\6\4\6\0\2\4\1\u014e\1\0\2\4" + "\1\0\3\4\3\0\20\4\33\0\1\u011c\11\0\1\u014f" + "\34\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\4\1\0\5\4\1\u0150\6\0\3\4" + "\1\0\2\4\1\0\3\4\3\0\20\4\2\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" + "\1\4\1\0\6\4\6\0\1\u0151\2\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\2\0\6\4\2\0\1\55" + "\3\4\1\0\1\4\3\0\1\4\1\0\1\4\1\0" + "\3\4\1\u0152\2\4\6\0\3\4\1\0\2\4\1\0" + "\3\4\3\0\20\4\2\0\6\4\2\0\1\55\3\4" + "\1\0\1\4\3\0\1\4\1\0\1\u0153\1\0\6\4" + "\6\0\3\4\1\0\2\4\1\0\3\4\3\0\20\4" + "\2\0\6\4\2\0\1\55\3\4\1\0\1\4\3\0" + "\1\4\1\0\1\u0154\1\0\6\4\6\0\3\4\1\0" + "\2\4\1\0\3\4\3\0\20\4\2\0\6\4\2\0" + "\1\55\3\4\1\0\1\4\3\0\1\4\1\0\1\4" + "\1\0\1\4\1\u0155\4\4\6\0\3\4\1\0\2\4" + "\1\0\3\4\3\0\20\4\27\0\1\u0156\52\0\6\4" + "\2\0\1\55\3\4\1\0\1\4\3\0\1\4\1\0" +
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
true
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/SimpleTokenMaker.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/SimpleTokenMaker.java
package jadx.gui.ui.codearea; import javax.swing.text.Segment; import org.fife.ui.rsyntaxtextarea.Token; import org.fife.ui.rsyntaxtextarea.TokenImpl; import org.fife.ui.rsyntaxtextarea.TokenMakerBase; import org.fife.ui.rsyntaxtextarea.TokenTypes; /** * Very simple token maker to use only one token per line without any parsing */ @SuppressWarnings("unused") // class registered by name in {@link AbstractCodeArea} public class SimpleTokenMaker extends TokenMakerBase { private final TokenImpl token; public SimpleTokenMaker() { token = new TokenImpl(); token.setType(TokenTypes.IDENTIFIER); } @Override public Token getTokenList(Segment segment, int initialTokenType, int startOffset) { token.text = segment.array; token.textOffset = startOffset; token.textCount = segment.count; token.setOffset(startOffset); return token; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/mode/JCodeMode.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/mode/JCodeMode.java
package jadx.gui.ui.codearea.mode; import javax.swing.Icon; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; import org.jetbrains.annotations.Nullable; import jadx.api.DecompilationMode; import jadx.api.ICodeInfo; import jadx.core.dex.nodes.ClassNode; import jadx.gui.treemodel.JClass; import jadx.gui.treemodel.JNode; public class JCodeMode extends JNode { private final JClass jCls; private final DecompilationMode mode; private @Nullable ICodeInfo codeInfo; public JCodeMode(JClass jClass, DecompilationMode mode) { this.jCls = jClass; this.mode = mode; } @Override public JClass getJParent() { return jCls.getJParent(); } @Override public Icon getIcon() { return jCls.getIcon(); } @Override public String makeString() { return jCls.makeString(); } @Override public ICodeInfo getCodeInfo() { if (codeInfo != null) { return codeInfo; } ClassNode cls = jCls.getCls().getClassNode(); codeInfo = cls.decompileWithMode(mode); return codeInfo; } @Override public String getSyntaxName() { return SyntaxConstants.SYNTAX_STYLE_JAVA; } @Override public String getName() { return jCls.getName(); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/RSTABundledTheme.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/RSTABundledTheme.java
package jadx.gui.ui.codearea.theme; import java.io.InputStream; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.Theme; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RSTABundledTheme implements IEditorTheme { private static final Logger LOG = LoggerFactory.getLogger(RSTABundledTheme.class); private static final String RSTA_THEME_PATH = "/org/fife/ui/rsyntaxtextarea/themes/"; private final String name; private Theme loadedTheme; public RSTABundledTheme(String name) { this.name = name; } @Override public String getId() { return "RSTA:" + name; } @Override public String getName() { return name; } @Override public void load() { String path = RSTA_THEME_PATH + name + ".xml"; try { try (InputStream is = RSTABundledTheme.class.getResourceAsStream(path)) { loadedTheme = Theme.load(is); } } catch (Throwable t) { LOG.error("Failed to load editor theme: {}", path, t); loadedTheme = new Theme(new RSyntaxTextArea()); } } @Override public void apply(RSyntaxTextArea textArea) { loadedTheme.apply(textArea); } @Override public void unload() { loadedTheme = null; } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/EditorThemeManager.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/EditorThemeManager.java
package jadx.gui.ui.codearea.theme; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.utils.StringUtils; import jadx.gui.settings.JadxSettings; public class EditorThemeManager { private static final Logger LOG = LoggerFactory.getLogger(EditorThemeManager.class); private final List<IEditorTheme> themes = new ArrayList<>(); private final Map<String, IEditorTheme> themesMap = new HashMap<>(); private IEditorTheme currentTheme = new FallbackEditorTheme(); public EditorThemeManager(JadxSettings settings) { registerThemes(); if (StringUtils.isEmpty(settings.getEditorTheme())) { // set default theme IEditorTheme defaultTheme = themes.get(0); settings.setEditorTheme(defaultTheme.getId()); } } private void registerThemes() { registerTheme(new DynamicCodeAreaTheme()); registerTheme(new RSTABundledTheme("default")); registerTheme(new RSTABundledTheme("eclipse")); registerTheme(new RSTABundledTheme("idea")); registerTheme(new RSTABundledTheme("vs")); registerTheme(new RSTABundledTheme("dark")); registerTheme(new RSTABundledTheme("monokai")); registerTheme(new RSTABundledTheme("druid")); } public void registerTheme(IEditorTheme editorTheme) { IEditorTheme prev = themesMap.put(editorTheme.getId(), editorTheme); if (prev != null) { themes.remove(prev); } themes.add(editorTheme); } public synchronized void setTheme(String id) { if (currentTheme.getId().equals(id)) { // already set return; } // resolve new IEditorTheme newTheme = themesMap.get(id); if (newTheme == null) { LOG.warn("Failed to resolve editor theme: {}", id); return; } // unload current unload(); // load new try { newTheme.load(); } catch (Throwable t) { LOG.warn("Failed to load editor theme: {}", id, t); } currentTheme = newTheme; } public void apply(RSyntaxTextArea textArea) { this.currentTheme.apply(textArea); } public ThemeIdAndName[] getThemeIdNameArray() { return themes.stream() .map(EditorThemeManager::toThemeIdAndName) .toArray(ThemeIdAndName[]::new); } public ThemeIdAndName getCurrentThemeIdName() { return toThemeIdAndName(currentTheme); } private static ThemeIdAndName toThemeIdAndName(IEditorTheme t) { return new ThemeIdAndName(t.getId(), t.getName()); } public void unload() { try { currentTheme.unload(); } catch (Throwable t) { LOG.warn("Failed to unload editor theme: {}", currentTheme.getId(), t); } } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false
skylot/jadx
https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/FallbackEditorTheme.java
jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/FallbackEditorTheme.java
package jadx.gui.ui.codearea.theme; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.Theme; public class FallbackEditorTheme implements IEditorTheme { private Theme baseTheme; @Override public String getId() { return "fallback"; } @Override public String getName() { return "Fallback"; } @Override public void load() { baseTheme = new Theme(new RSyntaxTextArea()); } @Override public void apply(RSyntaxTextArea textArea) { baseTheme.apply(textArea); } }
java
Apache-2.0
7bbb58863b8a80c0b862425d2701d23be40aeae8
2026-01-04T14:45:57.033910Z
false