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/ui/codearea/theme/DynamicCodeAreaTheme.java | jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/DynamicCodeAreaTheme.java | package jadx.gui.ui.codearea.theme;
import java.awt.Color;
import javax.swing.UIManager;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
import org.fife.ui.rsyntaxtextarea.SyntaxScheme;
import org.fife.ui.rsyntaxtextarea.Token;
import org.fife.ui.rtextarea.Gutter;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
/**
* Mix current UI theme colors and apply to code area theme.
*/
public class DynamicCodeAreaTheme implements IEditorTheme {
@Override
public String getId() {
return "DynamicCodeAreaTheme";
}
@Override
public String getName() {
return NLS.str("preferences.dynamic_editor_theme");
}
public void apply(RSyntaxTextArea textArea) {
// Get the current colors from UIManager
Color themeBackground = UIManager.getColor("Panel.background");
Color themeForeground = UIManager.getColor("Panel.foreground");
Color separatorForeground = UIManager.getColor("Separator.foreground");
Color editorSelectionBackground = UIManager.getColor("EditorPane.selectionBackground");
Color caretForeground = UIManager.getColor("EditorPane.caretForeground");
SyntaxScheme scheme = textArea.getSyntaxScheme();
boolean isDarkTheme = UiUtils.isDarkTheme(themeBackground);
// Background colors based on the theme
Color editorBackground = isDarkTheme ? themeBackground : Color.WHITE; // Use white for light theme
Color lineHighlight = isDarkTheme
? UiUtils.adjustBrightness(themeBackground, 1.2f)
: Color.decode("#EBECF0"); // Light gray for light theme
Color lineNumberForeground = UIManager.getColor("Label.foreground");
// Add these lines after setting the background colors
Color selectionColor = isDarkTheme
? new Color(51, 153, 255, 90) // Semi-transparent blue for dark theme
: new Color(51, 153, 255, 50); // Lighter blue for light theme
Color markAllHighlightColor = isDarkTheme ? Color.decode("#32593D") : Color.decode("#ffc800");
Color matchedBracketBackground = isDarkTheme ? UiUtils.adjustBrightness(Color.decode("#3B514D"), 1.2f) : Color.decode("#93D9D9");
Color markOccurrencesColor = UiUtils.adjustBrightness(editorSelectionBackground, isDarkTheme ? 0.6f : 1.4f);
// Set the syntax colors for the theme
if (isDarkTheme) {
Color dataTypeColor = Color.decode("#4EC9B0");
scheme.getStyle(Token.COMMENT_EOL).foreground = Color.decode("#57A64A");
scheme.getStyle(Token.COMMENT_MULTILINE).foreground = Color.decode("#57A64A");
scheme.getStyle(Token.COMMENT_DOCUMENTATION).foreground = Color.decode("#57A64A");
scheme.getStyle(Token.COMMENT_KEYWORD).foreground = Color.decode("#57A64A");
scheme.getStyle(Token.COMMENT_MARKUP).foreground = Color.decode("#57A64A");
scheme.getStyle(Token.RESERVED_WORD).foreground = Color.decode("#569CD6");
scheme.getStyle(Token.RESERVED_WORD_2).foreground = dataTypeColor;
scheme.getStyle(Token.FUNCTION).foreground = Color.decode("#DCDCAA");
scheme.getStyle(Token.ANNOTATION).foreground = Color.decode("#B3AE60");
scheme.getStyle(Token.LITERAL_NUMBER_DECIMAL_INT).foreground = Color.decode("#D7BA7D");
scheme.getStyle(Token.LITERAL_NUMBER_FLOAT).foreground = Color.decode("#D7BA7D");
scheme.getStyle(Token.LITERAL_NUMBER_HEXADECIMAL).foreground = Color.decode("#D7BA7D");
scheme.getStyle(Token.LITERAL_BOOLEAN).foreground = Color.decode("#569CD6");
scheme.getStyle(Token.LITERAL_CHAR).foreground = Color.decode("#CE9178");
scheme.getStyle(Token.LITERAL_STRING_DOUBLE_QUOTE).foreground = Color.decode("#CE9178");
scheme.getStyle(Token.DATA_TYPE).foreground = dataTypeColor;
scheme.getStyle(Token.OPERATOR).foreground = Color.WHITE;
scheme.getStyle(Token.SEPARATOR).foreground = Color.WHITE;
scheme.getStyle(Token.IDENTIFIER).foreground = themeForeground;
// XML-specific colors for dark theme
scheme.getStyle(Token.MARKUP_TAG_DELIMITER).foreground = Color.decode("#808080"); // Gray for < > /
scheme.getStyle(Token.MARKUP_TAG_NAME).foreground = Color.decode("#569CD6"); // Blue for tag names
scheme.getStyle(Token.MARKUP_TAG_ATTRIBUTE).foreground = Color.decode("#9CDCFE"); // Light blue for attributes
scheme.getStyle(Token.MARKUP_TAG_ATTRIBUTE_VALUE).foreground = Color.decode("#CE9178"); // Orange for values
} else {
Color dataTypeColor = Color.decode("#267F99");
scheme.getStyle(Token.COMMENT_EOL).foreground = Color.decode("#008000");
scheme.getStyle(Token.COMMENT_MULTILINE).foreground = Color.decode("#008000");
scheme.getStyle(Token.COMMENT_DOCUMENTATION).foreground = Color.decode("#008000");
scheme.getStyle(Token.COMMENT_KEYWORD).foreground = Color.decode("#008000");
scheme.getStyle(Token.COMMENT_MARKUP).foreground = Color.decode("#008000");
scheme.getStyle(Token.RESERVED_WORD).foreground = Color.decode("#0000FF");
scheme.getStyle(Token.RESERVED_WORD_2).foreground = dataTypeColor;
scheme.getStyle(Token.FUNCTION).foreground = Color.decode("#795E26");
scheme.getStyle(Token.ANNOTATION).foreground = Color.decode("#9E8809");
scheme.getStyle(Token.LITERAL_NUMBER_DECIMAL_INT).foreground = Color.decode("#098658");
scheme.getStyle(Token.LITERAL_NUMBER_FLOAT).foreground = Color.decode("#098658");
scheme.getStyle(Token.LITERAL_NUMBER_HEXADECIMAL).foreground = Color.decode("#098658");
scheme.getStyle(Token.LITERAL_BOOLEAN).foreground = Color.decode("#0451A5");
scheme.getStyle(Token.LITERAL_CHAR).foreground = Color.decode("#067d17");
scheme.getStyle(Token.LITERAL_STRING_DOUBLE_QUOTE).foreground = Color.decode("#067d17"); // Soft blue for values
scheme.getStyle(Token.DATA_TYPE).foreground = dataTypeColor;
scheme.getStyle(Token.OPERATOR).foreground = Color.decode("#333333");
scheme.getStyle(Token.SEPARATOR).foreground = Color.decode("#333333");
scheme.getStyle(Token.IDENTIFIER).foreground = themeForeground;
// XML-specific colors for light theme
scheme.getStyle(Token.MARKUP_TAG_DELIMITER).foreground = Color.decode("#800000"); // Dark red for < > /
scheme.getStyle(Token.MARKUP_TAG_NAME).foreground = Color.decode("#4A7A4F"); // Soft green for tag names (keys)
scheme.getStyle(Token.MARKUP_TAG_ATTRIBUTE).foreground = Color.decode("#FF0000"); // Red for attributes
scheme.getStyle(Token.MARKUP_TAG_ATTRIBUTE_VALUE).foreground = Color.decode("#0000FF"); // Blue for values
}
textArea.setBackground(editorBackground);
textArea.setCaretColor(caretForeground);
textArea.setSelectionColor(selectionColor);
textArea.setCurrentLineHighlightColor(lineHighlight);
textArea.setMarkAllHighlightColor(markAllHighlightColor);
textArea.setMarkOccurrencesColor(markOccurrencesColor);
textArea.setHyperlinkForeground(editorSelectionBackground);
textArea.setMatchedBracketBGColor(matchedBracketBackground);
textArea.setMatchedBracketBorderColor(lineNumberForeground);
textArea.setPaintMatchedBracketPair(true);
textArea.setAnimateBracketMatching(false);
textArea.setFadeCurrentLineHighlight(true);
// Reset gutter colors directly to ensure the change applies
Gutter gutter = RSyntaxUtilities.getGutter(textArea);
if (gutter != null) {
gutter.setBackground(editorBackground);
gutter.setBorderColor(separatorForeground);
gutter.setLineNumberColor(lineNumberForeground);
}
}
}
| 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/IEditorTheme.java | jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/IEditorTheme.java | package jadx.gui.ui.codearea.theme;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
public interface IEditorTheme {
String getId();
String getName();
default void load() {
// optional method
}
void apply(RSyntaxTextArea textArea);
default void unload() {
// optional method
}
}
| 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/RSTAThemeXML.java | jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/RSTAThemeXML.java | package jadx.gui.ui.codearea.theme;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RSTAThemeXML implements IEditorTheme {
private static final Logger LOG = LoggerFactory.getLogger(RSTAThemeXML.class);
private final Path themePath;
private final String name;
private Theme loadedTheme;
public RSTAThemeXML(Path themeXmlPath, String name) {
this.themePath = themeXmlPath;
this.name = name;
}
@Override
public String getId() {
return "file:" + themePath;
}
@Override
public String getName() {
return name;
}
@Override
public void load() {
try {
try (InputStream is = Files.newInputStream(themePath)) {
loadedTheme = Theme.load(is);
}
} catch (Exception e) {
LOG.warn("Failed to load editor theme: {}", themePath, e);
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/ThemeIdAndName.java | jadx-gui/src/main/java/jadx/gui/ui/codearea/theme/ThemeIdAndName.java | package jadx.gui.ui.codearea.theme;
public class ThemeIdAndName {
private final String id;
private final String name;
public ThemeIdAndName(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
@Override
public final boolean equals(Object other) {
if (!(other instanceof ThemeIdAndName)) {
return false;
}
return id.equals(((ThemeIdAndName) other).id);
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public String toString() {
return name;
}
}
| 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/filedialog/FileNameMultiExtensionFilter.java | jadx-gui/src/main/java/jadx/gui/ui/filedialog/FileNameMultiExtensionFilter.java | package jadx.gui.ui.filedialog;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* Custom file filter for filtering files with multiple extensions.
* It overcomes the limitation of {@link FileNameExtensionFilter},
* which treats only the last file extension split by dots as the
* file extension, and does not support multiple extensions such as
* {@code .jadx.kts}.
*/
class FileNameMultiExtensionFilter extends FileFilter {
private final FileNameExtensionFilter delegate;
private final String[] extensions;
public FileNameMultiExtensionFilter(String description, String... extensions) {
this.delegate = new FileNameExtensionFilter(description, extensions[0]);
this.extensions = extensions;
}
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
String fileName = file.getName();
for (String extension : extensions) {
if (fileName.endsWith(extension)) {
return true;
}
}
return false;
}
@Override
public String getDescription() {
return delegate.getDescription();
}
}
| 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/filedialog/CustomFileChooser.java | jadx-gui/src/main/java/jadx/gui/ui/filedialog/CustomFileChooser.java | package jadx.gui.ui.filedialog;
import java.awt.Component;
import java.awt.HeadlessException;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import jadx.api.plugins.utils.CommonFileUtils;
import jadx.core.utils.StringUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.files.FileUtils;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.NLS;
class CustomFileChooser extends JFileChooser {
static {
// disable left shortcut panel, can crush in "Win32ShellFolderManager2.getNetwork()" or similar call
UIManager.put("FileChooser.noPlacesBar", Boolean.TRUE);
}
private final FileDialogWrapper data;
public CustomFileChooser(FileDialogWrapper data) {
super(data.getCurrentDir() == null ? CommonFileUtils.CWD : data.getCurrentDir().toFile());
putClientProperty("FileChooser.useShellFolder", Boolean.FALSE);
this.data = data;
}
public List<Path> showDialog() {
setToolTipText(data.getTitle());
setFileSelectionMode(data.getSelectionMode());
setMultiSelectionEnabled(data.isOpen());
setAcceptAllFileFilterUsed(true);
List<String> fileExtList = data.getFileExtList();
if (Utils.notEmpty(fileExtList)) {
List<String> validFileExtList = fileExtList.stream()
.filter(StringUtils::notBlank)
.collect(Collectors.toList());
if (Utils.notEmpty(validFileExtList)) {
String description = NLS.str("file_dialog.supported_files") + ": (" + Utils.listToString(validFileExtList) + ')';
setFileFilter(new FileNameMultiExtensionFilter(description, validFileExtList.toArray(new String[0])));
}
}
if (data.getSelectedFile() != null) {
setSelectedFile(data.getSelectedFile().toFile());
}
MainWindow mainWindow = data.getMainWindow();
int ret = data.isOpen() ? showOpenDialog(mainWindow) : showSaveDialog(mainWindow);
if (ret != JFileChooser.APPROVE_OPTION) {
return Collections.emptyList();
}
data.setCurrentDir(getCurrentDirectory().toPath());
File[] selectedFiles = getSelectedFiles();
if (selectedFiles.length != 0) {
return FileUtils.toPathsWithTrim(selectedFiles);
}
File chosenFile = getSelectedFile();
if (chosenFile != null) {
return Collections.singletonList(FileUtils.toPathWithTrim(chosenFile));
}
return Collections.emptyList();
}
@Override
protected JDialog createDialog(Component parent) throws HeadlessException {
JDialog dialog = super.createDialog(parent);
dialog.setTitle(data.getTitle());
dialog.setLocationRelativeTo(null);
data.getMainWindow().getSettings().loadWindowPos(dialog);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
data.getMainWindow().getSettings().saveWindowPos(dialog);
super.windowClosed(e);
}
});
return dialog;
}
@Override
public void approveSelection() {
if (data.getSelectionMode() == FILES_AND_DIRECTORIES) {
File currentFile = getSelectedFile();
if (currentFile.isDirectory()) {
int option = JOptionPane.showConfirmDialog(
data.getMainWindow(),
NLS.str("file_dialog.load_dir_confirm") + "\n " + currentFile,
NLS.str("file_dialog.load_dir_title"),
JOptionPane.YES_NO_OPTION);
if (option != JOptionPane.YES_OPTION) {
this.setCurrentDirectory(currentFile);
this.updateUI();
return;
}
}
}
super.approveSelection();
}
}
| 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/filedialog/FileDialogWrapper.java | jadx-gui/src/main/java/jadx/gui/ui/filedialog/FileDialogWrapper.java | package jadx.gui.ui.filedialog;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JFileChooser;
import org.jetbrains.annotations.Nullable;
import jadx.gui.settings.JadxProject;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.NLS;
public class FileDialogWrapper {
private static final List<String> OPEN_FILES_EXTS = Arrays.asList(
"apk", "dex", "jar", "class", "smali", "zip", "aar", "arsc", "jadx.kts", "xapk", "apkm", "apks");
private final MainWindow mainWindow;
private boolean isOpen;
private String title;
private List<String> fileExtList = new ArrayList<>();
private int selectionMode = JFileChooser.FILES_AND_DIRECTORIES;
private @Nullable Path currentDir;
private @Nullable Path selectedFile;
public FileDialogWrapper(MainWindow mainWindow, FileOpenMode mode) {
this.mainWindow = mainWindow;
initForMode(mode);
}
public void setTitle(String title) {
this.title = title;
}
public void setFileExtList(List<String> fileExtList) {
this.fileExtList = fileExtList;
}
public void setSelectionMode(int selectionMode) {
this.selectionMode = selectionMode;
}
public void setSelectedFile(Path path) {
this.selectedFile = path;
}
public void setCurrentDir(Path currentDir) {
this.currentDir = currentDir;
}
public List<Path> show() {
if (mainWindow.getSettings().isUseAlternativeFileDialog()) {
return new CustomFileDialog(this).showDialog();
} else {
return new CustomFileChooser(this).showDialog();
}
}
private void initForMode(FileOpenMode mode) {
switch (mode) {
case OPEN_PROJECT:
title = NLS.str("file.open_title");
fileExtList = Collections.singletonList(JadxProject.PROJECT_EXTENSION);
selectionMode = JFileChooser.FILES_AND_DIRECTORIES;
currentDir = mainWindow.getSettings().getLastOpenFilePath();
isOpen = true;
break;
case OPEN:
title = NLS.str("file.open_title");
fileExtList = new ArrayList<>(OPEN_FILES_EXTS);
fileExtList.add(JadxProject.PROJECT_EXTENSION);
fileExtList.add("aab");
selectionMode = JFileChooser.FILES_AND_DIRECTORIES;
currentDir = mainWindow.getSettings().getLastOpenFilePath();
isOpen = true;
break;
case ADD:
title = NLS.str("file.add_files_action");
fileExtList = new ArrayList<>(OPEN_FILES_EXTS);
fileExtList.add("aab");
selectionMode = JFileChooser.FILES_AND_DIRECTORIES;
currentDir = mainWindow.getSettings().getLastOpenFilePath();
isOpen = true;
break;
case SAVE_PROJECT:
title = NLS.str("file.save_project");
fileExtList = Collections.singletonList(JadxProject.PROJECT_EXTENSION);
selectionMode = JFileChooser.FILES_ONLY;
currentDir = mainWindow.getSettings().getLastSaveFilePath();
isOpen = false;
break;
case EXPORT:
title = NLS.str("file.save_all_msg");
fileExtList = Collections.emptyList();
selectionMode = JFileChooser.DIRECTORIES_ONLY;
currentDir = mainWindow.getSettings().getLastSaveFilePath();
isOpen = false;
break;
case CUSTOM_SAVE:
isOpen = false;
currentDir = mainWindow.getSettings().getLastSaveFilePath();
break;
case CUSTOM_OPEN:
isOpen = true;
currentDir = mainWindow.getSettings().getLastOpenFilePath();
break;
case EXPORT_NODE:
isOpen = false;
title = NLS.str("file.export_node");
currentDir = mainWindow.getSettings().getLastSaveFilePath();
selectionMode = JFileChooser.FILES_ONLY;
break;
case EXPORT_NODE_FOLDER:
isOpen = true;
title = NLS.str("file.save_all_msg");
currentDir = mainWindow.getSettings().getLastSaveFilePath();
selectionMode = JFileChooser.DIRECTORIES_ONLY;
break;
}
}
public Path getCurrentDir() {
return currentDir;
}
public MainWindow getMainWindow() {
return mainWindow;
}
public boolean isOpen() {
return isOpen;
}
public String getTitle() {
return title;
}
public List<String> getFileExtList() {
return fileExtList;
}
public int getSelectionMode() {
return selectionMode;
}
public Path getSelectedFile() {
return selectedFile;
}
}
| 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/filedialog/FileOpenMode.java | jadx-gui/src/main/java/jadx/gui/ui/filedialog/FileOpenMode.java | package jadx.gui.ui.filedialog;
public enum FileOpenMode {
OPEN,
OPEN_PROJECT,
ADD,
SAVE_PROJECT,
EXPORT,
CUSTOM_SAVE,
CUSTOM_OPEN,
EXPORT_NODE,
EXPORT_NODE_FOLDER,
}
| 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/filedialog/CustomFileDialog.java | jadx-gui/src/main/java/jadx/gui/ui/filedialog/CustomFileDialog.java | package jadx.gui.ui.filedialog;
import java.awt.FileDialog;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import jadx.core.utils.ListUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.files.FileUtils;
class CustomFileDialog {
private final FileDialogWrapper data;
public CustomFileDialog(FileDialogWrapper data) {
this.data = data;
}
public List<Path> showDialog() {
FileDialog fileDialog = new FileDialog(data.getMainWindow(), data.getTitle());
fileDialog.setMode(data.isOpen() ? FileDialog.LOAD : FileDialog.SAVE);
fileDialog.setMultipleMode(true);
List<String> fileExtList = data.getFileExtList();
if (Utils.notEmpty(fileExtList)) {
fileDialog.setFilenameFilter((dir, name) -> ListUtils.anyMatch(fileExtList, name::endsWith));
}
if (data.getSelectedFile() != null) {
fileDialog.setFile(data.getSelectedFile().toAbsolutePath().toString());
}
if (data.getCurrentDir() != null) {
fileDialog.setDirectory(data.getCurrentDir().toAbsolutePath().toString());
}
fileDialog.setVisible(true);
File[] selectedFiles = fileDialog.getFiles();
if (!Utils.isEmpty(selectedFiles)) {
data.setCurrentDir(Paths.get(fileDialog.getDirectory()));
return FileUtils.toPathsWithTrim(selectedFiles);
}
if (fileDialog.getFile() != null) {
return Collections.singletonList(FileUtils.toPathWithTrim(fileDialog.getFile()));
}
return Collections.emptyList();
}
}
| 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/hexviewer/HexPreviewPanel.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/HexPreviewPanel.java | package jadx.gui.ui.hexviewer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import org.exbin.auxiliary.binary_data.BinaryData;
import org.exbin.auxiliary.binary_data.array.ByteArrayEditableData;
import org.exbin.bined.CodeAreaCaretListener;
import org.exbin.bined.CodeAreaCaretPosition;
import org.exbin.bined.CodeAreaUtils;
import org.exbin.bined.CodeCharactersCase;
import org.exbin.bined.CodeType;
import org.exbin.bined.EditMode;
import org.exbin.bined.SelectionRange;
import org.exbin.bined.basic.BasicCodeAreaZone;
import org.exbin.bined.color.CodeAreaBasicColors;
import org.exbin.bined.highlight.swing.color.CodeAreaMatchColorType;
import org.exbin.bined.swing.CodeAreaPainter;
import org.exbin.bined.swing.basic.DefaultCodeAreaCommandHandler;
import org.exbin.bined.swing.capability.CharAssessorPainterCapable;
import org.exbin.bined.swing.capability.ColorAssessorPainterCapable;
import org.exbin.bined.swing.section.SectCodeArea;
import org.exbin.bined.swing.section.color.SectionCodeAreaColorProfile;
import jadx.gui.settings.JadxSettings;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
public class HexPreviewPanel extends JPanel {
private static final long serialVersionUID = 3261685857479120073L;
private static final int CACHE_SIZE = 250;
private final byte[] valuesCache = new byte[CACHE_SIZE];
private final SectCodeArea hexCodeArea;
private final SectionCodeAreaColorProfile defaultColors;
private final HexEditorHeader header;
private final HexSearchBar searchBar;
private final HexInspectorPanel inspector;
private JPopupMenu popupMenu;
private JMenuItem cutAction;
private JMenuItem copyAction;
private JMenuItem copyHexAction;
private JMenuItem copyStringAction;
private JMenuItem pasteAction;
private JMenuItem deleteAction;
private JMenuItem selectAllAction;
private JMenuItem copyOffsetItem;
private BasicCodeAreaZone popupMenuPositionZone = BasicCodeAreaZone.UNKNOWN;
public HexPreviewPanel(JadxSettings settings) {
hexCodeArea = new SectCodeArea();
hexCodeArea.setCodeFont(settings.getSmaliFont());
hexCodeArea.setEditMode(EditMode.READ_ONLY);
hexCodeArea.setCharset(StandardCharsets.UTF_8);
hexCodeArea.setComponentPopupMenu(new JPopupMenu() {
@Override
public void show(Component invoker, int x, int y) {
popupMenuPositionZone = hexCodeArea.getPainter().getPositionZone(x, y);
createPopupMenu();
if (popupMenu != null && popupMenuPositionZone != BasicCodeAreaZone.HEADER
&& popupMenuPositionZone != BasicCodeAreaZone.ROW_POSITIONS) {
updatePopupActionStates();
popupMenu.show(invoker, x, y);
}
}
});
inspector = new HexInspectorPanel();
searchBar = new HexSearchBar(hexCodeArea);
header = new HexEditorHeader(hexCodeArea);
header.setFont(settings.getUiFont());
CodeAreaPainter painter = hexCodeArea.getPainter();
defaultColors = (SectionCodeAreaColorProfile) hexCodeArea.getColorsProfile();
hexCodeArea.setColorsProfile(getColorsProfile());
BinEdCodeAreaAssessor codeAreaAssessor = new BinEdCodeAreaAssessor(((ColorAssessorPainterCapable) painter).getColorAssessor(),
((CharAssessorPainterCapable) painter).getCharAssessor());
((ColorAssessorPainterCapable) painter).setColorAssessor(codeAreaAssessor);
((CharAssessorPainterCapable) painter).setCharAssessor(codeAreaAssessor);
setLayout(new BorderLayout());
add(searchBar, BorderLayout.PAGE_START);
add(hexCodeArea, BorderLayout.CENTER);
add(header, BorderLayout.PAGE_END);
add(inspector, BorderLayout.EAST);
setFocusable(true);
addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
hexCodeArea.requestFocusInWindow();
}
@Override
public void focusLost(FocusEvent e) {
}
});
createActions();
enableUpdate();
}
public SectionCodeAreaColorProfile getColorsProfile() {
boolean isDarkTheme = UiUtils.isDarkTheme(Objects.requireNonNull(defaultColors.getColor(CodeAreaBasicColors.TEXT_BACKGROUND)));
Color markAllHighlightColor = isDarkTheme ? Color.decode("#32593D") : Color.decode("#ffc800");
Color editorSelectionBackground = Objects.requireNonNull(defaultColors.getColor(CodeAreaBasicColors.SELECTION_BACKGROUND));
Color currentMatchColor = UiUtils.adjustBrightness(editorSelectionBackground, isDarkTheme ? 0.6f : 1.4f);
defaultColors.setColor(CodeAreaMatchColorType.MATCH_BACKGROUND, markAllHighlightColor);
defaultColors.setColor(CodeAreaMatchColorType.CURRENT_MATCH_BACKGROUND, currentMatchColor);
return defaultColors;
}
public boolean isDataLoaded() {
return !hexCodeArea.getContentData().isEmpty();
}
public void setData(byte[] data) {
if (data != null) {
hexCodeArea.setContentData(new ByteArrayEditableData(data));
inspector.setBytes(data);
}
}
public void scrollToOffset(int pos) {
hexCodeArea.setSelection(pos, pos + 1);
hexCodeArea.setActiveCaretPosition(pos);
hexCodeArea.centerOnPosition(hexCodeArea.getActiveCaretPosition());
}
public void enableUpdate() {
CodeAreaCaretListener caretMovedListener = (CodeAreaCaretPosition caretPosition) -> updateValues();
hexCodeArea.addCaretMovedListener(caretMovedListener);
}
private void updateValues() {
CodeAreaCaretPosition caretPosition = hexCodeArea.getActiveCaretPosition();
long dataPosition = caretPosition.getDataPosition();
long dataSize = hexCodeArea.getDataSize();
if (dataPosition < dataSize) {
int availableData = dataSize - dataPosition >= CACHE_SIZE ? CACHE_SIZE : (int) (dataSize - dataPosition);
BinaryData contentData = hexCodeArea.getContentData();
contentData.copyToArray(dataPosition, valuesCache, 0, availableData);
if (availableData < CACHE_SIZE) {
Arrays.fill(valuesCache, availableData, CACHE_SIZE, (byte) 0);
}
}
inspector.setOffset((int) dataPosition);
}
private void createActions() {
cutAction = new JMenuItem(NLS.str("popup.cut"));
cutAction.addActionListener(e -> performCut());
copyAction = new JMenuItem(NLS.str("popup.copy"));
copyAction.addActionListener(e -> performCopy());
copyHexAction = new JMenuItem(NLS.str("popup.copy_as_hex"));
copyHexAction.addActionListener(e -> performCopyAsCode());
copyStringAction = new JMenuItem(NLS.str("popup.copy_as_string"));
copyStringAction.addActionListener(e -> performCopy());
pasteAction = new JMenuItem(NLS.str("popup.paste"));
pasteAction.addActionListener(e -> performPaste());
deleteAction = new JMenuItem(NLS.str("popup.delete"));
deleteAction.addActionListener(e -> {
if (!isEditable()) {
performDelete();
}
});
selectAllAction = new JMenuItem(NLS.str("popup.select_all"));
selectAllAction.addActionListener(e -> performSelectAll());
copyOffsetItem = new JMenuItem(NLS.str("popup.copy_offset"));
copyOffsetItem.addActionListener(e -> copyOffset());
}
private void createPopupMenu() {
boolean isEditable = isEditable();
popupMenu = new JPopupMenu();
popupMenu.add(copyAction);
if (isEditable) {
popupMenu.add(cutAction);
popupMenu.add(pasteAction);
popupMenu.add(deleteAction);
popupMenu.addSeparator();
}
JMenu copyMenu = new JMenu(NLS.str("popup.copy_as"));
copyMenu.add(copyHexAction);
copyMenu.add(copyStringAction);
popupMenu.add(copyMenu);
popupMenu.add(copyOffsetItem);
popupMenu.add(selectAllAction);
}
private void updatePopupActionStates() {
boolean selectionExists = isSelection();
boolean isEditable = !isEditable();
cutAction.setEnabled(isEditable && selectionExists);
copyAction.setEnabled(selectionExists);
copyHexAction.setEnabled(selectionExists);
copyStringAction.setEnabled(selectionExists);
deleteAction.setEnabled(isEditable && selectionExists);
selectAllAction.setEnabled(hexCodeArea.getDataSize() > 0);
}
public SectCodeArea getEditor() {
return this.hexCodeArea;
}
public HexEditorHeader getHeader() {
return this.header;
}
public HexInspectorPanel getInspector() {
return this.inspector;
}
public HexSearchBar getSearchBar() {
return this.searchBar;
}
public void showSearchBar() {
searchBar.showAndFocus();
}
public void performCut() {
hexCodeArea.cut();
}
public void performCopy() {
hexCodeArea.copy();
}
public void performCopyAsCode() {
((DefaultCodeAreaCommandHandler) hexCodeArea.getCommandHandler()).copyAsCode();
}
public void performPaste() {
hexCodeArea.paste();
}
public void performDelete() {
hexCodeArea.delete();
}
public void performSelectAll() {
hexCodeArea.selectAll();
}
public boolean isSelection() {
return hexCodeArea.hasSelection();
}
public boolean isEditable() {
return hexCodeArea.isEditable();
}
public boolean canPaste() {
return hexCodeArea.canPaste();
}
public static String getSelectionData(SectCodeArea core) {
SelectionRange selection = core.getSelection();
if (!selection.isEmpty()) {
long first = selection.getFirst();
long last = selection.getLast();
BinaryData copy = core.getContentData().copy(first, last - first + 1);
CodeType codeType = core.getCodeType();
CodeCharactersCase charactersCase = core.getCodeCharactersCase();
int charsPerByte = codeType.getMaxDigitsForByte() + 1;
int textLength = (int) (copy.getDataSize() * charsPerByte);
if (textLength > 0) {
textLength--;
}
char[] targetData = new char[textLength];
Arrays.fill(targetData, ' ');
for (int i = 0; i < (int) copy.getDataSize(); i++) {
CodeAreaUtils.byteToCharsCode(copy.getByte(i), codeType, targetData, i * charsPerByte, charactersCase);
}
return new String(targetData);
}
return null;
}
public void copyOffset() {
String str = header.addressString(hexCodeArea.getSelection().getStart());
UiUtils.copyToClipboard(str);
}
}
| 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/hexviewer/HexEditorHeader.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/HexEditorHeader.java | package jadx.gui.ui.hexviewer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.UIManager;
import org.exbin.bined.CodeAreaCaretListener;
import org.exbin.bined.CodeAreaSection;
import org.exbin.bined.DataChangedListener;
import org.exbin.bined.SelectionChangedListener;
import org.exbin.bined.SelectionRange;
import org.exbin.bined.basic.BasicCodeAreaSection;
import org.exbin.bined.swing.section.SectCodeArea;
public class HexEditorHeader extends JComponent {
private static final long serialVersionUID = 1L;
private static final String HEX_ALPHABET = "0123456789ABCDEF";
private final SectCodeArea parent;
private final DataChangedListener dataChangedListener = this::repaint;
private final CodeAreaCaretListener caretMovedListener = caretPosition -> repaint();
private final SelectionChangedListener selectionChangedListener = this::repaint;
private Dimension minimumSize = null;
private Dimension preferredSize = null;
public HexEditorHeader(SectCodeArea parent) {
this.parent = parent;
if (this.parent != null) {
this.parent.addCaretMovedListener(caretMovedListener);
this.parent.addSelectionChangedListener(selectionChangedListener);
this.parent.addDataChangedListener(dataChangedListener);
}
}
@Override
public void addNotify() {
super.addNotify();
if (this.parent != null) {
this.parent.addCaretMovedListener(caretMovedListener);
this.parent.addSelectionChangedListener(selectionChangedListener);
this.parent.addDataChangedListener(dataChangedListener);
}
}
@Override
public void removeNotify() {
if (this.parent != null) {
this.parent.removeCaretMovedListener(caretMovedListener);
this.parent.removeSelectionChangedListener(selectionChangedListener);
this.parent.removeDataChangedListener(dataChangedListener);
}
super.removeNotify();
}
@Override
public Dimension getMinimumSize() {
if (minimumSize != null) {
return minimumSize;
}
Insets i = getInsets();
FontMetrics fm = getFontMetrics(parent.getFont());
if (fm == null) {
return new Dimension(100, 20); // Fallback
}
int ch = fm.getHeight() + 2; // Row height
int cw = fm.stringWidth(HEX_ALPHABET) / 16; // Char width estimate
String sampleText = "Sel: 00000000:00000000 Len: 00000000/00000000 TXT UTF-8";
int minTextWidth = fm.stringWidth(sampleText);
int minimumWidth = minTextWidth + cw * 5 + i.left + i.right;
int minimumHeight = ch + 5 + i.top + i.bottom;
return new Dimension(minimumWidth, minimumHeight);
}
@Override
public void setMinimumSize(Dimension minimumSize) {
this.minimumSize = minimumSize;
revalidate();
}
@Override
public Dimension getPreferredSize() {
if (preferredSize != null) {
return preferredSize;
}
Insets i = getInsets();
FontMetrics fm = getFontMetrics(parent.getFont());
if (fm == null) {
return getMinimumSize(); // Fallback
}
int ch = fm.getHeight() + 2;
int cw = fm.stringWidth(HEX_ALPHABET) / 16;
String sampleText = "Sel: 00000000:00000000 Len: 00000000/00000000 TXT UTF-8";
int preferredTextWidth = fm.stringWidth(sampleText);
int preferredWidth = preferredTextWidth + cw * 10 + i.left + i.right;
int preferredHeight = ch + 5 + i.top + i.bottom;
return new Dimension(preferredWidth, preferredHeight);
}
@Override
public void setPreferredSize(Dimension preferredSize) {
this.preferredSize = preferredSize;
revalidate();
}
@Override
protected void paintComponent(Graphics g) {
// Standard Graphics2D setup
if (g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
// Get insets, width, height
Insets i = getInsets();
int fw = getWidth();
int fh = getHeight();
int w = fw - i.left - i.right;
int h = fh - i.top - i.bottom;
// Get font metrics
g.setFont(parent.getFont());
FontMetrics fm = g.getFontMetrics();
if (fm == null) {
return; // Cannot paint without font metrics
}
int ca = fm.getAscent() + 1; // Character ascent for baseline
int ch = fm.getHeight() + 2; // Row height including padding
int cw = fm.stringWidth(HEX_ALPHABET) / 16; // Character width estimate
if (cw <= 0) {
cw = 1; // Avoid division by zero or incorrect calculations
}
// Get colors and status from parent editor
Color separatorForeground = UIManager.getColor("Separator.foreground");
Color themeBackground = UIManager.getColor("Panel.background");
Color themeForeground = UIManager.getColor("Panel.foreground");
SelectionRange selectionRange = parent.getSelection();
long ss = selectionRange.getStart();
long se = selectionRange.getEnd();
long sl = selectionRange.getLength();
long length = parent.getDataSize();
// Vertical position for the text baseline (centered vertically)
int ty = i.top + ((h - ch) / 2) + ca; // Calculate middle Y for the single line of text
// Draw Background
g.setColor(themeBackground);
g.fillRect(i.left, i.top, w, h);
// Draw Text Elements (Sel, Len, Status)
g.setColor(themeForeground);
// Start drawing position (adjust for left inset)
int currentX = i.left + cw / 2; // Start with a small left padding
// Selection Range (Sel: start:end
String selLabel = "Sel:";
g.drawString(selLabel, currentX, ty);
currentX += fm.stringWidth(selLabel) + cw; // "Sel:" + space
String sss = addressString(ss);
g.drawString(sss, currentX, ty);
currentX += fm.stringWidth(sss); // start
String separator1 = ":";
g.drawString(separator1, currentX, ty);
currentX += fm.stringWidth(separator1); // :
String ses = addressString(se);
g.drawString(ses, currentX, ty);
currentX += fm.stringWidth(ses) + cw; // end + larger space
// Draw Divider After Sel Range
int dividerTopY = i.top;
int dividerHeight = h;
g.setColor(separatorForeground);
g.fillRect(currentX, dividerTopY, 1, dividerHeight);
currentX += cw; // Add larger space after the divider
// Length Information (Len: selected/total-
g.setColor(themeForeground);
String lenLabel = "Len:";
g.drawString(lenLabel, currentX, ty);
currentX += fm.stringWidth(lenLabel) + cw; // "Len:" + space
String sls = addressString(sl);
g.drawString(sls, currentX, ty);
currentX += fm.stringWidth(sls); // selected length
String separator2 = "/";
g.drawString(separator2, currentX, ty);
currentX += fm.stringWidth(separator2);
String ls = addressString(length);
g.drawString(ls, currentX, ty);
currentX += fm.stringWidth(ls) + cw; // total length + larger space
// Draw Divider After Len Info
g.setColor(separatorForeground);
g.fillRect(currentX, dividerTopY, 1, dividerHeight);
currentX += cw; // Add larger space after the divider
// Status Indicators (TXT/HEX, RO/RW, OVR/INS, LE/BE, Charset)
g.setColor(themeForeground); // Ensure color is set for text
// Draw TXT/HEX status
String statusTxtHex = "HEX";
CodeAreaSection section = parent.getActiveSection();
if (section == BasicCodeAreaSection.TEXT_PREVIEW) {
statusTxtHex = "TXT";
}
g.drawString(statusTxtHex, currentX, ty);
currentX += fm.stringWidth(statusTxtHex) + cw; // TXT/HEX
// Draw Divider After TXT/HEX
g.setColor(separatorForeground);
g.fillRect(currentX, dividerTopY, 1, dividerHeight);
currentX += cw; // Add larger space after the divider
g.setColor(themeForeground); // Restore text color
// Draw Charset
String statusCharset = parent.getCharset().name();
g.drawString(statusCharset, currentX, ty);
// No divider or space needed after the last element
// Draw Bottom Border
g.setColor(separatorForeground); // Use headerDivider color for the border
g.fillRect(i.left, i.top + h - 1, w, 1);
}
public String addressString(long address) {
return String.format("%08X", address);
}
}
| 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/hexviewer/HexInspectorPanel.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/HexInspectorPanel.java | package jadx.gui.ui.hexviewer;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.commons.lang3.ArrayUtils;
public class HexInspectorPanel extends JPanel {
private final List<ValueFormatter> formatters = new ArrayList<>();
private byte[] bytes = null;
private Integer offset = null;
private boolean isLittleEndian;
private int row = 0;
public HexInspectorPanel() {
setLayout(new GridBagLayout());
addValueFormat("Signed 8 bit", 1, b -> Integer.toString(b.get()));
addValueFormat("Unsigned 8 bit", 1, b -> Integer.toString(b.get() & 0xFF));
addValueFormat("Signed 16 bit", 2, b -> Short.toString(b.getShort()));
addValueFormat("Unsigned 16 bit", 2, b -> Integer.toString(b.getShort() & 0xFFFF));
addValueFormat("Float 32 bit", 4, b -> Float.toString(b.getFloat()));
addValueFormat("Signed 32 bit", 4, b -> Integer.toString(b.getInt()));
addValueFormat("Unsigned 32 bit", 4, b -> Integer.toUnsignedString(b.getInt()));
addValueFormat("Signed 64 bit", 8, b -> Long.toString(b.getLong()));
addValueFormat("Float 64 bit", 8, b -> Double.toString(b.getDouble()));
addValueFormat("Unsigned 64 bit", 8, b -> Long.toUnsignedString(b.getLong()));
addValueFormat("Hexadecimal", 1, b -> Integer.toString(b.get(), 16));
addValueFormat("Octal", 1, b -> Integer.toString(b.get(), 8));
addValueFormat("Binary", 1, b -> Integer.toString(b.get(), 2));
GridBagConstraints constraints;
constraints = getConstraints();
constraints.gridwidth = 2;
JCheckBox littleEndianCheckBox = new JCheckBox("Little endian", false);
littleEndianCheckBox.addItemListener(ev -> {
isLittleEndian = ev.getStateChange() == ItemEvent.SELECTED;
reloadOffset();
});
add(littleEndianCheckBox, constraints);
// Workaround to force widgets to start from the top (otherwise centered)
constraints = getConstraints();
constraints.weighty = 1;
add(new JLabel(" "), constraints);
}
public void setOffset(int offset) {
this.offset = offset;
reloadOffset();
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
private void reloadOffset() {
if (bytes == null || offset == null) {
return;
}
for (int i = 0; i < formatters.size(); i++) {
ValueFormatter formatter = formatters.get(i);
if (canDisplay(offset, formatter.dataSize)) {
ByteBuffer buffer = decodeByteArray(offset, formatter.dataSize);
String value = formatter.function.apply(buffer);
((JTextField) getComponent(i * 2 + 1)).setText(value);
}
}
}
private GridBagConstraints getConstraints() {
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 5, 5);
constraints.gridy = row;
row++;
return constraints;
}
private void addValueFormat(String name, int dataSize, Function<ByteBuffer, String> formatter) {
formatters.add(new ValueFormatter(dataSize, formatter));
GridBagConstraints constraints = getConstraints();
constraints.gridx = 0;
constraints.anchor = GridBagConstraints.WEST;
add(new JLabel(name), constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 1;
JTextField textField = new JTextField();
textField.setEditable(false);
add(textField, constraints);
}
private boolean canDisplay(int offset, int size) {
return offset + size <= bytes.length;
}
private ByteBuffer decodeByteArray(int offset, int size) {
byte[] chunk = sliceBytes(offset, size);
if (isLittleEndian) {
ArrayUtils.reverse(chunk);
}
return ByteBuffer.wrap(chunk);
}
private byte[] sliceBytes(int offset, int size) {
byte[] slice = new byte[size];
System.arraycopy(bytes, offset, slice, 0, size);
return slice;
}
private static class ValueFormatter {
public final int dataSize;
public final Function<ByteBuffer, String> function;
public ValueFormatter(int dataSize, Function<ByteBuffer, String> function) {
this.dataSize = dataSize;
this.function = function;
}
}
}
| 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/hexviewer/BinEdCodeAreaAssessor.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/BinEdCodeAreaAssessor.java | package jadx.gui.ui.hexviewer;
/*
* Copyright (C) ExBin Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.exbin.bined.CodeAreaSection;
import org.exbin.bined.highlight.swing.NonAsciiCodeAreaColorAssessor;
import org.exbin.bined.highlight.swing.NonprintablesCodeAreaAssessor;
import org.exbin.bined.highlight.swing.SearchCodeAreaColorAssessor;
import org.exbin.bined.swing.CodeAreaCharAssessor;
import org.exbin.bined.swing.CodeAreaColorAssessor;
import org.exbin.bined.swing.CodeAreaPaintState;
/**
* Color assessor for binary editor with registrable modifiers.
*
* @author ExBin Project (https://exbin.org)
*/
public class BinEdCodeAreaAssessor implements CodeAreaColorAssessor, CodeAreaCharAssessor {
private final List<PositionColorModifier> priorityColorModifiers = new ArrayList<>();
private final List<PositionColorModifier> colorModifiers = new ArrayList<>();
private final CodeAreaColorAssessor parentColorAssessor;
private final CodeAreaCharAssessor parentCharAssessor;
public BinEdCodeAreaAssessor(CodeAreaColorAssessor parentColorAssessor, CodeAreaCharAssessor parentCharAssessor) {
NonAsciiCodeAreaColorAssessor nonAsciiCodeAreaColorAssessor = new NonAsciiCodeAreaColorAssessor(parentColorAssessor);
NonprintablesCodeAreaAssessor nonprintablesCodeAreaAssessor =
new NonprintablesCodeAreaAssessor(nonAsciiCodeAreaColorAssessor, parentCharAssessor);
SearchCodeAreaColorAssessor searchCodeAreaColorAssessor = new SearchCodeAreaColorAssessor(nonprintablesCodeAreaAssessor);
this.parentColorAssessor = searchCodeAreaColorAssessor;
this.parentCharAssessor = nonprintablesCodeAreaAssessor;
}
public void addColorModifier(PositionColorModifier colorModifier) {
colorModifiers.add(colorModifier);
}
public void removeColorModifier(PositionColorModifier colorModifier) {
colorModifiers.remove(colorModifier);
}
public void addPriorityColorModifier(PositionColorModifier colorModifier) {
priorityColorModifiers.add(colorModifier);
}
public void removePriorityColorModifier(PositionColorModifier colorModifier) {
priorityColorModifiers.remove(colorModifier);
}
@Override
public void startPaint(CodeAreaPaintState codeAreaPaintState) {
for (PositionColorModifier colorModifier : priorityColorModifiers) {
colorModifier.resetColors();
}
for (PositionColorModifier colorModifier : colorModifiers) {
colorModifier.resetColors();
}
if (parentColorAssessor != null) {
parentColorAssessor.startPaint(codeAreaPaintState);
}
}
@Override
public Color getPositionBackgroundColor(long rowDataPosition, int byteOnRow, int charOnRow, CodeAreaSection section,
boolean inSelection) {
for (PositionColorModifier colorModifier : priorityColorModifiers) {
Color positionBackgroundColor =
colorModifier.getPositionBackgroundColor(rowDataPosition, byteOnRow, charOnRow, section, inSelection);
if (positionBackgroundColor != null) {
return positionBackgroundColor;
}
}
if (!inSelection) {
for (PositionColorModifier colorModifier : colorModifiers) {
Color positionBackgroundColor =
colorModifier.getPositionBackgroundColor(rowDataPosition, byteOnRow, charOnRow, section, inSelection);
if (positionBackgroundColor != null) {
return positionBackgroundColor;
}
}
}
if (parentColorAssessor != null) {
return parentColorAssessor.getPositionBackgroundColor(rowDataPosition, byteOnRow, charOnRow, section, inSelection);
}
return null;
}
@Override
public Color getPositionTextColor(long rowDataPosition, int byteOnRow, int charOnRow, CodeAreaSection section, boolean inSelection) {
for (PositionColorModifier colorModifier : priorityColorModifiers) {
Color positionTextColor = colorModifier.getPositionTextColor(rowDataPosition, byteOnRow, charOnRow, section, inSelection);
if (positionTextColor != null) {
return positionTextColor;
}
}
if (!inSelection) {
for (PositionColorModifier colorModifier : colorModifiers) {
Color positionTextColor = colorModifier.getPositionTextColor(rowDataPosition, byteOnRow, charOnRow, section, inSelection);
if (positionTextColor != null) {
return positionTextColor;
}
}
}
if (parentColorAssessor != null) {
return parentColorAssessor.getPositionTextColor(rowDataPosition, byteOnRow, charOnRow, section, inSelection);
}
return null;
}
@Override
public char getPreviewCharacter(long rowDataPosition, int byteOnRow, int charOnRow, CodeAreaSection section) {
return parentCharAssessor != null ? parentCharAssessor.getPreviewCharacter(rowDataPosition, byteOnRow, charOnRow, section) : ' ';
}
@Override
public char getPreviewCursorCharacter(long rowDataPosition, int byteOnRow, int charOnRow, byte[] cursorData, int cursorDataLength,
CodeAreaSection section) {
return parentCharAssessor != null
? parentCharAssessor.getPreviewCursorCharacter(rowDataPosition, byteOnRow, charOnRow, cursorData, cursorDataLength, section)
: ' ';
}
@Override
public Optional<CodeAreaCharAssessor> getParentCharAssessor() {
return Optional.ofNullable(parentCharAssessor);
}
@Override
public Optional<CodeAreaColorAssessor> getParentColorAssessor() {
return Optional.ofNullable(parentColorAssessor);
}
public interface PositionColorModifier {
Color getPositionBackgroundColor(long rowDataPosition, int byteOnRow, int charOnRow, CodeAreaSection section, boolean inSelection);
Color getPositionTextColor(long rowDataPosition, int byteOnRow, int charOnRow, CodeAreaSection section, boolean inSelection);
void resetColors();
}
}
| 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/hexviewer/HexSearchBar.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/HexSearchBar.java | package jadx.gui.ui.hexviewer;
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 org.exbin.auxiliary.binary_data.array.ByteArrayEditableData;
import org.exbin.bined.CodeAreaUtils;
import org.exbin.bined.swing.section.SectCodeArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.formdev.flatlaf.FlatClientProperties;
import jadx.core.utils.StringUtils;
import jadx.gui.ui.hexviewer.search.BinarySearch;
import jadx.gui.ui.hexviewer.search.SearchCondition;
import jadx.gui.ui.hexviewer.search.SearchParameters;
import jadx.gui.ui.hexviewer.search.service.BinarySearchServiceImpl;
import jadx.gui.utils.HexUtils;
import jadx.gui.utils.Icons;
import jadx.gui.utils.NLS;
import jadx.gui.utils.TextStandardActions;
import jadx.gui.utils.UiUtils;
public class HexSearchBar extends JToolBar {
private static final long serialVersionUID = 1836871286618633003L;
private static final Logger LOG = LoggerFactory.getLogger(HexSearchBar.class);
private final SectCodeArea hexCodeArea;
private final JTextField searchField;
private final JLabel resultCountLabel;
private final JToggleButton markAllCB;
private final JToggleButton findTypeCB;
private final JToggleButton matchCaseCB;
private final JButton nextMatchButton;
private final JButton prevMatchButton;
private Control control = null;
public HexSearchBar(SectCodeArea textArea) {
hexCodeArea = 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:
control.performFind();
break;
}
}
});
searchField.addActionListener(e -> control.notifySearchChanging());
TextStandardActions.attach(searchField);
add(searchField);
ActionListener searchSettingListener = e -> control.notifySearchChanged();
resultCountLabel = new JLabel();
resultCountLabel.setBorder(new EmptyBorder(0, 10, 0, 10));
resultCountLabel.setForeground(Color.GRAY);
add(resultCountLabel);
matchCaseCB = new JToggleButton();
matchCaseCB.setIcon(Icons.ICON_MATCH);
matchCaseCB.setSelectedIcon(Icons.ICON_MATCH_SELECTED);
matchCaseCB.setToolTipText(NLS.str("search.match_case"));
matchCaseCB.addActionListener(searchSettingListener);
add(matchCaseCB);
findTypeCB = new JToggleButton();
findTypeCB.setIcon(Icons.ICON_FIND_TYPE_TXT);
findTypeCB.setSelectedIcon(Icons.ICON_FIND_TYPE_HEX);
if (findTypeCB.isSelected()) {
findTypeCB.setToolTipText(NLS.str("search.find_type_hex"));
} else {
findTypeCB.setToolTipText(NLS.str("search.find_type_text"));
}
findTypeCB.addActionListener(e -> {
searchField.setText("");
updateFindStatus();
control.notifySearchChanged();
});
add(findTypeCB);
prevMatchButton = new JButton();
prevMatchButton.setIcon(Icons.ICON_UP);
prevMatchButton.setToolTipText(NLS.str("search.previous"));
prevMatchButton.addActionListener(e -> control.prevMatch());
prevMatchButton.setBorderPainted(false);
add(prevMatchButton);
nextMatchButton = new JButton();
nextMatchButton.setIcon(Icons.ICON_DOWN);
nextMatchButton.setToolTipText(NLS.str("search.next"));
nextMatchButton.addActionListener(e -> control.nextMatch());
nextMatchButton.setBorderPainted(false);
add(nextMatchButton);
markAllCB = new JToggleButton();
markAllCB.setIcon(Icons.ICON_MARK);
markAllCB.setSelectedIcon(Icons.ICON_MARK_SELECTED);
markAllCB.setToolTipText(NLS.str("search.mark_all"));
markAllCB.setSelected(true);
markAllCB.addActionListener(searchSettingListener);
add(markAllCB);
JButton closeButton = new JButton();
closeButton.setIcon(Icons.ICON_CLOSE);
closeButton.addActionListener(e -> toggle());
closeButton.setBorderPainted(false);
add(closeButton);
BinarySearch binarySearch = new BinarySearch(this);
binarySearch.setBinarySearchService(new BinarySearchServiceImpl(hexCodeArea));
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);
if (hexCodeArea.hasSelection()) {
searchField.setText(hexCodeArea.getActiveSection().toString());
}
String selectedText = HexPreviewPanel.getSelectionData(hexCodeArea);
if (!StringUtils.isEmpty(selectedText)) {
searchField.setText(selectedText);
makeFindByHexButton();
}
searchField.selectAll();
searchField.requestFocus();
}
public void toggle() {
boolean visible = !isVisible();
setVisible(visible);
if (visible) {
String preferText = HexPreviewPanel.getSelectionData(hexCodeArea);
if (!StringUtils.isEmpty(preferText)) {
searchField.setText(preferText);
makeFindByHexButton();
}
searchField.selectAll();
searchField.requestFocus();
} else {
control.performEscape();
hexCodeArea.requestFocus();
}
}
public void setInfoLabel(String text) {
resultCountLabel.setText(text);
}
public void updateMatchCount(boolean hasMatches, boolean prevMatchAvailable, boolean nextMatchAvailable) {
prevMatchButton.setEnabled(prevMatchAvailable);
nextMatchButton.setEnabled(nextMatchAvailable);
}
public void setControl(Control control) {
this.control = control;
}
public void clearSearch() {
setInfoLabel("");
searchField.setText("");
}
public SearchParameters getSearchParameters() {
SearchParameters searchParameters = new SearchParameters();
searchParameters.setMatchCase(matchCaseCB.isSelected());
searchParameters.setMatchMode(SearchParameters.MatchMode.fromBoolean(markAllCB.isSelected()));
SearchParameters.SearchDirection searchDirection = control.getSearchDirection();
searchParameters.setSearchDirection(searchDirection);
long startPosition;
if (searchParameters.isSearchFromCursor()) {
startPosition = hexCodeArea.getActiveCaretPosition().getDataPosition();
} else {
switch (searchDirection) {
case FORWARD: {
startPosition = 0;
break;
}
case BACKWARD: {
startPosition = hexCodeArea.getDataSize() - 1;
break;
}
default:
throw CodeAreaUtils.getInvalidTypeException(searchDirection);
}
}
searchParameters.setStartPosition(startPosition);
searchParameters.setCondition(new SearchCondition(makeSearchCondition()));
return searchParameters;
}
private SearchCondition makeSearchCondition() {
SearchCondition condition = new SearchCondition();
if (findTypeCB.isSelected()) {
condition.setSearchMode(SearchCondition.SearchMode.BINARY);
} else {
condition.setSearchMode(SearchCondition.SearchMode.TEXT);
}
if (!StringUtils.isEmpty(searchField.getText())) {
if (condition.getSearchMode() == SearchCondition.SearchMode.TEXT) {
condition.setSearchText(searchField.getText());
} else {
String hexBytes = searchField.getText();
boolean isValidHexInput = HexUtils.isValidHexString(hexBytes);
UiUtils.highlightAsErrorField(searchField, !isValidHexInput);
if (isValidHexInput) {
condition.setBinaryData(new ByteArrayEditableData(HexUtils.hexStringToByteArray(hexBytes)));
}
}
}
return condition;
}
public void updateFindStatus() {
UiUtils.highlightAsErrorField(searchField, false);
SearchCondition condition = makeSearchCondition();
if (condition.getSearchMode() == SearchCondition.SearchMode.TEXT) {
findTypeCB.setSelected(false);
findTypeCB.setToolTipText(NLS.str("search.find_type_text"));
matchCaseCB.setEnabled(true);
} else {
makeFindByHexButton();
matchCaseCB.setEnabled(false);
}
}
private void makeFindByHexButton() {
findTypeCB.setSelected(true);
findTypeCB.setToolTipText(NLS.str("search.find_type_hex"));
}
public interface Control {
void prevMatch();
void nextMatch();
void performEscape();
void performFind();
/**
* Parameters of search have changed.
*/
void notifySearchChanged();
/**
* Parameters of search are changing which might not lead to immediate
* search change.
* <p>
* Typically, text typing.
*/
void notifySearchChanging();
SearchParameters.SearchDirection getSearchDirection();
void 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/hexviewer/search/SearchParameters.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/search/SearchParameters.java | package jadx.gui.ui.hexviewer.search;
/*
* Copyright (C) ExBin Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Parameters for action to search for occurrences of text or data.
*
* @author ExBin Project (https://exbin.org)
*/
public class SearchParameters {
private SearchCondition condition = new SearchCondition();
private long startPosition;
private boolean searchFromCursor;
private boolean matchCase = true;
private MatchMode matchMode = MatchMode.MULTIPLE;
private SearchDirection searchDirection = SearchDirection.FORWARD;
public SearchParameters() {
}
public SearchCondition getCondition() {
return condition;
}
public void setCondition(SearchCondition condition) {
this.condition = condition;
}
public long getStartPosition() {
return startPosition;
}
public void setStartPosition(long startPosition) {
this.startPosition = startPosition;
}
public boolean isSearchFromCursor() {
return searchFromCursor;
}
public void setSearchFromCursor(boolean searchFromCursor) {
this.searchFromCursor = searchFromCursor;
}
public boolean isMatchCase() {
return matchCase;
}
public void setMatchCase(boolean matchCase) {
this.matchCase = matchCase;
}
public MatchMode getMatchMode() {
return matchMode;
}
public void setMatchMode(MatchMode matchMode) {
this.matchMode = matchMode;
}
public SearchDirection getSearchDirection() {
return searchDirection;
}
public void setSearchDirection(SearchDirection searchDirection) {
this.searchDirection = searchDirection;
}
public void setFromParameters(SearchParameters searchParameters) {
condition = searchParameters.getCondition();
startPosition = searchParameters.getStartPosition();
searchFromCursor = searchParameters.isSearchFromCursor();
matchCase = searchParameters.isMatchCase();
matchMode = searchParameters.getMatchMode();
searchDirection = searchParameters.getSearchDirection();
}
public enum SearchDirection {
FORWARD, BACKWARD
}
public enum MatchMode {
SINGLE, MULTIPLE;
public static MatchMode fromBoolean(boolean multipleMatches) {
return multipleMatches ? MULTIPLE : SINGLE;
}
}
}
| 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/hexviewer/search/SearchCondition.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/search/SearchCondition.java | package jadx.gui.ui.hexviewer.search;
import java.util.Objects;
import org.exbin.auxiliary.binary_data.BinaryData;
import org.exbin.auxiliary.binary_data.EditableBinaryData;
import org.exbin.auxiliary.binary_data.array.ByteArrayEditableData;
import org.exbin.bined.CodeAreaUtils;
/**
* Parameters for action to search for occurrences of text or data.
*
* @author ExBin Project (https://exbin.org)
*/
public class SearchCondition {
private SearchMode searchMode = SearchMode.TEXT;
private String searchText = "";
private EditableBinaryData binaryData;
public SearchCondition() {
}
/**
* This is copy constructor.
*
* @param source source condition
*/
public SearchCondition(SearchCondition source) {
searchMode = source.getSearchMode();
searchText = source.getSearchText();
binaryData = new ByteArrayEditableData();
if (source.getBinaryData() != null) {
binaryData.insert(0, source.getBinaryData());
}
}
public SearchMode getSearchMode() {
return searchMode;
}
public void setSearchMode(SearchMode searchMode) {
this.searchMode = searchMode;
}
public String getSearchText() {
return searchText;
}
public void setSearchText(String searchText) {
this.searchText = searchText;
}
public BinaryData getBinaryData() {
return binaryData;
}
public void setBinaryData(EditableBinaryData binaryData) {
this.binaryData = binaryData;
}
public boolean isEmpty() {
switch (searchMode) {
case TEXT: {
return searchText == null || searchText.isEmpty();
}
case BINARY: {
return binaryData == null || binaryData.isEmpty();
}
default:
throw CodeAreaUtils.getInvalidTypeException(searchMode);
}
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SearchCondition other = (SearchCondition) obj;
if (this.searchMode != other.searchMode) {
return false;
}
if (searchMode == SearchMode.TEXT) {
return Objects.equals(this.searchText, other.searchText);
} else {
return Objects.equals(this.binaryData, other.binaryData);
}
}
public void clear() {
searchText = "";
if (binaryData != null) {
binaryData.clear();
}
}
public enum SearchMode {
TEXT, BINARY
}
}
| 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/hexviewer/search/BinarySearch.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/search/BinarySearch.java | package jadx.gui.ui.hexviewer.search;
/*
* Copyright (C) ExBin Project
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.exbin.auxiliary.binary_data.EditableBinaryData;
import org.exbin.auxiliary.binary_data.array.ByteArrayEditableData;
import jadx.gui.ui.hexviewer.HexSearchBar;
import jadx.gui.ui.hexviewer.search.service.BinarySearchService;
import jadx.gui.utils.NLS;
/**
* Binary search.
*
* @author ExBin Project (https://exbin.org)
*/
public class BinarySearch {
private static final int DEFAULT_DELAY = 500;
private InvokeSearchThread invokeSearchThread;
private SearchThread searchThread;
private SearchOperation currentSearchOperation = SearchOperation.FIND;
private SearchParameters.SearchDirection currentSearchDirection = SearchParameters.SearchDirection.FORWARD;
private final SearchParameters currentSearchParameters = new SearchParameters();
private BinarySearchService.FoundMatches foundMatches = new BinarySearchService.FoundMatches();
private BinarySearchService binarySearchService;
private final BinarySearchService.SearchStatusListener searchStatusListener;
private HexSearchBar binarySearchPanel;
public BinarySearch(HexSearchBar binarySearchPanel) {
this.binarySearchPanel = binarySearchPanel;
searchStatusListener = new BinarySearchService.SearchStatusListener() {
@Override
public void setStatus(BinarySearchService.FoundMatches foundMatches, SearchParameters.MatchMode matchMode) {
BinarySearch.this.foundMatches = foundMatches;
switch (foundMatches.getMatchesCount()) {
case 0:
binarySearchPanel.setInfoLabel(NLS.str("search.match_not_found"));
break;
case 1:
binarySearchPanel.setInfoLabel(
matchMode == SearchParameters.MatchMode.MULTIPLE
? NLS.str("search.single_match")
: NLS.str("search.match_found"));
break;
default:
binarySearchPanel.setInfoLabel(String.format(NLS.str("search.match_of"),
foundMatches.getMatchPosition() + 1, foundMatches.getMatchesCount()));
break;
}
updateMatchStatus();
}
@Override
public void clearStatus() {
binarySearchPanel.setInfoLabel("");
BinarySearch.this.foundMatches = new BinarySearchService.FoundMatches();
updateMatchStatus();
}
private void updateMatchStatus() {
int matchesCount = foundMatches.getMatchesCount();
int matchPosition = foundMatches.getMatchPosition();
binarySearchPanel.updateMatchCount(matchesCount > 0,
matchesCount > 1 && matchPosition > 0,
matchPosition < matchesCount - 1);
}
};
binarySearchPanel.setControl(new HexSearchBar.Control() {
@Override
public void prevMatch() {
foundMatches.prev();
binarySearchService.setMatchPosition(foundMatches.getMatchPosition());
searchStatusListener.setStatus(foundMatches, binarySearchService.getLastSearchParameters().getMatchMode());
}
@Override
public void nextMatch() {
foundMatches.next();
binarySearchService.setMatchPosition(foundMatches.getMatchPosition());
searchStatusListener.setStatus(foundMatches, binarySearchService.getLastSearchParameters().getMatchMode());
}
@Override
public void performEscape() {
cancelSearch();
close();
clearSearch();
}
@Override
public void performFind() {
invokeSearch(SearchOperation.FIND);
}
@Override
public void notifySearchChanged() {
if (currentSearchOperation == SearchOperation.FIND) {
invokeSearch(SearchOperation.FIND);
}
}
@Override
public void notifySearchChanging() {
if (currentSearchOperation != SearchOperation.FIND) {
return;
}
SearchCondition condition = currentSearchParameters.getCondition();
SearchCondition updatedSearchCondition = binarySearchPanel.getSearchParameters().getCondition();
switch (updatedSearchCondition.getSearchMode()) {
case TEXT: {
String searchText = updatedSearchCondition.getSearchText();
if (searchText.isEmpty()) {
condition.setSearchText(searchText);
clearSearch();
return;
}
if (searchText.equals(condition.getSearchText())) {
return;
}
condition.setSearchText(searchText);
break;
}
case BINARY: {
EditableBinaryData searchData = (EditableBinaryData) updatedSearchCondition.getBinaryData();
if (searchData == null || searchData.isEmpty()) {
condition.setBinaryData(null);
clearSearch();
return;
}
if (searchData.equals(condition.getBinaryData())) {
return;
}
ByteArrayEditableData data = new ByteArrayEditableData();
data.insert(0, searchData);
condition.setBinaryData(data);
break;
}
}
BinarySearch.this.invokeSearch(SearchOperation.FIND, DEFAULT_DELAY);
}
@Override
public SearchParameters.SearchDirection getSearchDirection() {
return currentSearchDirection;
}
@Override
public void close() {
cancelSearch();
clearSearch();
}
});
}
public void setBinarySearchService(BinarySearchService binarySearchService) {
this.binarySearchService = binarySearchService;
}
public void setTargetComponent(HexSearchBar targetComponent) {
binarySearchPanel = targetComponent;
}
public BinarySearchService.SearchStatusListener getSearchStatusListener() {
return searchStatusListener;
}
private void invokeSearch(SearchOperation searchOperation) {
invokeSearch(searchOperation, binarySearchPanel.getSearchParameters(), 0);
}
private void invokeSearch(SearchOperation searchOperation, final int delay) {
invokeSearch(searchOperation, binarySearchPanel.getSearchParameters(), delay);
}
private void invokeSearch(SearchOperation searchOperation, SearchParameters searchParameters) {
invokeSearch(searchOperation, searchParameters, 0);
}
private void invokeSearch(SearchOperation searchOperation, SearchParameters searchParameters, final int delay) {
if (invokeSearchThread != null) {
invokeSearchThread.interrupt();
}
invokeSearchThread = new InvokeSearchThread();
invokeSearchThread.delay = delay;
currentSearchOperation = searchOperation;
currentSearchParameters.setFromParameters(searchParameters);
invokeSearchThread.start();
}
public void cancelSearch() {
if (invokeSearchThread != null) {
invokeSearchThread.interrupt();
}
if (searchThread != null) {
searchThread.interrupt();
}
}
public void clearSearch() {
SearchCondition condition = currentSearchParameters.getCondition();
condition.clear();
binarySearchPanel.clearSearch();
binarySearchService.clearMatches();
searchStatusListener.clearStatus();
}
public HexSearchBar getPanel() {
return binarySearchPanel;
}
public void dataChanged() {
binarySearchService.clearMatches();
invokeSearch(currentSearchOperation, DEFAULT_DELAY);
}
private class InvokeSearchThread extends Thread {
private int delay = DEFAULT_DELAY;
public InvokeSearchThread() {
super("InvokeSearchThread");
}
@Override
public void run() {
try {
Thread.sleep(delay);
if (searchThread != null) {
searchThread.interrupt();
}
searchThread = new SearchThread();
searchThread.start();
} catch (InterruptedException ex) {
// don't search
}
}
}
private class SearchThread extends Thread {
public SearchThread() {
super("SearchThread");
}
@Override
public void run() {
switch (currentSearchOperation) {
case FIND:
binarySearchService.performFind(currentSearchParameters, searchStatusListener);
break;
case FIND_AGAIN:
binarySearchService.performFindAgain(searchStatusListener);
break;
default:
throw new UnsupportedOperationException("Not supported yet.");
}
}
}
private enum SearchOperation {
FIND,
FIND_AGAIN
}
}
| 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/hexviewer/search/service/BinarySearchServiceImpl.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/search/service/BinarySearchServiceImpl.java | package jadx.gui.ui.hexviewer.search.service;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.exbin.auxiliary.binary_data.BinaryData;
import org.exbin.bined.CharsetStreamTranslator;
import org.exbin.bined.CodeAreaUtils;
import org.exbin.bined.highlight.swing.SearchCodeAreaColorAssessor;
import org.exbin.bined.highlight.swing.SearchMatch;
import org.exbin.bined.swing.CodeAreaSwingUtils;
import org.exbin.bined.swing.capability.ColorAssessorPainterCapable;
import org.exbin.bined.swing.section.SectCodeArea;
import jadx.gui.ui.hexviewer.search.SearchCondition;
import jadx.gui.ui.hexviewer.search.SearchParameters;
/**
* Binary search service.
*
* @author ExBin Project (https://exbin.org)
*/
public class BinarySearchServiceImpl implements BinarySearchService {
private static final int MAX_MATCHES_COUNT = 100;
private final SectCodeArea codeArea;
private final SearchParameters lastSearchParameters = new SearchParameters();
public BinarySearchServiceImpl(SectCodeArea codeArea) {
this.codeArea = codeArea;
}
@Override
public void performFind(SearchParameters searchParameters, SearchStatusListener searchStatusListener) {
SearchCodeAreaColorAssessor searchAssessor = CodeAreaSwingUtils
.findColorAssessor((ColorAssessorPainterCapable) codeArea.getPainter(), SearchCodeAreaColorAssessor.class);
SearchCondition condition = searchParameters.getCondition();
searchStatusListener.clearStatus();
if (condition.isEmpty()) {
searchAssessor.clearMatches();
codeArea.repaint();
return;
}
long position;
switch (searchParameters.getSearchDirection()) {
case FORWARD: {
if (searchParameters.isSearchFromCursor()) {
position = codeArea.getActiveCaretPosition().getDataPosition();
} else {
position = 0;
}
break;
}
case BACKWARD: {
if (searchParameters.isSearchFromCursor()) {
position = codeArea.getActiveCaretPosition().getDataPosition() - 1;
} else {
long searchDataSize;
switch (condition.getSearchMode()) {
case TEXT: {
searchDataSize = condition.getSearchText().length();
break;
}
case BINARY: {
searchDataSize = condition.getBinaryData().getDataSize();
break;
}
default:
throw CodeAreaUtils.getInvalidTypeException(condition.getSearchMode());
}
position = codeArea.getDataSize() - searchDataSize;
}
break;
}
default:
throw CodeAreaUtils.getInvalidTypeException(searchParameters.getSearchDirection());
}
searchParameters.setStartPosition(position);
switch (condition.getSearchMode()) {
case TEXT: {
searchForText(searchParameters, searchStatusListener);
break;
}
case BINARY: {
searchForBinaryData(searchParameters, searchStatusListener);
break;
}
default:
throw CodeAreaUtils.getInvalidTypeException(condition.getSearchMode());
}
}
/**
* Performs search by binary data.
*/
private void searchForBinaryData(SearchParameters searchParameters, SearchStatusListener searchStatusListener) {
SearchCodeAreaColorAssessor searchAssessor = CodeAreaSwingUtils
.findColorAssessor((ColorAssessorPainterCapable) codeArea.getPainter(), SearchCodeAreaColorAssessor.class);
SearchCondition condition = searchParameters.getCondition();
long position = searchParameters.getStartPosition();
BinaryData searchData = condition.getBinaryData();
long searchDataSize = searchData.getDataSize();
BinaryData data = codeArea.getContentData();
List<SearchMatch> foundMatches = new ArrayList<>();
long dataSize = data.getDataSize();
while (position >= 0 && position <= dataSize - searchDataSize) {
long matchLength = 0;
while (matchLength < searchDataSize) {
if (data.getByte(position + matchLength) != searchData.getByte(matchLength)) {
break;
}
matchLength++;
}
if (matchLength == searchDataSize) {
SearchMatch match = new SearchMatch();
match.setPosition(position);
match.setLength(searchDataSize);
if (searchParameters.getSearchDirection() == SearchParameters.SearchDirection.BACKWARD) {
foundMatches.add(0, match);
} else {
foundMatches.add(match);
}
if (foundMatches.size() == MAX_MATCHES_COUNT || searchParameters.getMatchMode() == SearchParameters.MatchMode.SINGLE) {
break;
}
}
position++;
}
searchAssessor.setMatches(foundMatches);
if (!foundMatches.isEmpty()) {
if (searchParameters.getSearchDirection() == SearchParameters.SearchDirection.BACKWARD) {
searchAssessor.setCurrentMatchIndex(foundMatches.size() - 1);
} else {
searchAssessor.setCurrentMatchIndex(0);
}
SearchMatch firstMatch = Objects.requireNonNull(searchAssessor.getCurrentMatch());
codeArea.revealPosition(firstMatch.getPosition(), 0, codeArea.getActiveSection());
}
lastSearchParameters.setFromParameters(searchParameters);
searchStatusListener.setStatus(
new FoundMatches(foundMatches.size(), foundMatches.isEmpty() ? -1 : searchAssessor.getCurrentMatchIndex()),
searchParameters.getMatchMode());
codeArea.repaint();
}
/**
* Performs search by text/characters.
*/
private void searchForText(SearchParameters searchParameters, SearchStatusListener searchStatusListener) {
SearchCodeAreaColorAssessor searchAssessor = CodeAreaSwingUtils
.findColorAssessor((ColorAssessorPainterCapable) codeArea.getPainter(), SearchCodeAreaColorAssessor.class);
SearchCondition condition = searchParameters.getCondition();
long position = searchParameters.getStartPosition();
String findText;
if (searchParameters.isMatchCase()) {
findText = condition.getSearchText();
} else {
findText = condition.getSearchText().toLowerCase();
}
long searchDataSize = findText.length();
BinaryData data = codeArea.getContentData();
List<SearchMatch> foundMatches = new ArrayList<>();
Charset charset = codeArea.getCharset();
int maxBytesPerChar;
try {
CharsetEncoder encoder = charset.newEncoder();
maxBytesPerChar = (int) encoder.maxBytesPerChar();
} catch (UnsupportedOperationException ex) {
maxBytesPerChar = CharsetStreamTranslator.DEFAULT_MAX_BYTES_PER_CHAR;
}
byte[] charData = new byte[maxBytesPerChar];
long dataSize = data.getDataSize();
long lastPosition = position;
while (position >= 0 && position <= dataSize - searchDataSize) {
int matchCharLength = 0;
int matchLength = 0;
while (matchCharLength < (int) searchDataSize) {
if (Thread.interrupted()) {
return;
}
long searchPosition = position + (long) matchLength;
int bytesToUse = maxBytesPerChar;
if (searchPosition + bytesToUse > dataSize) {
bytesToUse = (int) (dataSize - searchPosition);
}
if (searchPosition == lastPosition + 1) {
System.arraycopy(charData, 1, charData, 0, maxBytesPerChar - 1);
charData[bytesToUse - 1] = data.getByte(searchPosition + bytesToUse - 1);
} else if (searchPosition == lastPosition - 1) {
System.arraycopy(charData, 0, charData, 1, maxBytesPerChar - 1);
charData[0] = data.getByte(searchPosition);
} else {
data.copyToArray(searchPosition, charData, 0, bytesToUse);
}
if (bytesToUse < maxBytesPerChar) {
Arrays.fill(charData, bytesToUse, maxBytesPerChar, (byte) 0);
}
lastPosition = searchPosition;
char singleChar = new String(charData, charset).charAt(0);
if (searchParameters.isMatchCase()) {
if (singleChar != findText.charAt(matchCharLength)) {
break;
}
} else if (Character.toLowerCase(singleChar) != findText.charAt(matchCharLength)) {
break;
}
int characterLength = String.valueOf(singleChar).getBytes(charset).length;
matchCharLength++;
matchLength += characterLength;
}
if (matchCharLength == findText.length()) {
SearchMatch match = new SearchMatch();
match.setPosition(position);
match.setLength(matchLength);
if (searchParameters.getSearchDirection() == SearchParameters.SearchDirection.BACKWARD) {
foundMatches.add(0, match);
} else {
foundMatches.add(match);
}
if (foundMatches.size() == MAX_MATCHES_COUNT || searchParameters.getMatchMode() == SearchParameters.MatchMode.SINGLE) {
break;
}
}
switch (searchParameters.getSearchDirection()) {
case FORWARD: {
position++;
break;
}
case BACKWARD: {
position--;
break;
}
default:
throw CodeAreaUtils.getInvalidTypeException(searchParameters.getSearchDirection());
}
}
if (Thread.interrupted()) {
return;
}
searchAssessor.setMatches(foundMatches);
if (!foundMatches.isEmpty()) {
if (searchParameters.getSearchDirection() == SearchParameters.SearchDirection.BACKWARD) {
searchAssessor.setCurrentMatchIndex(foundMatches.size() - 1);
} else {
searchAssessor.setCurrentMatchIndex(0);
}
SearchMatch firstMatch = searchAssessor.getCurrentMatch();
codeArea.revealPosition(firstMatch.getPosition(), 0, codeArea.getActiveSection());
}
lastSearchParameters.setFromParameters(searchParameters);
searchStatusListener.setStatus(
new FoundMatches(foundMatches.size(), foundMatches.isEmpty() ? -1 : searchAssessor.getCurrentMatchIndex()),
searchParameters.getMatchMode());
codeArea.repaint();
}
@Override
public void setMatchPosition(int matchPosition) {
SearchCodeAreaColorAssessor searchAssessor = CodeAreaSwingUtils
.findColorAssessor((ColorAssessorPainterCapable) codeArea.getPainter(), SearchCodeAreaColorAssessor.class);
searchAssessor.setCurrentMatchIndex(matchPosition);
SearchMatch currentMatch = searchAssessor.getCurrentMatch();
codeArea.revealPosition(currentMatch.getPosition(), 0, codeArea.getActiveSection());
codeArea.repaint();
}
@Override
public void performFindAgain(SearchStatusListener searchStatusListener) {
SearchCodeAreaColorAssessor searchAssessor = CodeAreaSwingUtils
.findColorAssessor((ColorAssessorPainterCapable) codeArea.getPainter(), SearchCodeAreaColorAssessor.class);
List<SearchMatch> foundMatches = searchAssessor.getMatches();
int matchesCount = foundMatches.size();
if (matchesCount > 0) {
switch (lastSearchParameters.getMatchMode()) {
case MULTIPLE:
if (matchesCount > 1) {
int currentMatchIndex = searchAssessor.getCurrentMatchIndex();
setMatchPosition(currentMatchIndex < matchesCount - 1 ? currentMatchIndex + 1 : 0);
searchStatusListener.setStatus(new FoundMatches(foundMatches.size(), searchAssessor.getCurrentMatchIndex()),
lastSearchParameters.getMatchMode());
}
break;
case SINGLE:
switch (lastSearchParameters.getSearchDirection()) {
case FORWARD:
lastSearchParameters.setStartPosition(foundMatches.get(0).getPosition() + 1);
break;
case BACKWARD:
SearchMatch match = foundMatches.get(0);
lastSearchParameters.setStartPosition(match.getPosition() - 1);
break;
}
SearchCondition condition = lastSearchParameters.getCondition();
switch (condition.getSearchMode()) {
case TEXT: {
searchForText(lastSearchParameters, searchStatusListener);
break;
}
case BINARY: {
searchForBinaryData(lastSearchParameters, searchStatusListener);
break;
}
default:
throw CodeAreaUtils.getInvalidTypeException(condition.getSearchMode());
}
break;
}
}
}
@Override
public SearchParameters getLastSearchParameters() {
return lastSearchParameters;
}
@Override
public void clearMatches() {
SearchCodeAreaColorAssessor searchAssessor = CodeAreaSwingUtils
.findColorAssessor((ColorAssessorPainterCapable) codeArea.getPainter(), SearchCodeAreaColorAssessor.class);
searchAssessor.clearMatches();
}
}
| 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/hexviewer/search/service/BinarySearchService.java | jadx-gui/src/main/java/jadx/gui/ui/hexviewer/search/service/BinarySearchService.java | package jadx.gui.ui.hexviewer.search.service;
import jadx.gui.ui.hexviewer.search.SearchParameters;
public interface BinarySearchService {
void performFind(SearchParameters dialogSearchParameters, SearchStatusListener searchStatusListener);
void setMatchPosition(int matchPosition);
void performFindAgain(SearchStatusListener searchStatusListener);
SearchParameters getLastSearchParameters();
void clearMatches();
public interface SearchStatusListener {
void setStatus(FoundMatches foundMatches, SearchParameters.MatchMode matchMode);
void clearStatus();
}
public static class FoundMatches {
private int matchesCount;
private int matchPosition;
public FoundMatches() {
matchesCount = 0;
matchPosition = -1;
}
public FoundMatches(int matchesCount, int matchPosition) {
if (matchPosition >= matchesCount) {
throw new IllegalStateException("Match position is out of range");
}
this.matchesCount = matchesCount;
this.matchPosition = matchPosition;
}
public int getMatchesCount() {
return matchesCount;
}
public int getMatchPosition() {
return matchPosition;
}
public void setMatchesCount(int matchesCount) {
this.matchesCount = matchesCount;
}
public void setMatchPosition(int matchPosition) {
this.matchPosition = matchPosition;
}
public void next() {
if (matchPosition == matchesCount - 1) {
throw new IllegalStateException("Cannot find next on last match");
}
matchPosition++;
}
public void prev() {
if (matchPosition == 0) {
throw new IllegalStateException("Cannot find previous on first match");
}
matchPosition--;
}
}
}
| 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/treenodes/SummaryNode.java | jadx-gui/src/main/java/jadx/gui/ui/treenodes/SummaryNode.java | package jadx.gui.ui.treenodes;
import java.io.File;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import jadx.api.ICodeInfo;
import jadx.api.ResourceFile;
import jadx.api.impl.SimpleCodeInfo;
import jadx.core.dex.attributes.IAttributeNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.ProcessState;
import jadx.core.utils.ErrorsCounter;
import jadx.core.utils.Utils;
import jadx.gui.JadxWrapper;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.panel.HtmlPanel;
import jadx.gui.ui.tab.TabbedPane;
import jadx.gui.utils.UiUtils;
public class SummaryNode extends JNode {
private static final long serialVersionUID = 4295299814582784805L;
private static final ImageIcon ICON = UiUtils.openSvgIcon("nodes/detailView");
private final MainWindow mainWindow;
private final JadxWrapper wrapper;
public SummaryNode(MainWindow mainWindow) {
this.mainWindow = mainWindow;
this.wrapper = mainWindow.getWrapper();
}
@Override
public ICodeInfo getCodeInfo() {
StringEscapeUtils.Builder builder = StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_HTML4);
try {
builder.append("<html>");
builder.append("<body>");
writeInputSummary(builder);
writeDecompilationSummary(builder);
builder.append("</body>");
} catch (Exception e) {
builder.append("Error build summary: ");
builder.append("<pre>");
builder.append(Utils.getStackTrace(e));
builder.append("</pre>");
}
return new SimpleCodeInfo(builder.toString());
}
private void writeInputSummary(StringEscapeUtils.Builder builder) throws IOException {
builder.append("<h2>Input</h2>");
builder.append("<h3>Files</h3>");
builder.append("<ul>");
for (File inputFile : wrapper.getArgs().getInputFiles()) {
builder.append("<li>");
builder.escape(inputFile.getCanonicalFile().getAbsolutePath());
builder.append("</li>");
}
builder.append("</ul>");
List<ClassNode> classes = wrapper.getRootNode().getClasses(true);
List<String> codeSources = classes.stream()
.map(ClassNode::getInputFileName)
.distinct()
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList());
codeSources.remove("synthetic");
int codeSourcesCount = codeSources.size();
builder.append("<h3>Code sources</h3>");
builder.append("<ul>");
if (codeSourcesCount != 1) {
builder.append("<li>Count: " + codeSourcesCount + "</li>");
}
for (String input : codeSources) {
builder.append("<li>");
builder.escape(input);
builder.append("</li>");
}
builder.append("</ul>");
addNativeLibsInfo(builder);
int methodsCount = classes.stream().mapToInt(cls -> cls.getMethods().size()).sum();
int fieldsCount = classes.stream().mapToInt(cls -> cls.getFields().size()).sum();
int insnCount = classes.stream().flatMap(cls -> cls.getMethods().stream()).mapToInt(MethodNode::getInsnsCount).sum();
builder.append("<h3>Counts</h3>");
builder.append("<ul>");
builder.append("<li>Classes: " + classes.size() + "</li>");
builder.append("<li>Methods: " + methodsCount + "</li>");
builder.append("<li>Fields: " + fieldsCount + "</li>");
builder.append("<li>Instructions: " + insnCount + " (units)</li>");
builder.append("</ul>");
}
private void addNativeLibsInfo(StringEscapeUtils.Builder builder) {
List<String> nativeLibs = wrapper.getResources().stream()
.map(ResourceFile::getOriginalName)
.filter(f -> f.endsWith(".so"))
.sorted(Comparator.naturalOrder())
.collect(Collectors.toList());
builder.append("<h3>Native libs</h3>");
builder.append("<ul>");
if (nativeLibs.isEmpty()) {
builder.append("<li>Total count: 0</li>");
} else {
Map<String, Set<String>> libsByArch = new HashMap<>();
for (String libFile : nativeLibs) {
String[] parts = StringUtils.split(libFile, '/');
int count = parts.length;
if (count >= 2) {
String arch = parts[count - 2];
String name = parts[count - 1];
libsByArch.computeIfAbsent(arch, (a) -> new HashSet<>())
.add(name);
}
}
String arches = libsByArch.keySet().stream()
.sorted(Comparator.naturalOrder())
.collect(Collectors.joining(", "));
builder.append("<li>Arch list: " + arches + "</li>");
String perArchCount = libsByArch.entrySet().stream()
.map(entry -> entry.getKey() + ":" + entry.getValue().size())
.sorted(Comparator.naturalOrder())
.collect(Collectors.joining(", "));
builder.append("<li>Per arch count: " + perArchCount + "</li>");
builder.append("<br>");
builder.append("<li>Total count: " + nativeLibs.size() + "</li>");
for (String lib : nativeLibs) {
builder.append("<li>");
builder.escape(lib);
builder.append("</li>");
}
}
builder.append("</ul>");
}
private void writeDecompilationSummary(StringEscapeUtils.Builder builder) {
builder.append("<h2>Decompilation</h2>");
List<ClassNode> classes = wrapper.getRootNode().getClassesWithoutInner();
int classesCount = classes.size();
long notLoadedClasses = classes.stream().filter(c -> c.getState() == ProcessState.NOT_LOADED).count();
long loadedClasses = classes.stream().filter(c -> c.getState() == ProcessState.LOADED).count();
long processedClasses = classes.stream().filter(c -> c.getState() == ProcessState.PROCESS_COMPLETE).count();
long generatedClasses = classes.stream().filter(c -> c.getState() == ProcessState.GENERATED_AND_UNLOADED).count();
builder.append("<ul>");
builder.append("<li>Top level classes: " + classesCount + "</li>");
builder.append("<li>Not loaded: " + valueAndPercent(notLoadedClasses, classesCount) + "</li>");
builder.append("<li>Loaded: " + valueAndPercent(loadedClasses, classesCount) + "</li>");
builder.append("<li>Processed: " + valueAndPercent(processedClasses, classesCount) + "</li>");
builder.append("<li>Code generated: " + valueAndPercent(generatedClasses, classesCount) + "</li>");
builder.append("</ul>");
ErrorsCounter counter = wrapper.getRootNode().getErrorsCounter();
Set<IAttributeNode> problemNodes = new HashSet<>();
problemNodes.addAll(counter.getErrorNodes());
problemNodes.addAll(counter.getWarnNodes());
long problemMethods = problemNodes.stream().filter(MethodNode.class::isInstance).count();
int methodsCount = classes.stream().mapToInt(cls -> cls.getMethods().size()).sum();
double methodSuccessRate = (methodsCount - problemMethods) * 100.0 / (double) methodsCount;
builder.append("<h3>Issues</h3>");
builder.append("<ul>");
builder.append("<li>Errors: " + counter.getErrorCount() + "</li>");
builder.append("<li>Warnings: " + counter.getWarnsCount() + "</li>");
builder.append("<li>Nodes with errors: " + counter.getErrorNodes().size() + "</li>");
builder.append("<li>Nodes with warnings: " + counter.getWarnNodes().size() + "</li>");
builder.append("<li>Total nodes with issues: " + problemNodes.size() + "</li>");
builder.append("<li>Methods with issues: " + problemMethods + "</li>");
builder.append("<li>Methods success rate: " + String.format("%.2f", methodSuccessRate) + "%</li>");
builder.append("</ul>");
}
private String valueAndPercent(long value, int total) {
return String.format("%d (%.2f%%)", value, value * 100 / ((double) total));
}
@Override
public boolean hasContent() {
return true;
}
@Override
public ContentPanel getContentPanel(TabbedPane tabbedPane) {
return new HtmlPanel(tabbedPane, this);
}
@Override
public String makeString() {
return "Summary";
}
@Override
public Icon getIcon() {
return ICON;
}
@Override
public JClass getJParent() {
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/treenodes/UndisplayedStringsNode.java | jadx-gui/src/main/java/jadx/gui/ui/treenodes/UndisplayedStringsNode.java | package jadx.gui.ui.treenodes;
import javax.swing.Icon;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.panel.UndisplayedStringsPanel;
import jadx.gui.ui.tab.TabbedPane;
import jadx.gui.utils.Icons;
import jadx.gui.utils.NLS;
public class UndisplayedStringsNode extends JNode {
private static final long serialVersionUID = 2005158949697898302L;
private final String undisplayedStings;
public UndisplayedStringsNode(String undisplayedStings) {
this.undisplayedStings = undisplayedStings;
}
@Override
public boolean hasContent() {
return true;
}
@Override
public ContentPanel getContentPanel(TabbedPane tabbedPane) {
return new UndisplayedStringsPanel(tabbedPane, this);
}
@Override
public String makeString() {
return NLS.str("msg.non_displayable_chars.title");
}
@Override
public Icon getIcon() {
return Icons.FONT;
}
@Override
public JClass getJParent() {
return null;
}
@Override
public String makeDescString() {
return undisplayedStings;
}
@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/export/ExportProjectProperties.java | jadx-gui/src/main/java/jadx/gui/ui/export/ExportProjectProperties.java | package jadx.gui.ui.export;
import org.jetbrains.annotations.Nullable;
import jadx.core.export.ExportGradleType;
public class ExportProjectProperties {
private boolean skipSources;
private boolean skipResources;
private boolean asGradleMode;
private @Nullable ExportGradleType exportGradleType;
private String exportPath;
public boolean isSkipSources() {
return skipSources;
}
public void setSkipSources(boolean skipSources) {
this.skipSources = skipSources;
}
public boolean isSkipResources() {
return skipResources;
}
public void setSkipResources(boolean skipResources) {
this.skipResources = skipResources;
}
public boolean isAsGradleMode() {
return asGradleMode;
}
public void setAsGradleMode(boolean asGradleMode) {
this.asGradleMode = asGradleMode;
}
public @Nullable ExportGradleType getExportGradleType() {
return exportGradleType;
}
public void setExportGradleType(@Nullable ExportGradleType exportGradleType) {
this.exportGradleType = exportGradleType;
}
public String getExportPath() {
return exportPath;
}
public void setExportPath(String exportPath) {
this.exportPath = exportPath;
}
@Override
public String toString() {
return "ExportProjectProperties{exportPath='" + exportPath + '\''
+ ", asGradleMode=" + asGradleMode
+ ", exportGradleType=" + exportGradleType
+ ", skipSources=" + skipSources
+ ", skipResources=" + skipResources
+ '}';
}
}
| 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/export/ExportProjectDialog.java | jadx-gui/src/main/java/jadx/gui/ui/export/ExportProjectDialog.java | package jadx.gui.ui.export;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.nio.file.Files;
import java.nio.file.Path;
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.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.export.ExportGradle;
import jadx.core.export.ExportGradleType;
import jadx.core.utils.files.FileUtils;
import jadx.gui.JadxWrapper;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.dialog.CommonDialog;
import jadx.gui.ui.filedialog.FileDialogWrapper;
import jadx.gui.ui.filedialog.FileOpenMode;
import jadx.gui.utils.NLS;
import jadx.gui.utils.TextStandardActions;
import jadx.gui.utils.ui.DocumentUpdateListener;
public class ExportProjectDialog extends CommonDialog {
private static final Logger LOG = LoggerFactory.getLogger(ExportProjectDialog.class);
private final ExportProjectProperties exportProjectProperties = new ExportProjectProperties();
private final Consumer<ExportProjectProperties> exportListener;
public ExportProjectDialog(MainWindow mainWindow, Consumer<ExportProjectProperties> exportListener) {
super(mainWindow);
this.exportListener = exportListener;
initUI();
}
private void initUI() {
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout(5, 5));
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPanel.add(makeContentPane(), BorderLayout.PAGE_START);
contentPanel.add(initButtonsPanel(), BorderLayout.PAGE_END);
getContentPane().add(contentPanel);
setTitle(NLS.str("export_dialog.title"));
commonWindowInit();
}
private JPanel makeContentPane() {
JLabel pathLbl = new JLabel(NLS.str("export_dialog.save_path"));
JTextField pathField = new JTextField();
pathField.getDocument().addDocumentListener(new DocumentUpdateListener(ev -> setExportProjectPath(pathField)));
pathField.setText(mainWindow.getSettings().getLastSaveFilePath().toString());
TextStandardActions.attach(pathField);
JButton browseButton = makeEditorBrowseButton(pathField);
JCheckBox resourceDecode = new JCheckBox(NLS.str("preferences.skipResourcesDecode"));
resourceDecode.setSelected(mainWindow.getSettings().isSkipResources());
resourceDecode.addItemListener(e -> {
exportProjectProperties.setSkipResources(e.getStateChange() == ItemEvent.SELECTED);
});
JCheckBox skipSources = new JCheckBox(NLS.str("preferences.skipSourcesDecode"));
skipSources.setSelected(mainWindow.getSettings().isSkipSources());
skipSources.addItemListener(e -> {
exportProjectProperties.setSkipSources(e.getStateChange() == ItemEvent.SELECTED);
});
JLabel exportTypeLbl = new JLabel(NLS.str("export_dialog.export_gradle_type"));
JComboBox<ExportGradleType> exportTypeComboBox = new JComboBox<>(ExportGradleType.values());
exportTypeLbl.setLabelFor(exportTypeComboBox);
ExportGradleType initialExportType = getExportGradleType();
exportProjectProperties.setExportGradleType(initialExportType);
exportTypeComboBox.setSelectedItem(initialExportType);
exportTypeComboBox.addItemListener(e -> {
exportProjectProperties.setExportGradleType((ExportGradleType) e.getItem());
});
exportTypeComboBox.setEnabled(false);
JCheckBox exportAsGradleProject = new JCheckBox(NLS.str("export_dialog.export_gradle"));
exportAsGradleProject.addItemListener(e -> {
boolean enableGradle = e.getStateChange() == ItemEvent.SELECTED;
exportProjectProperties.setAsGradleMode(enableGradle);
exportTypeComboBox.setEnabled(enableGradle);
resourceDecode.setEnabled(!enableGradle);
skipSources.setEnabled(!enableGradle);
});
JPanel pathPanel = new JPanel();
pathPanel.setLayout(new BoxLayout(pathPanel, BoxLayout.LINE_AXIS));
pathPanel.setAlignmentX(LEFT_ALIGNMENT);
pathPanel.add(pathLbl);
pathPanel.add(Box.createRigidArea(new Dimension(5, 0)));
pathPanel.add(pathField);
pathPanel.add(Box.createRigidArea(new Dimension(5, 0)));
pathPanel.add(browseButton);
JPanel typePanel = new JPanel();
typePanel.setLayout(new BoxLayout(typePanel, BoxLayout.LINE_AXIS));
typePanel.setAlignmentX(LEFT_ALIGNMENT);
typePanel.add(Box.createRigidArea(new Dimension(20, 0)));
typePanel.add(exportTypeLbl);
typePanel.add(Box.createRigidArea(new Dimension(5, 0)));
typePanel.add(exportTypeComboBox);
typePanel.add(Box.createHorizontalGlue());
JPanel exportOptionsPanel = new JPanel();
exportOptionsPanel.setBorder(BorderFactory.createTitledBorder(NLS.str("export_dialog.export_options")));
exportOptionsPanel.setLayout(new BoxLayout(exportOptionsPanel, BoxLayout.PAGE_AXIS));
exportOptionsPanel.add(exportAsGradleProject);
exportOptionsPanel.add(typePanel);
exportOptionsPanel.add(resourceDecode);
exportOptionsPanel.add(skipSources);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.add(pathPanel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 10)));
mainPanel.add(exportOptionsPanel);
return mainPanel;
}
private ExportGradleType getExportGradleType() {
try {
JadxWrapper wrapper = mainWindow.getWrapper();
return ExportGradle.detectExportType(wrapper.getRootNode(), wrapper.getResources());
} catch (Exception e) {
LOG.warn("Failed to detect export type", e);
return ExportGradleType.AUTO;
}
}
private void setExportProjectPath(JTextField field) {
String path = field.getText();
if (!path.isEmpty()) {
exportProjectProperties.setExportPath(field.getText());
}
}
protected JPanel initButtonsPanel() {
JButton cancelButton = new JButton(NLS.str("common_dialog.cancel"));
cancelButton.addActionListener(event -> dispose());
JButton exportProjectButton = new JButton(NLS.str("common_dialog.ok"));
exportProjectButton.addActionListener(event -> exportProject());
getRootPane().setDefaultButton(exportProjectButton);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(exportProjectButton);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(cancelButton);
return buttonPane;
}
private JButton makeEditorBrowseButton(final JTextField textField) {
JButton button = new JButton(NLS.str("export_dialog.browse"));
button.addActionListener(e -> {
FileDialogWrapper fileDialog = new FileDialogWrapper(mainWindow, FileOpenMode.EXPORT);
mainWindow.getSettings().setLastSaveFilePath(fileDialog.getCurrentDir());
List<Path> saveDirs = fileDialog.show();
if (saveDirs.isEmpty()) {
return;
}
String path = saveDirs.get(0).toString();
textField.setText(path);
});
return button;
}
private void exportProject() {
String exportPathStr = exportProjectProperties.getExportPath();
if (!validateAndMakeDir(exportPathStr)) {
JOptionPane.showMessageDialog(this, NLS.str("message.enter_valid_path"),
NLS.str("message.errorTitle"), JOptionPane.WARNING_MESSAGE);
return;
}
mainWindow.getSettings().setLastSaveFilePath(Path.of(exportPathStr));
LOG.debug("Export properties: {}", exportProjectProperties);
exportListener.accept(exportProjectProperties);
dispose();
}
private static boolean validateAndMakeDir(String exportPath) {
if (exportPath == null || exportPath.isBlank()) {
return false;
}
try {
Path path = Path.of(exportPath);
if (Files.isRegularFile(path)) {
// dir exists as a file
return false;
}
FileUtils.makeDirs(path);
return true;
} catch (Exception e) {
LOG.warn("Export path validate error, path string:{}", exportPath, 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/menu/JadxMenuBar.java | jadx-gui/src/main/java/jadx/gui/ui/menu/JadxMenuBar.java | package jadx.gui.ui.menu;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class JadxMenuBar extends JMenuBar {
public void reloadShortcuts() {
for (int i = 0; i < getMenuCount(); i++) {
JMenu menu = getMenu(i);
if (menu instanceof JadxMenu) {
((JadxMenu) menu).reloadShortcuts();
}
}
}
}
| 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/menu/HiddenMenuItem.java | jadx-gui/src/main/java/jadx/gui/ui/menu/HiddenMenuItem.java | package jadx.gui.ui.menu;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.Action;
import javax.swing.JMenuItem;
public class HiddenMenuItem extends JMenuItem {
public HiddenMenuItem(Action a) {
super(a);
}
@Override
protected void paintComponent(Graphics g) {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(0, 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/menu/JadxMenu.java | jadx-gui/src/main/java/jadx/gui/ui/menu/JadxMenu.java | package jadx.gui.ui.menu;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import jadx.gui.ui.action.ActionModel;
import jadx.gui.ui.action.JadxGuiAction;
import jadx.gui.utils.shortcut.Shortcut;
import jadx.gui.utils.shortcut.ShortcutsController;
public class JadxMenu extends JMenu {
// fake component to fill action shortcut component property
public static final JComponent JADX_MENU_COMPONENT = new JComponent() {
@Override
public String toString() {
return "JADX_MENU_COMPONENT";
}
};
private final ShortcutsController shortcutsController;
public JadxMenu(String name, ShortcutsController shortcutsController) {
super(name);
this.shortcutsController = shortcutsController;
}
@Override
public JMenuItem add(JMenuItem menuItem) {
Action action = menuItem.getAction();
bindAction(action);
return super.add(menuItem);
}
@Override
public JMenuItem add(Action action) {
bindAction(action);
return super.add(action);
}
public void bindAction(Action action) {
if (action instanceof JadxGuiAction) {
JadxGuiAction guiAction = (JadxGuiAction) action;
JComponent shortcutComponent = guiAction.getShortcutComponent();
if (shortcutComponent == null) {
guiAction.setShortcutComponent(JADX_MENU_COMPONENT);
}
shortcutsController.bind(guiAction);
}
}
public void reloadShortcuts() {
for (int i = 0; i < getItemCount(); i++) {
// TODO only repaint the items whose shortcut changed
JMenuItem item = getItem(i);
if (item == null) {
continue;
}
Action action = item.getAction();
if (!(action instanceof JadxGuiAction) || ((JadxGuiAction) action).getActionModel() == null) {
continue;
}
ActionModel actionModel = ((JadxGuiAction) action).getActionModel();
Shortcut shortcut = shortcutsController.get(actionModel);
if (shortcut != null) {
item.setAccelerator(shortcut.toKeyStroke());
} else {
item.setAccelerator(null);
}
item.repaint();
item.revalidate();
}
}
}
| 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/tab/TabComponent.java | jadx-gui/src/main/java/jadx/gui/ui/tab/TabComponent.java | package jadx.gui.ui.tab;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicButtonUI;
import jadx.core.utils.ListUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
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.ActionModel;
import jadx.gui.ui.action.JadxGuiAction;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.tab.dnd.TabDndGestureListener;
import jadx.gui.utils.Icons;
import jadx.gui.utils.NLS;
import jadx.gui.utils.OverlayIcon;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.NodeLabel;
public class TabComponent extends JPanel {
private static final long serialVersionUID = -8147035487543610321L;
private final TabbedPane tabbedPane;
private final TabsController tabsController;
private final ContentPanel contentPanel;
private OverlayIcon icon;
private JLabel label;
private JButton pinBtn;
private JButton closeBtn;
public TabComponent(TabbedPane tabbedPane, ContentPanel contentPanel) {
this.tabbedPane = tabbedPane;
this.tabsController = tabbedPane.getMainWindow().getTabsController();
this.contentPanel = contentPanel;
init();
}
public void loadSettings() {
label.setFont(getLabelFont());
if (tabbedPane.getDnd() != null) {
tabbedPane.getDnd().loadSettings();
}
}
private Font getLabelFont() {
Font font = tabsController.getMainWindow().getSettings().getCodeFont();
int style = font.getStyle();
style |= Font.BOLD;
if (getBlueprint().isPreviewTab()) {
style ^= Font.ITALIC; // flip italic bit to distinguish preview
}
return font.deriveFont(style);
}
private void init() {
setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
setOpaque(false);
JNode node = getNode();
icon = new OverlayIcon(node.getIcon());
label = new NodeLabel(buildTabTitle(node), node.disableHtml());
String toolTip = contentPanel.getTabTooltip();
if (toolTip != null) {
setToolTipText(toolTip);
}
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
label.setIcon(icon);
if (node instanceof JEditableNode) {
((JEditableNode) node).addChangeListener(c -> label.setText(buildTabTitle(node)));
}
pinBtn = new JButton();
pinBtn.setIcon(Icons.PIN);
pinBtn.setRolloverIcon(Icons.PIN_HOVERED);
pinBtn.setRolloverEnabled(true);
pinBtn.setOpaque(false);
pinBtn.setUI(new BasicButtonUI());
pinBtn.setContentAreaFilled(false);
pinBtn.setBorder(null);
pinBtn.setBorderPainted(false);
pinBtn.addActionListener(e -> togglePin());
closeBtn = new JButton();
closeBtn.setIcon(Icons.CLOSE_INACTIVE);
closeBtn.setRolloverIcon(Icons.CLOSE);
closeBtn.setRolloverEnabled(true);
closeBtn.setOpaque(false);
closeBtn.setUI(new BasicButtonUI());
closeBtn.setContentAreaFilled(false);
closeBtn.setFocusable(false);
closeBtn.setBorder(null);
closeBtn.setBorderPainted(false);
closeBtn.addActionListener(e -> {
tabsController.closeTab(node, true);
});
MouseAdapter clickAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isMiddleMouseButton(e)) {
tabsController.closeTab(node, true);
} else if (SwingUtilities.isRightMouseButton(e)) {
JPopupMenu menu = createTabPopupMenu();
menu.show(e.getComponent(), e.getX(), e.getY());
} else if (SwingUtilities.isLeftMouseButton(e)) {
tabsController.selectTab(node);
if (e.getClickCount() == 2) {
tabsController.setTabPreview(node, false);
}
}
}
};
addMouseListener(clickAdapter);
addListenerForDnd();
add(label);
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
update();
}
public void update() {
updateCloseOrPinButton();
updateBookmarkIcon();
updateFont();
}
private void updateCloseOrPinButton() {
if (getBlueprint().isPinned()) {
if (closeBtn.isShowing()) {
remove(closeBtn);
}
if (!pinBtn.isShowing()) {
add(pinBtn);
}
} else {
if (pinBtn.isShowing()) {
remove(pinBtn);
}
if (!closeBtn.isShowing()) {
add(closeBtn);
}
}
}
private void updateBookmarkIcon() {
icon.clear();
if (getBlueprint().isBookmarked()) {
icon.add(Icons.BOOKMARK_OVERLAY_DARK);
}
label.repaint();
}
private void togglePin() {
boolean pinned = !getBlueprint().isPinned();
tabsController.setTabPinned(getNode(), pinned);
if (pinned) {
tabsController.setTabPositionFirst(getNode());
}
}
private void toggleBookmark() {
boolean bookmarked = !getBlueprint().isBookmarked();
tabsController.setTabBookmarked(getNode(), bookmarked);
}
private void updateFont() {
label.setFont(getLabelFont());
}
private void addListenerForDnd() {
if (tabbedPane.getDnd() == null) {
return;
}
TabComponent comp = this;
DragGestureListener dgl = new TabDndGestureListener(tabbedPane.getDnd()) {
@Override
protected Point getDragOrigin(DragGestureEvent e) {
return SwingUtilities.convertPoint(comp, e.getDragOrigin(), tabbedPane);
}
};
DragSource.getDefaultDragSource()
.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);
}
private String buildTabTitle(JNode node) {
String tabTitle;
if (node.getRootClass() != null) {
tabTitle = node.getRootClass().getName();
} else {
tabTitle = node.makeLongStringHtml();
}
if (node instanceof JEditableNode) {
if (((JEditableNode) node).isChanged()) {
return "*" + tabTitle;
}
}
return tabTitle;
}
private JPopupMenu createTabPopupMenu() {
JPopupMenu menu = new JPopupMenu();
String nodeFullName = getNodeFullName(contentPanel);
if (nodeFullName != null) {
JMenuItem copyRootClassName = new JMenuItem(NLS.str("tabs.copy_class_name"));
copyRootClassName.addActionListener(actionEvent -> UiUtils.setClipboardString(nodeFullName));
menu.add(copyRootClassName);
menu.addSeparator();
}
if (getBlueprint().supportsQuickTabs()) {
String pinTitle = getBlueprint().isPinned() ? NLS.str("tabs.unpin") : NLS.str("tabs.pin");
JMenuItem pinTab = new JMenuItem(pinTitle);
pinTab.addActionListener(e -> togglePin());
menu.add(pinTab);
JMenuItem unpinAll = new JMenuItem(NLS.str("tabs.unpin_all"));
unpinAll.addActionListener(e -> tabsController.unpinAllTabs());
menu.add(unpinAll);
String bookmarkTitle = getBlueprint().isBookmarked() ? NLS.str("tabs.unbookmark") : NLS.str("tabs.bookmark");
JMenuItem bookmarkTab = new JMenuItem(bookmarkTitle);
bookmarkTab.addActionListener(e -> toggleBookmark());
menu.add(bookmarkTab);
JMenuItem unbookmarkAll = new JMenuItem(NLS.str("tabs.unbookmark_all"));
unbookmarkAll.addActionListener(e -> tabsController.unbookmarkAllTabs());
menu.add(unbookmarkAll);
menu.addSeparator();
}
if (nodeFullName != null) {
MainWindow mainWindow = tabsController.getMainWindow();
JadxGuiAction selectInTree = new JadxGuiAction(ActionModel.SYNC, () -> mainWindow.selectNodeInTree(getNode()));
// attach shortcut without bind only to show current keybinding
selectInTree.setShortcut(mainWindow.getShortcutsController().get(ActionModel.SYNC));
menu.add(selectInTree);
menu.addSeparator();
}
JMenuItem closeTab = new JMenuItem(NLS.str("tabs.close"));
closeTab.addActionListener(e -> tabsController.closeTab(getNode(), true));
if (getBlueprint().isPinned()) {
closeTab.setEnabled(false);
}
menu.add(closeTab);
List<TabBlueprint> tabs = tabsController.getOpenTabs();
if (tabs.size() > 1) {
JMenuItem closeOther = new JMenuItem(NLS.str("tabs.closeOthers"));
closeOther.addActionListener(e -> {
JNode currentNode = getNode();
for (TabBlueprint tab : tabs) {
if (tab.getNode() != currentNode) {
tabsController.closeTab(tab, true);
}
}
});
menu.add(closeOther);
JMenuItem closeAll = new JMenuItem(NLS.str("tabs.closeAll"));
closeAll.addActionListener(e -> tabsController.closeAllTabs(true));
menu.add(closeAll);
// We don't use TabsController here because tabs position is
// specific to TabbedPane
List<ContentPanel> contentPanels = tabbedPane.getTabs();
int currentIndex = contentPanels.indexOf(contentPanel);
if (currentIndex > 0) { // Add item only if there are tabs on the left (index > 0)
JMenuItem closeAllLeft = new JMenuItem(NLS.str("tabs.closeAllLeft"));
closeAllLeft.addActionListener(e -> {
// Iterate in reverse order from the index before the current tab to the beginning
for (int i = currentIndex - 1; i >= 0; i--) {
ContentPanel panelToClose = contentPanels.get(i);
tabsController.closeTab(panelToClose.getNode(), true);
}
});
menu.add(closeAllLeft);
}
if (contentPanel != ListUtils.last(contentPanels)) {
JMenuItem closeAllRight = new JMenuItem(NLS.str("tabs.closeAllRight"));
closeAllRight.addActionListener(e -> {
boolean pastCurrentPanel = false;
for (ContentPanel panel : contentPanels) {
if (!pastCurrentPanel) {
if (panel == contentPanel) {
pastCurrentPanel = true;
}
} else {
tabsController.closeTab(panel.getNode(), true);
}
}
});
menu.add(closeAllRight);
}
menu.addSeparator();
TabBlueprint selectedTab = tabsController.getSelectedTab();
for (TabBlueprint tab : tabs) {
if (tab == selectedTab) {
continue;
}
JNode node = tab.getNode();
final String clsName = node.makeLongString();
JMenuItem item = new JMenuItem(clsName);
item.addActionListener(e -> tabsController.codeJump(node));
item.setIcon(node.getIcon());
menu.add(item);
}
}
return menu;
}
private String getNodeFullName(ContentPanel contentPanel) {
JNode node = contentPanel.getNode();
JClass jClass = node.getRootClass();
if (jClass != null) {
return jClass.getFullName();
}
return node.getName();
}
public ContentPanel getContentPanel() {
return contentPanel;
}
public TabBlueprint getBlueprint() {
JNode node = contentPanel.getNode();
TabBlueprint blueprint = tabsController.getTabByNode(node);
if (blueprint == null) {
throw new JadxRuntimeException("TabComponent does not have a corresponding TabBlueprint, node: " + node);
}
return blueprint;
}
public JNode getNode() {
return contentPanel.getNode();
}
}
| 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/tab/TabsController.java | jadx-gui/src/main/java/jadx/gui/ui/tab/TabsController.java | package jadx.gui.ui.tab;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JavaClass;
import jadx.api.metadata.ICodeAnnotation;
import jadx.api.metadata.ICodeNodeRef;
import jadx.api.metadata.annotations.NodeDeclareRef;
import jadx.gui.jobs.SimpleTask;
import jadx.gui.jobs.TaskWithExtraOnFinish;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.codearea.EditorViewState;
import jadx.gui.utils.JumpPosition;
import jadx.gui.utils.UiUtils;
public class TabsController {
private static final Logger LOG = LoggerFactory.getLogger(TabsController.class);
private final MainWindow mainWindow;
private final Map<JNode, TabBlueprint> tabsMap = new HashMap<>();
private final List<ITabStatesListener> listeners = new ArrayList<>();
private boolean forceClose;
private @Nullable TabBlueprint selectedTab;
public TabsController(MainWindow mainWindow) {
this.mainWindow = mainWindow;
if (UiUtils.JADX_GUI_DEBUG) {
addListener(new LogTabStates());
}
}
public MainWindow getMainWindow() {
return mainWindow;
}
public void addListener(ITabStatesListener listener) {
listeners.add(listener);
}
public void removeListener(ITabStatesListener listener) {
listeners.remove(listener);
}
public @Nullable TabBlueprint getTabByNode(JNode node) {
return tabsMap.get(node);
}
public TabBlueprint openTab(JNode node) {
return openTab(node, false, false);
}
public TabBlueprint openTab(JNode node, boolean hidden, boolean preview) {
if (!node.hasContent()) {
LOG.warn("Can't open tab for node without content, node: {}", node);
}
TabBlueprint blueprint = getTabByNode(node);
if (blueprint == null) {
TabBlueprint newBlueprint = new TabBlueprint(node);
newBlueprint.setHidden(hidden);
newBlueprint.setPreviewTab(preview);
tabsMap.put(node, newBlueprint);
listeners.forEach(l -> l.onTabOpen(newBlueprint));
if (hidden) {
listeners.forEach(l -> l.onTabVisibilityChange(newBlueprint));
}
blueprint = newBlueprint;
}
setTabHiddenInternal(blueprint, hidden);
return blueprint;
}
public TabBlueprint previewTab(JNode node) {
TabBlueprint blueprint = getPreviewTab();
if (blueprint != null) {
closeTab(blueprint.getNode());
}
return openTab(node, false, true);
}
public void selectTab(JNode node) {
selectTab(node, false);
}
public void selectTab(JNode node, boolean fromTree) {
if (selectedTab != null && selectedTab.getNode() == node) {
// already selected
return;
}
if (mainWindow.getSettings().isEnablePreviewTab() && fromTree) {
selectedTab = previewTab(node);
} else {
selectedTab = openTab(node);
}
listeners.forEach(l -> l.onTabSelect(selectedTab));
}
public void deselectTab() {
selectedTab = null;
}
/**
* Jump to node definition
*/
public void codeJump(JNode node) {
codeJump(node, false);
}
/**
* Jump to node definition
*/
public void codeJump(JNode node, boolean fromTree) {
JClass parentCls = node.getJParent();
if (parentCls != null) {
// handle jump to inner class, method or field:
// - load parent
// - search position and jump to it
JavaClass cls = node.getJParent().getCls();
JavaClass origTopCls = cls.getOriginalTopParentClass();
JavaClass codeParent = cls.getTopParentClass();
if (!Objects.equals(codeParent, origTopCls)) {
JClass jumpCls = mainWindow.getCacheObject().getNodeCache().makeFrom(codeParent);
loadCodeWithUIAction(jumpCls, () -> jumpToInnerClass(node, codeParent, jumpCls, fromTree));
return;
}
}
if (node.getRootClass() == null) {
// not a class, select tab (without position scroll)
selectTab(node, fromTree);
return;
}
codeJump(new JumpPosition(node), fromTree);
}
private void loadCodeWithUIAction(JClass cls, Runnable action) {
SimpleTask loadTask = cls.getLoadTask();
if (loadTask == null) {
// already loaded
UiUtils.uiRun(action);
return;
}
mainWindow.getBackgroundExecutor().execute(new TaskWithExtraOnFinish(loadTask, action));
}
/**
* Search and jump to original node in jumpCls
*/
private void jumpToInnerClass(JNode node, JavaClass codeParent, JClass jumpCls, boolean fromTree) {
codeParent.getCodeInfo().getCodeMetadata().searchDown(0, (pos, ann) -> {
if (ann.getAnnType() == ICodeAnnotation.AnnType.DECLARATION) {
ICodeNodeRef declNode = ((NodeDeclareRef) ann).getNode();
if (declNode.equals(node.getJavaNode().getCodeNodeRef())) {
codeJump(new JumpPosition(jumpCls, pos), fromTree);
return true;
}
}
return null;
});
}
public void codeJump(JumpPosition pos) {
codeJump(pos, false);
}
/**
* Prefer {@link TabsController#codeJump(JNode)} method
*/
public void codeJump(JumpPosition pos, boolean fromTree) {
JumpPosition currentPosition = mainWindow.getTabbedPane().getCurrentPosition();
if (selectedTab == null || selectedTab.getNode() != pos.getNode()) {
selectTab(pos.getNode(), fromTree);
}
listeners.forEach(l -> l.onTabCodeJump(selectedTab, currentPosition, pos));
}
public void smaliJump(JClass cls, int pos, boolean debugMode) {
selectTab(cls);
TabBlueprint blueprint = getTabByNode(cls);
listeners.forEach(l -> l.onTabSmaliJump(blueprint, pos, debugMode));
}
public void closeTab(JNode node) {
closeTab(node, false);
}
public void closeTab(JNode node, boolean considerPins) {
TabBlueprint blueprint = getTabByNode(node);
if (blueprint != null) {
closeTab(blueprint, considerPins);
}
}
public void closeTab(TabBlueprint blueprint, boolean considerPins) {
if (forceClose) {
closeTabForce(blueprint);
return;
}
if (!considerPins || !blueprint.isPinned()) {
if (!blueprint.isReferenced()) {
closeTabForce(blueprint);
} else {
closeTabSoft(blueprint);
}
}
}
/**
* Removes Tab from everywhere
*/
private void closeTabForce(TabBlueprint blueprint) {
listeners.forEach(l -> l.onTabClose(blueprint));
tabsMap.remove(blueprint.getNode());
}
/**
* Hides Tab from TabbedPane
*/
private void closeTabSoft(TabBlueprint blueprint) {
setTabHidden(blueprint.getNode(), true);
}
public void setTabPositionFirst(JNode node) {
TabBlueprint blueprint = openTab(node);
listeners.forEach(l -> l.onTabPositionFirst(blueprint));
}
public void setTabPinned(JNode node, boolean pinned) {
TabBlueprint blueprint = openTab(node);
setTabPinnedInternal(blueprint, pinned);
}
public void setTabPinnedInternal(TabBlueprint blueprint, boolean pinned) {
if (blueprint.isPinned() != pinned) {
blueprint.setPreviewTab(false);
blueprint.setPinned(pinned);
listeners.forEach(l -> l.onTabPinChange(blueprint));
}
}
public void setTabBookmarked(JNode node, boolean bookmarked) {
TabBlueprint blueprint = openTab(node);
setTabBookmarkedInternal(blueprint, bookmarked);
}
private void setTabBookmarkedInternal(TabBlueprint blueprint, boolean bookmarked) {
if (blueprint.isBookmarked() != bookmarked) {
blueprint.setPreviewTab(false);
blueprint.setBookmarked(bookmarked);
listeners.forEach(l -> l.onTabBookmarkChange(blueprint));
removeTabIfNotReferenced(blueprint);
}
}
public void setTabHidden(JNode node, boolean hidden) {
TabBlueprint blueprint = getTabByNode(node);
setTabHiddenInternal(blueprint, hidden);
}
private void setTabHiddenInternal(TabBlueprint blueprint, boolean hidden) {
if (blueprint != null && blueprint.isHidden() != hidden) {
blueprint.setPreviewTab(false);
blueprint.setHidden(hidden);
listeners.forEach(l -> l.onTabVisibilityChange(blueprint));
}
}
public void setTabPreview(JNode node, boolean isPreview) {
TabBlueprint blueprint = getTabByNode(node);
setTabPreviewInternal(blueprint, isPreview);
}
private void setTabPreviewInternal(TabBlueprint blueprint, boolean isPreview) {
if (blueprint != null && blueprint.isPreviewTab() != isPreview) {
blueprint.setPreviewTab(isPreview);
listeners.forEach(l -> l.onTabPreviewChange(blueprint));
}
}
private void removeTabIfNotReferenced(TabBlueprint blueprint) {
if (blueprint.isHidden() && !blueprint.isReferenced()) {
tabsMap.remove(blueprint.getNode());
}
}
public void closeAllTabs() {
closeAllTabs(false);
}
public void forceCloseAllTabs() {
forceClose = true;
closeAllTabs();
forceClose = false;
selectedTab = null;
}
public boolean isForceClose() {
return forceClose;
}
public void closeAllTabs(boolean considerPins) {
List.copyOf(tabsMap.values()).forEach(t -> closeTab(t.getNode(), considerPins));
}
public void unpinAllTabs() {
tabsMap.values().forEach(t -> setTabPinned(t.getNode(), false));
}
public void unbookmarkAllTabs() {
tabsMap.values().forEach(t -> setTabBookmarked(t.getNode(), false));
}
public TabBlueprint getSelectedTab() {
return selectedTab;
}
public List<TabBlueprint> getTabs() {
return List.copyOf(tabsMap.values());
}
public List<TabBlueprint> getOpenTabs() {
return List.copyOf(tabsMap.values());
}
public List<TabBlueprint> getPinnedTabs() {
return tabsMap.values().stream()
.filter(TabBlueprint::isPinned)
.collect(Collectors.toUnmodifiableList());
}
public List<TabBlueprint> getBookmarkedTabs() {
return tabsMap.values().stream()
.filter(TabBlueprint::isBookmarked)
.collect(Collectors.toUnmodifiableList());
}
public TabBlueprint getPreviewTab() {
return tabsMap.values().stream()
.filter(TabBlueprint::isPreviewTab).findFirst().orElse(null);
}
public void restoreEditorViewState(EditorViewState viewState) {
JNode node = viewState.getNode();
TabBlueprint blueprint = openTab(node, viewState.isHidden(), viewState.isPreviewTab());
setTabPinnedInternal(blueprint, viewState.isPinned());
setTabBookmarkedInternal(blueprint, viewState.isBookmarked());
listeners.forEach(l -> l.onTabRestore(blueprint, viewState));
if (viewState.isActive()) {
selectTab(node);
}
}
public void notifyRestoreEditorViewStateDone() {
if (selectedTab == null && !tabsMap.isEmpty()) {
JNode node = tabsMap.values().iterator().next().getNode();
LOG.warn("No active tab found, select {}", node); // TODO: find the reason of this issue
selectTab(node);
}
listeners.forEach(ITabStatesListener::onTabsRestoreDone);
}
public List<EditorViewState> getEditorViewStates() {
List<TabBlueprint> reorderedTabs = new ArrayList<>(tabsMap.values());
listeners.forEach(l -> l.onTabsReorder(reorderedTabs));
List<EditorViewState> states = new ArrayList<>();
for (TabBlueprint blueprint : reorderedTabs) {
states.add(getEditorViewState(blueprint));
}
return states;
}
public EditorViewState getEditorViewState(TabBlueprint blueprint) {
EditorViewState viewState = new EditorViewState(blueprint.getNode());
listeners.forEach(l -> l.onTabSave(blueprint, viewState));
viewState.setActive(blueprint == selectedTab);
viewState.setPinned(blueprint.isPinned());
viewState.setBookmarked(blueprint.isBookmarked());
viewState.setHidden(blueprint.isHidden());
viewState.setPreviewTab(blueprint.isPreviewTab());
return 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/tab/QuickTabsBookmarkParentNode.java | jadx-gui/src/main/java/jadx/gui/ui/tab/QuickTabsBookmarkParentNode.java | package jadx.gui.ui.tab;
import javax.swing.Icon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.Icons;
import jadx.gui.utils.NLS;
public class QuickTabsBookmarkParentNode extends QuickTabsParentNode {
protected QuickTabsBookmarkParentNode(TabsController tabsController) {
super(tabsController);
}
@Override
public String getTitle() {
return NLS.str("tree.bookmarked_tabs");
}
@Override
Icon getIcon() {
return Icons.BOOKMARK_DARK;
}
@Override
JPopupMenu onTreePopupMenu(MainWindow mainWindow) {
if (getChildCount() == 0) {
return null;
}
JPopupMenu menu = new JPopupMenu();
JMenuItem unbookmarkAll = new JMenuItem(NLS.str("tabs.unbookmark_all"));
unbookmarkAll.addActionListener(e -> getTabsController().unbookmarkAllTabs());
menu.add(unbookmarkAll);
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/tab/QuickTabsTree.java | jadx-gui/src/main/java/jadx/gui/ui/tab/QuickTabsTree.java | package jadx.gui.ui.tab;
import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.UiUtils;
public class QuickTabsTree extends JTree implements ITabStatesListener, TreeSelectionListener {
private final MainWindow mainWindow;
private final DefaultTreeModel treeModel;
private final QuickTabsParentNode openParentNode;
private final QuickTabsParentNode pinParentNode;
private final QuickTabsParentNode bookmarkParentNode;
public QuickTabsTree(MainWindow mainWindow) {
this.mainWindow = mainWindow;
mainWindow.getTabsController().addListener(this);
Root root = new Root();
pinParentNode = new QuickTabsPinParentNode(mainWindow.getTabsController());
openParentNode = new QuickTabsOpenParentNode(mainWindow.getTabsController());
bookmarkParentNode = new QuickTabsBookmarkParentNode(mainWindow.getTabsController());
root.add(openParentNode);
root.add(pinParentNode);
root.add(bookmarkParentNode);
treeModel = new DefaultTreeModel(root);
setModel(treeModel);
setCellRenderer(new CellRenderer());
setRootVisible(false);
setShowsRootHandles(true);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
TreeNode pressedNode = UiUtils.getTreeNodeUnderMouse(QuickTabsTree.this, e);
if (SwingUtilities.isLeftMouseButton(e)) {
if (nodeClickAction(pressedNode)) {
setFocusable(true);
requestFocus();
}
}
if (SwingUtilities.isRightMouseButton(e)) {
triggerRightClickAction(e);
}
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
nodeClickAction(getLastSelectedPathComponent());
}
}
});
loadSettings();
fillOpenParentNode();
fillPinParentNode();
fillBookmarkParentNode();
}
private void triggerRightClickAction(MouseEvent e) {
TreeNode treeNode = UiUtils.getTreeNodeUnderMouse(this, e);
if (!(treeNode instanceof QuickTabsBaseNode)) {
return;
}
QuickTabsBaseNode quickTabsNode = (QuickTabsBaseNode) treeNode;
JPopupMenu menu = quickTabsNode.onTreePopupMenu(mainWindow);
if (menu != null) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
private boolean nodeClickAction(Object pressedNode) {
if (pressedNode == null) {
return false;
}
if (pressedNode instanceof QuickTabsChildNode) {
QuickTabsChildNode childNode = (QuickTabsChildNode) pressedNode;
mainWindow.getTabsController().selectTab(childNode.getJNode());
return true;
}
return false;
}
private void fillOpenParentNode() {
mainWindow.getTabsController().getOpenTabs().forEach(this::onTabOpen);
}
private void fillPinParentNode() {
mainWindow.getTabsController().getPinnedTabs().forEach(this::onTabPinChange);
}
private void fillBookmarkParentNode() {
mainWindow.getTabsController().getBookmarkedTabs().forEach(this::onTabBookmarkChange);
}
private void clearParentNode(QuickTabsParentNode parentNode) {
int[] childIndices = new int[parentNode.getChildCount()];
Object[] objects = new Object[parentNode.getChildCount()];
for (int i = 0; i < childIndices.length; i++) {
childIndices[i] = i;
objects[i] = parentNode.getChildAt(i);
}
parentNode.removeAllNodes();
treeModel.nodesWereRemoved(parentNode, childIndices, objects);
}
private void addJNode(QuickTabsParentNode parentNode, JNode node) {
if (parentNode.addJNode(node)) {
treeModel.nodesWereInserted(parentNode, new int[] { parentNode.getChildCount() - 1 });
}
}
private void removeJNode(QuickTabsParentNode parentNode, JNode node) {
QuickTabsChildNode child = parentNode.getQuickTabsNode(node);
if (child != null) {
int removedIndex = parentNode.getIndex(child);
if (parentNode.removeJNode(node)) {
treeModel.nodesWereRemoved(parentNode, new int[] { removedIndex }, new Object[] { child });
}
}
}
@Override
public void valueChanged(TreeSelectionEvent event) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) getLastSelectedPathComponent();
if (selectedNode != null) {
if (selectedNode instanceof QuickTabsChildNode) {
QuickTabsChildNode childNode = (QuickTabsChildNode) selectedNode;
JNode jNode = childNode.getJNode();
TabsController tabsController = mainWindow.getTabsController();
tabsController.selectTab(jNode);
}
}
}
public void loadSettings() {
setFont(mainWindow.getSettings().getCodeFont());
}
public void dispose() {
mainWindow.getTabsController().removeListener(this);
}
@Override
public void onTabOpen(TabBlueprint blueprint) {
if (!blueprint.isHidden() && blueprint.getNode().supportsQuickTabs()) {
addJNode(openParentNode, blueprint.getNode());
}
}
@Override
public void onTabClose(TabBlueprint blueprint) {
removeJNode(openParentNode, blueprint.getNode());
removeJNode(pinParentNode, blueprint.getNode());
removeJNode(bookmarkParentNode, blueprint.getNode());
}
@Override
public void onTabPinChange(TabBlueprint blueprint) {
JNode node = blueprint.getNode();
if (blueprint.isPinned()) {
addJNode(pinParentNode, node);
} else {
removeJNode(pinParentNode, node);
}
}
@Override
public void onTabBookmarkChange(TabBlueprint blueprint) {
JNode node = blueprint.getNode();
if (blueprint.isBookmarked()) {
addJNode(bookmarkParentNode, node);
} else {
removeJNode(bookmarkParentNode, node);
}
}
@Override
public void onTabVisibilityChange(TabBlueprint blueprint) {
JNode node = blueprint.getNode();
if (!blueprint.isHidden()) {
addJNode(openParentNode, node);
} else {
removeJNode(openParentNode, node);
}
}
private class Root extends DefaultMutableTreeNode {
}
private class CellRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
if (value instanceof QuickTabsBaseNode) {
QuickTabsBaseNode quickTabsNode = (QuickTabsBaseNode) value;
setIcon(quickTabsNode.getIcon());
}
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/tab/LogTabStates.java | jadx-gui/src/main/java/jadx/gui/ui/tab/LogTabStates.java | package jadx.gui.ui.tab;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.gui.ui.codearea.EditorViewState;
import jadx.gui.utils.JumpPosition;
/**
* Utility class to log events from TabsController by implementing ITabStatesListener.
*/
public class LogTabStates implements ITabStatesListener {
private static final Logger LOG = LoggerFactory.getLogger(LogTabStates.class);
@Override
public void onTabBookmarkChange(TabBlueprint blueprint) {
LOG.debug("onTabBookmarkChange: blueprint={}", blueprint);
}
@Override
public void onTabClose(TabBlueprint blueprint) {
LOG.debug("onTabClose: blueprint={}", blueprint);
}
@Override
public void onTabCodeJump(TabBlueprint blueprint, @Nullable JumpPosition prevPos, JumpPosition newPos) {
LOG.debug("onTabCodeJump: blueprint={}, prevPos={}, newPos={}", blueprint, prevPos, newPos);
}
@Override
public void onTabOpen(TabBlueprint blueprint) {
LOG.debug("onTabOpen: blueprint={}", blueprint);
}
@Override
public void onTabPinChange(TabBlueprint blueprint) {
LOG.debug("onTabPinChange: blueprint={}", blueprint);
}
@Override
public void onTabPositionFirst(TabBlueprint blueprint) {
LOG.debug("onTabPositionFirst: blueprint={}", blueprint);
}
@Override
public void onTabRestore(TabBlueprint blueprint, EditorViewState viewState) {
LOG.debug("onTabRestore: blueprint={}, viewState={}", blueprint, viewState);
}
@Override
public void onTabSave(TabBlueprint blueprint, EditorViewState viewState) {
LOG.debug("onTabSave: blueprint={}, viewState={}", blueprint, viewState);
}
@Override
public void onTabSelect(TabBlueprint blueprint) {
LOG.debug("onTabSelect: blueprint={}", blueprint);
}
@Override
public void onTabSmaliJump(TabBlueprint blueprint, int pos, boolean debugMode) {
LOG.debug("onTabSmaliJump: blueprint={}, pos={}, debugMode={}", blueprint, pos, debugMode);
}
@Override
public void onTabsReorder(List<TabBlueprint> blueprints) {
LOG.debug("onTabsReorder: blueprints={}", blueprints);
}
@Override
public void onTabsRestoreDone() {
LOG.debug("onTabsRestoreDone");
}
@Override
public void onTabVisibilityChange(TabBlueprint blueprint) {
LOG.debug("onTabVisibilityChange: blueprint={}", blueprint);
}
@Override
public void onTabPreviewChange(TabBlueprint blueprint) {
LOG.debug("onTabPreviewChange: blueprint={}", blueprint);
}
}
| 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/tab/QuickTabsParentNode.java | jadx-gui/src/main/java/jadx/gui/ui/tab/QuickTabsParentNode.java | package jadx.gui.ui.tab;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JPopupMenu;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.MainWindow;
abstract class QuickTabsParentNode extends QuickTabsBaseNode {
private final TabsController tabsController;
private final Map<JNode, QuickTabsChildNode> childrenMap = new HashMap<>();
protected QuickTabsParentNode(TabsController tabsController) {
super();
this.tabsController = tabsController;
}
public boolean addJNode(JNode node) {
if (childrenMap.containsKey(node)) {
return false;
}
QuickTabsChildNode childNode = new QuickTabsChildNode(node);
childrenMap.put(node, childNode);
add(childNode);
return true;
}
public boolean removeJNode(JNode node) {
QuickTabsChildNode childNode = childrenMap.remove(node);
if (childNode == null) {
return false;
}
remove(childNode);
return true;
}
public void removeAllNodes() {
removeAllChildren();
}
public QuickTabsChildNode getQuickTabsNode(JNode node) {
return childrenMap.get(node);
}
public TabsController getTabsController() {
return tabsController;
}
abstract String getTitle();
@Override
public String toString() {
return getTitle();
}
@Override
JPopupMenu onTreePopupMenu(MainWindow mainWindow) {
return super.onTreePopupMenu(mainWindow);
}
}
| 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/tab/ITabStatesListener.java | jadx-gui/src/main/java/jadx/gui/ui/tab/ITabStatesListener.java | package jadx.gui.ui.tab;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.gui.ui.codearea.EditorViewState;
import jadx.gui.utils.JumpPosition;
/**
* Tabbed pane events listener
*/
public interface ITabStatesListener {
/**
* Tab added to tabbed pane without become active (selected)
*/
default void onTabOpen(TabBlueprint blueprint) {
}
/**
* Tab become active (selected)
*/
default void onTabSelect(TabBlueprint blueprint) {
}
/**
* Caret position changes.
*
* @param prevPos previous caret position; can be null if unknown; can be from another tab
* @param newPos new caret position, node refer to jump target node
*/
default void onTabCodeJump(TabBlueprint blueprint, @Nullable JumpPosition prevPos, JumpPosition newPos) {
}
default void onTabSmaliJump(TabBlueprint blueprint, int pos, boolean debugMode) {
}
default void onTabClose(TabBlueprint blueprint) {
}
default void onTabPositionFirst(TabBlueprint blueprint) {
}
default void onTabPinChange(TabBlueprint blueprint) {
}
default void onTabBookmarkChange(TabBlueprint blueprint) {
}
default void onTabVisibilityChange(TabBlueprint blueprint) {
}
default void onTabRestore(TabBlueprint blueprint, EditorViewState viewState) {
}
default void onTabsRestoreDone() {
}
default void onTabsReorder(List<TabBlueprint> blueprints) {
}
default void onTabSave(TabBlueprint blueprint, EditorViewState viewState) {
}
default void onTabPreviewChange(TabBlueprint blueprint) {
}
}
| 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/tab/QuickTabsOpenParentNode.java | jadx-gui/src/main/java/jadx/gui/ui/tab/QuickTabsOpenParentNode.java | package jadx.gui.ui.tab;
import javax.swing.Icon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.Icons;
import jadx.gui.utils.NLS;
public class QuickTabsOpenParentNode extends QuickTabsParentNode {
protected QuickTabsOpenParentNode(TabsController tabsController) {
super(tabsController);
}
@Override
public String getTitle() {
return NLS.str("tree.open_tabs");
}
@Override
Icon getIcon() {
return Icons.FOLDER;
}
@Override
JPopupMenu onTreePopupMenu(MainWindow mainWindow) {
if (getChildCount() == 0) {
return null;
}
JPopupMenu menu = new JPopupMenu();
JMenuItem closeAll = new JMenuItem(NLS.str("tabs.closeAll"));
closeAll.addActionListener(e -> getTabsController().closeAllTabs(true));
menu.add(closeAll);
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/tab/QuickTabsBaseNode.java | jadx-gui/src/main/java/jadx/gui/ui/tab/QuickTabsBaseNode.java | package jadx.gui.ui.tab;
import javax.swing.Icon;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;
import jadx.gui.ui.MainWindow;
abstract class QuickTabsBaseNode extends DefaultMutableTreeNode {
JPopupMenu onTreePopupMenu(MainWindow mainWindow) {
return null;
}
Icon getIcon() {
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/tab/TabbedPane.java | jadx-gui/src/main/java/jadx/gui/ui/tab/TabbedPane.java | package jadx.gui.ui.tab;
import java.awt.Component;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.jobs.SilentTask;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.codearea.AbstractCodeArea;
import jadx.gui.ui.codearea.AbstractCodeContentPanel;
import jadx.gui.ui.codearea.ClassCodeContentPanel;
import jadx.gui.ui.codearea.EditorViewState;
import jadx.gui.ui.codearea.SmaliArea;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.panel.FontPanel;
import jadx.gui.ui.panel.HtmlPanel;
import jadx.gui.ui.panel.IViewStateSupport;
import jadx.gui.ui.panel.ImagePanel;
import jadx.gui.ui.tab.dnd.TabDndController;
import jadx.gui.utils.JumpPosition;
import jadx.gui.utils.UiUtils;
public class TabbedPane extends JTabbedPane implements ITabStatesListener {
private static final long serialVersionUID = -8833600618794570904L;
private static final Logger LOG = LoggerFactory.getLogger(TabbedPane.class);
private final transient MainWindow mainWindow;
private final transient TabsController controller;
private final transient Map<JNode, ContentPanel> tabsMap = new HashMap<>();
private transient ContentPanel curTab;
private transient ContentPanel lastTab;
private transient TabDndController dnd;
public TabbedPane(MainWindow window, TabsController controller) {
this.mainWindow = window;
this.controller = controller;
controller.addListener(this);
setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
MouseAdapter clickAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int tabIndex = indexAtLocation(e.getX(), e.getY());
if (tabIndex == -1 || tabIndex > getTabCount()) {
return;
}
TabComponent tab = (TabComponent) getTabComponentAt(tabIndex);
tab.dispatchEvent(e);
}
};
addMouseListener(clickAdapter);
addMouseWheelListener(event -> {
if (dnd != null && dnd.isDragging()) {
return;
}
int direction = event.getWheelRotation();
if (getTabCount() == 0 || direction == 0) {
return;
}
direction = (direction < 0) ? -1 : 1; // normalize direction
int index = getSelectedIndex();
int maxIndex = getTabCount() - 1;
index += direction;
index = Math.max(0, Math.min(maxIndex, index));
try {
setSelectedIndex(index);
} catch (IndexOutOfBoundsException e) {
// ignore error
}
});
interceptTabKey();
interceptCloseKey();
enableSwitchingTabs();
}
private void interceptTabKey() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
private static final int ctrlDown = KeyEvent.CTRL_DOWN_MASK;
private long ctrlInterval = 0;
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
long cur = System.currentTimeMillis();
if (!FocusManager.isActive()) {
return false; // don't do nothing when tab is not on focus.
}
int code = e.getKeyCode();
boolean consume = code == KeyEvent.VK_TAB; // consume Tab key event anyway
boolean isReleased = e.getID() == KeyEvent.KEY_RELEASED;
if (isReleased) {
if (code == KeyEvent.VK_CONTROL) {
ctrlInterval = cur;
} else if (code == KeyEvent.VK_TAB) {
boolean doSwitch = false;
if ((e.getModifiersEx() & ctrlDown) != 0) {
doSwitch = lastTab != null && getTabCount() > 1;
} else {
// the gap of the release of ctrl and tab is very close, nearly the same time,
// but ctrl released first.
ctrlInterval = cur - ctrlInterval;
if (ctrlInterval <= 90) {
doSwitch = lastTab != null && getTabCount() > 1;
}
}
if (doSwitch) {
selectTab(lastTab);
}
}
} else if (consume && (e.getModifiersEx() & ctrlDown) == 0) {
// switch between source and smali
if (curTab instanceof ClassCodeContentPanel) {
((ClassCodeContentPanel) curTab).switchPanel();
}
}
return consume;
}
});
}
private void interceptCloseKey() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
private static final int closeKey = KeyEvent.VK_W;
private boolean canClose = true;
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (!FocusManager.isActive()) {
return false; // do nothing when tab is not on focus.
}
if (e.getKeyCode() != closeKey) {
return false; // only intercept the events of the close key
}
if (e.getID() == KeyEvent.KEY_RELEASED) {
canClose = true; // after the close key is lifted we allow to use it again
return false;
}
if (e.isControlDown() && canClose) {
// close the current tab
closeCodePanel(curTab);
canClose = false; // make sure we dont close more tabs until the close key is lifted
return true;
}
return false;
}
});
}
private void enableSwitchingTabs() {
addChangeListener(e -> {
ContentPanel tab = getSelectedContentPanel();
if (tab == null) { // all closed
curTab = null;
lastTab = null;
return;
}
FocusManager.focusOnCodePanel(tab);
if (tab == curTab) { // a tab was closed by not the current one.
if (lastTab != null && indexOfComponent(lastTab) == -1) { // lastTab was closed
setLastTabAdjacentToCurTab();
}
return;
}
if (tab == lastTab) {
if (indexOfComponent(curTab) == -1) { // curTab was closed and lastTab is the current one.
curTab = lastTab;
setLastTabAdjacentToCurTab();
return;
}
// it's switching between lastTab and curTab.
}
lastTab = curTab;
curTab = tab;
});
}
private void setLastTabAdjacentToCurTab() {
if (getTabCount() < 2) {
lastTab = null;
return;
}
int idx = indexOfComponent(curTab);
if (idx == 0) {
lastTab = (ContentPanel) getComponentAt(idx + 1);
} else {
lastTab = (ContentPanel) getComponentAt(idx - 1);
}
}
public MainWindow getMainWindow() {
return mainWindow;
}
public TabsController getTabsController() {
return controller;
}
private @Nullable ContentPanel showCode(JumpPosition jumpPos) {
JNode jumpNode = jumpPos.getNode();
ContentPanel contentPanel = getTabByNode(jumpNode);
if (contentPanel == null) {
return null;
}
selectTab(contentPanel);
int pos = jumpPos.getPos();
if (pos < 0) {
LOG.warn("Invalid jump: {}", jumpPos, new JadxRuntimeException());
pos = 0;
}
contentPanel.scrollToPos(pos);
return contentPanel;
}
public void selectTab(ContentPanel contentPanel) {
controller.selectTab(contentPanel.getNode());
}
private void smaliJump(JClass cls, int pos, boolean debugMode) {
ContentPanel panel = getTabByNode(cls);
if (panel == null) {
panel = showCode(new JumpPosition(cls, 1));
if (panel == null) {
throw new JadxRuntimeException("Failed to open panel for JClass: " + cls);
}
} else {
selectTab(panel);
}
ClassCodeContentPanel codePane = (ClassCodeContentPanel) panel;
codePane.showSmaliPane();
SmaliArea smaliArea = (SmaliArea) codePane.getSmaliCodeArea();
if (debugMode) {
smaliArea.scrollToDebugPos(pos);
}
smaliArea.scrollToPos(pos);
smaliArea.requestFocus();
}
public @Nullable JumpPosition getCurrentPosition() {
ContentPanel selectedCodePanel = getSelectedContentPanel();
if (selectedCodePanel instanceof AbstractCodeContentPanel) {
AbstractCodeArea codeArea = ((AbstractCodeContentPanel) selectedCodePanel).getCodeArea();
if (codeArea != null) {
return codeArea.getCurrentPosition();
}
}
return null;
}
private void addContentPanel(ContentPanel contentPanel) {
tabsMap.put(contentPanel.getNode(), contentPanel);
int tabCount = getTabCount();
add(contentPanel, tabCount);
setTabComponentAt(tabCount, makeTabComponent(contentPanel));
}
public void closeCodePanel(ContentPanel contentPanel) {
closeCodePanel(contentPanel, false);
}
public void closeCodePanel(ContentPanel contentPanel, boolean considerPins) {
controller.closeTab(contentPanel.getNode(), considerPins);
}
public List<ContentPanel> getTabs() {
List<ContentPanel> list = new ArrayList<>(getTabCount());
for (int i = 0; i < getTabCount(); i++) {
list.add((ContentPanel) getComponentAt(i));
}
return list;
}
public @Nullable ContentPanel getTabByNode(JNode node) {
return tabsMap.get(node);
}
public @Nullable TabComponent getTabComponentByNode(JNode node) {
ContentPanel contentPanel = getTabByNode(node);
if (contentPanel == null) {
return null;
}
int index = indexOfComponent(contentPanel);
if (index == -1) {
return null;
}
Component component = getTabComponentAt(index);
if (!(component instanceof TabComponent)) {
return null;
}
return (TabComponent) component;
}
public void refresh(JNode node) {
ContentPanel panel = getTabByNode(node);
if (panel != null) {
setTabComponentAt(indexOfComponent(panel), makeTabComponent(panel));
fireStateChanged();
}
}
public void reloadInactiveTabs() {
UiUtils.uiThreadGuard();
int tabCount = getTabCount();
if (tabCount == 1) {
return;
}
int current = getSelectedIndex();
for (int i = 0; i < tabCount; i++) {
if (i == current) {
continue;
}
ContentPanel oldPanel = (ContentPanel) getComponentAt(i);
TabBlueprint tab = controller.getTabByNode(oldPanel.getNode());
if (tab == null) {
continue;
}
EditorViewState viewState = controller.getEditorViewState(tab);
JNode node = oldPanel.getNode();
ContentPanel panel = node.getContentPanel(this);
FocusManager.listen(panel);
tabsMap.put(node, panel);
setComponentAt(i, panel);
setTabComponentAt(i, makeTabComponent(panel));
controller.restoreEditorViewState(viewState);
}
fireStateChanged();
}
@Nullable
public ContentPanel getSelectedContentPanel() {
return (ContentPanel) getSelectedComponent();
}
private Component makeTabComponent(final ContentPanel contentPanel) {
return new TabComponent(this, contentPanel);
}
public void closeAllTabs() {
closeAllTabs(false);
}
public void closeAllTabs(boolean considerPins) {
for (ContentPanel panel : getTabs()) {
closeCodePanel(panel, considerPins);
}
}
public void loadSettings() {
for (int i = 0; i < getTabCount(); i++) {
((ContentPanel) getComponentAt(i)).loadSettings();
((TabComponent) getTabComponentAt(i)).loadSettings();
}
}
public void reset() {
closeAllTabs();
tabsMap.clear();
curTab = null;
lastTab = null;
FocusManager.reset();
}
@Nullable
public Component getFocusedComp() {
return FocusManager.getFocusedComp();
}
public TabDndController getDnd() {
return dnd;
}
public void setDnd(TabDndController dnd) {
this.dnd = dnd;
}
@Override
public void onTabOpen(TabBlueprint blueprint) {
if (blueprint.isHidden()) {
return;
}
JNode node = blueprint.getNode();
ContentPanel newPanel = node.getContentPanel(this);
if (newPanel != null) {
if (node != newPanel.getNode()) {
throw new JadxRuntimeException("Incorrect node found in content panel");
}
FocusManager.listen(newPanel);
addContentPanel(newPanel);
blueprint.setCreated(true);
}
}
@Override
public void onTabSelect(TabBlueprint blueprint) {
ContentPanel contentPanel = getTabByNode(blueprint.getNode());
if (contentPanel != null) {
setSelectedComponent(contentPanel);
}
}
@Override
public void onTabCodeJump(TabBlueprint blueprint, @Nullable JumpPosition prevPos, JumpPosition position) {
// queue task to wait completion of loading tasks
mainWindow.getBackgroundExecutor().execute(new SilentTask(() -> showCode(position)));
}
@Override
public void onTabSmaliJump(TabBlueprint blueprint, int pos, boolean debugMode) {
JNode node = blueprint.getNode();
if (node instanceof JClass) {
smaliJump((JClass) node, pos, debugMode);
}
}
@Override
public void onTabClose(TabBlueprint blueprint) {
ContentPanel contentPanelToClose = getTabByNode(blueprint.getNode());
if (contentPanelToClose == null) {
return;
}
ContentPanel currentContentPanel = getSelectedContentPanel();
if (currentContentPanel == contentPanelToClose) {
if (lastTab != null && lastTab.getNode() != null) {
selectTab(lastTab);
} else if (getTabCount() > 1) {
int removalIdx = indexOfComponent(contentPanelToClose);
if (removalIdx > 0) { // select left tab
setSelectedIndex(removalIdx - 1);
} else if (removalIdx == 0) { // select right tab
setSelectedIndex(removalIdx + 1);
}
} else {
// no other tabs => inform controller to reset selection
controller.deselectTab();
}
}
tabsMap.remove(contentPanelToClose.getNode());
remove(contentPanelToClose);
contentPanelToClose.dispose();
}
@Override
public void onTabPositionFirst(TabBlueprint blueprint) {
ContentPanel contentPanel = getTabByNode(blueprint.getNode());
if (contentPanel == null) {
return;
}
setTabPosition(contentPanel, 0);
}
private void setTabPosition(ContentPanel contentPanel, int position) {
TabComponent tabComponent = getTabComponentByNode(contentPanel.getNode());
if (tabComponent == null) {
return;
}
boolean restoreSelection = contentPanel == getSelectedContentPanel();
remove(contentPanel);
add(contentPanel, position);
setTabComponentAt(position, tabComponent);
if (restoreSelection) {
setSelectedIndex(position);
}
}
@Override
public void onTabPinChange(TabBlueprint blueprint) {
TabComponent tabComponent = getTabComponentByNode(blueprint.getNode());
if (tabComponent == null) {
return;
}
tabComponent.update();
}
@Override
public void onTabBookmarkChange(TabBlueprint blueprint) {
TabComponent tabComponent = getTabComponentByNode(blueprint.getNode());
if (tabComponent == null) {
return;
}
tabComponent.update();
}
@Override
public void onTabVisibilityChange(TabBlueprint blueprint) {
if (!blueprint.isHidden() && !tabsMap.containsKey(blueprint.getNode())) {
onTabOpen(blueprint);
}
if (blueprint.isHidden() && tabsMap.containsKey(blueprint.getNode())) {
onTabClose(blueprint);
}
}
@Override
public void onTabPreviewChange(TabBlueprint blueprint) {
TabComponent tabComponent = getTabComponentByNode(blueprint.getNode());
if (tabComponent == null) {
return;
}
tabComponent.update();
}
@Override
public void onTabRestore(TabBlueprint blueprint, EditorViewState viewState) {
ContentPanel contentPanel = getTabByNode(blueprint.getNode());
if (contentPanel instanceof IViewStateSupport) {
((IViewStateSupport) contentPanel).restoreEditorViewState(viewState);
}
}
@Override
public void onTabsReorder(List<TabBlueprint> blueprints) {
List<TabBlueprint> newBlueprints = new ArrayList<>(blueprints.size());
for (ContentPanel contentPanel : getTabs()) {
TabBlueprint blueprint = controller.getTabByNode(contentPanel.getNode());
if (blueprint != null) {
newBlueprints.add(blueprint);
}
}
// Add back hidden tabs
Set<TabBlueprint> set = new LinkedHashSet<>(blueprints);
newBlueprints.forEach(set::remove);
newBlueprints.addAll(set);
blueprints.clear();
blueprints.addAll(newBlueprints);
}
@Override
public void onTabSave(TabBlueprint blueprint, EditorViewState viewState) {
ContentPanel contentPanel = getTabByNode(blueprint.getNode());
if (contentPanel instanceof IViewStateSupport) {
((IViewStateSupport) contentPanel).saveEditorViewState(viewState);
}
}
private static class FocusManager implements FocusListener {
private static final FocusManager INSTANCE = new FocusManager();
private static @Nullable Component focusedComp;
static boolean isActive() {
return focusedComp != null;
}
static void reset() {
focusedComp = null;
}
static Component getFocusedComp() {
return focusedComp;
}
@Override
public void focusGained(FocusEvent e) {
focusedComp = (Component) e.getSource();
}
@Override
public void focusLost(FocusEvent e) {
focusedComp = null;
}
static void listen(ContentPanel pane) {
if (pane instanceof ClassCodeContentPanel) {
((ClassCodeContentPanel) pane).getCodeArea().addFocusListener(INSTANCE);
((ClassCodeContentPanel) pane).getSmaliCodeArea().addFocusListener(INSTANCE);
return;
}
if (pane instanceof AbstractCodeContentPanel) {
((AbstractCodeContentPanel) pane).getChildrenComponent().addFocusListener(INSTANCE);
return;
}
if (pane instanceof HtmlPanel) {
((HtmlPanel) pane).getHtmlArea().addFocusListener(INSTANCE);
return;
}
if (pane instanceof ImagePanel) {
pane.addFocusListener(INSTANCE);
return;
}
if (pane instanceof FontPanel) {
pane.addFocusListener(INSTANCE);
return;
}
// throw new JadxRuntimeException("Add the new ContentPanel to TabbedPane.FocusManager: " + pane);
}
static void focusOnCodePanel(ContentPanel pane) {
if (pane instanceof ClassCodeContentPanel) {
SwingUtilities.invokeLater(() -> ((ClassCodeContentPanel) pane).getCurrentCodeArea().requestFocus());
return;
}
if (pane instanceof AbstractCodeContentPanel) {
SwingUtilities.invokeLater(() -> ((AbstractCodeContentPanel) pane).getChildrenComponent().requestFocus());
return;
}
if (pane instanceof HtmlPanel) {
SwingUtilities.invokeLater(() -> ((HtmlPanel) pane).getHtmlArea().requestFocusInWindow());
return;
}
if (pane instanceof ImagePanel) {
SwingUtilities.invokeLater(((ImagePanel) pane)::requestFocusInWindow);
return;
}
if (pane instanceof FontPanel) {
SwingUtilities.invokeLater(((FontPanel) pane)::requestFocusInWindow);
return;
}
// throw new JadxRuntimeException("Add the new ContentPanel to TabbedPane.FocusManager: " + pane);
}
}
}
| 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/tab/NavigationController.java | jadx-gui/src/main/java/jadx/gui/ui/tab/NavigationController.java | package jadx.gui.ui.tab;
import org.jetbrains.annotations.Nullable;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.JumpManager;
import jadx.gui.utils.JumpPosition;
/**
* TODO: Save jumps history into project file to restore after reload or reopen
*/
public class NavigationController implements ITabStatesListener {
private final transient MainWindow mainWindow;
private final transient JumpManager jumps = new JumpManager();
public NavigationController(MainWindow mainWindow) {
this.mainWindow = mainWindow;
mainWindow.getTabsController().addListener(this);
}
public void navBack() {
jump(jumps.getPrev());
}
public void navForward() {
jump(jumps.getNext());
}
private void jump(@Nullable JumpPosition pos) {
if (pos != null) {
mainWindow.getTabsController().codeJump(pos);
}
}
@Override
public void onTabCodeJump(TabBlueprint blueprint, @Nullable JumpPosition prevPos, JumpPosition newPos) {
if (newPos.equals(jumps.getCurrent())) {
// ignore self-initiated jumps
return;
}
jumps.addPosition(prevPos);
jumps.addPosition(newPos);
}
@Override
public void onTabSmaliJump(TabBlueprint blueprint, int pos, boolean debugMode) {
// TODO: save smali jump
}
public void reset() {
jumps.reset();
}
public void dispose() {
reset();
mainWindow.getTabsController().removeListener(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/tab/EditorSyncManager.java | jadx-gui/src/main/java/jadx/gui/ui/tab/EditorSyncManager.java | package jadx.gui.ui.tab;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.panel.ContentPanel;
public class EditorSyncManager implements ITabStatesListener {
private final MainWindow mainWindow;
private final TabbedPane tabbedPane;
public EditorSyncManager(MainWindow mainWindow, TabbedPane tabbedPane) {
this.mainWindow = mainWindow;
this.tabbedPane = tabbedPane;
mainWindow.getTabsController().addListener(this);
}
public void sync() {
ContentPanel selectedContentPanel = tabbedPane.getSelectedContentPanel();
if (selectedContentPanel != null) {
mainWindow.selectNodeInTree(selectedContentPanel.getNode());
}
}
@Override
public void onTabSelect(TabBlueprint blueprint) {
mainWindow.toggleHexViewMenu();
if (mainWindow.getSettings().isAlwaysSelectOpened()) {
// verify that tab opened for this blueprint (some nodes don't open tab with content)
ContentPanel selectedContentPanel = tabbedPane.getSelectedContentPanel();
if (selectedContentPanel != null && selectedContentPanel.getNode().equals(blueprint.getNode())) {
sync();
}
}
}
@Override
public void onTabClose(TabBlueprint blueprint) {
ITabStatesListener.super.onTabClose(blueprint);
mainWindow.toggleHexViewMenu();
}
}
| 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/tab/QuickTabsPinParentNode.java | jadx-gui/src/main/java/jadx/gui/ui/tab/QuickTabsPinParentNode.java | package jadx.gui.ui.tab;
import javax.swing.Icon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.Icons;
import jadx.gui.utils.NLS;
public class QuickTabsPinParentNode extends QuickTabsParentNode {
protected QuickTabsPinParentNode(TabsController tabsController) {
super(tabsController);
}
@Override
public String getTitle() {
return NLS.str("tree.pinned_tabs");
}
@Override
Icon getIcon() {
return Icons.PIN;
}
@Override
JPopupMenu onTreePopupMenu(MainWindow mainWindow) {
if (getChildCount() == 0) {
return null;
}
JPopupMenu menu = new JPopupMenu();
JMenuItem unpinAll = new JMenuItem(NLS.str("tabs.unpin_all"));
unpinAll.addActionListener(e -> getTabsController().unpinAllTabs());
menu.add(unpinAll);
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/tab/TabBlueprint.java | jadx-gui/src/main/java/jadx/gui/ui/tab/TabBlueprint.java | package jadx.gui.ui.tab;
import java.util.Objects;
import jadx.gui.treemodel.JNode;
public class TabBlueprint {
private final JNode node;
private boolean created;
private boolean pinned;
private boolean bookmarked;
private boolean hidden;
private boolean previewTab;
public TabBlueprint(JNode node) {
this.node = Objects.requireNonNull(node);
}
public JNode getNode() {
return node;
}
public boolean isCreated() {
return created;
}
public void setCreated(boolean created) {
this.created = created;
}
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 supportsQuickTabs() {
return node.supportsQuickTabs();
}
public boolean isReferenced() {
return isBookmarked();
}
public boolean isHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public boolean isPreviewTab() {
return previewTab;
}
public void setPreviewTab(boolean previewTab) {
this.previewTab = previewTab;
}
@Override
public final boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TabBlueprint)) {
return false;
}
return node.equals(((TabBlueprint) o).node);
}
@Override
public int hashCode() {
return node.hashCode();
}
@Override
public String toString() {
return "TabBlueprint{" + "node="
+ node + ", pinned="
+ pinned + ", bookmarked="
+ bookmarked + ", hidden="
+ hidden + ", previewTab="
+ previewTab + '}';
}
}
| 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/tab/QuickTabsChildNode.java | jadx-gui/src/main/java/jadx/gui/ui/tab/QuickTabsChildNode.java | package jadx.gui.ui.tab;
import javax.swing.Icon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.NLS;
public class QuickTabsChildNode extends QuickTabsBaseNode {
private final JNode node;
public QuickTabsChildNode(JNode node) {
this.node = node;
}
@Override
public String toString() {
return node.toString();
}
public JNode getJNode() {
return node;
}
@Override
public JPopupMenu onTreePopupMenu(MainWindow mainWindow) {
JPopupMenu menu = node.onTreePopupMenu(mainWindow);
if (node.supportsQuickTabs()) {
if (getParent() instanceof QuickTabsPinParentNode) {
if (menu == null) {
menu = new JPopupMenu();
}
JMenuItem closeAction = new JMenuItem(NLS.str("tabs.close"));
closeAction.addActionListener(e -> mainWindow.getTabsController().closeTab(node, true));
menu.add(closeAction, 0);
menu.add(new JPopupMenu.Separator(), 1);
}
if (getParent() instanceof QuickTabsPinParentNode) {
if (menu == null) {
menu = new JPopupMenu();
}
JMenuItem unpinAction = new JMenuItem(NLS.str("tabs.unpin"));
unpinAction.addActionListener(e -> mainWindow.getTabsController().setTabPinned(node, false));
menu.add(unpinAction, 0);
menu.add(new JPopupMenu.Separator(), 1);
}
if (getParent() instanceof QuickTabsBookmarkParentNode) {
if (menu == null) {
menu = new JPopupMenu();
}
JMenuItem unbookmarkAction = new JMenuItem(NLS.str("tabs.unbookmark"));
unbookmarkAction.addActionListener(e -> mainWindow.getTabsController().setTabBookmarked(node, false));
menu.add(unbookmarkAction, 0);
menu.add(new JPopupMenu.Separator(), 1);
}
}
return menu;
}
@Override
Icon getIcon() {
return node.getIcon();
}
}
| 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/tab/dnd/TabDndTransferable.java | jadx-gui/src/main/java/jadx/gui/ui/tab/dnd/TabDndTransferable.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 TERAI Atsuhiro
* Copyright (c) 2024 Skylot
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jadx.gui.ui.tab.dnd;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
class TabDndTransferable implements Transferable {
private static final String NAME = "Transferable Tab";
@Override
public Object getTransferData(DataFlavor flavor) {
return this;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME) };
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return NAME.equals(flavor.getHumanPresentableName());
}
}
| 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/tab/dnd/TabDndController.java | jadx-gui/src/main/java/jadx/gui/ui/tab/dnd/TabDndController.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 TERAI Atsuhiro
* Copyright (c) 2024 Skylot
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jadx.gui.ui.tab.dnd;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTarget;
import java.awt.image.BufferedImage;
import java.util.Objects;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.plaf.metal.MetalTabbedPaneUI;
import jadx.gui.settings.JadxSettings;
import jadx.gui.ui.tab.TabbedPane;
public class TabDndController {
private final transient JTabbedPane pane;
private static final int DROP_TARGET_MARK_SIZE = 4;
private static final int SCROLL_AREA_SIZE = 30;
private static final int SCROLL_AREA_EXTRA = 30; // Making area with scroll buttons a bit bigger.
private static final String ACTION_SCROLL_FORWARD = "scrollTabsForwardAction";
private static final String ACTION_SCROLL_BACKWARD = "scrollTabsBackwardAction";
private final transient TabDndGhostPane tabDndGhostPane;
protected int dragTabIndex = -1;
protected boolean drawGhost = true; // Semi-transparent tab copy moving along with cursor.
protected boolean paintScrollTriggerAreas = false; // For debug purposes.
protected Rectangle rectBackward = new Rectangle();
protected Rectangle rectForward = new Rectangle();
private boolean isDragging = false;
public TabDndController(TabbedPane pane, JadxSettings settings) {
pane.setDnd(this);
this.pane = pane;
tabDndGhostPane = new TabDndGhostPane(this, settings);
new DropTarget(tabDndGhostPane, DnDConstants.ACTION_COPY_OR_MOVE, new TabDndTargetListener(this), true);
DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(pane,
DnDConstants.ACTION_COPY_OR_MOVE,
new TabDndGestureListener(this));
}
public static boolean isHorizontalTabPlacement(int tabPlacement) {
return tabPlacement == JTabbedPane.TOP || tabPlacement == JTabbedPane.BOTTOM;
}
/**
* Check if dragging near edges and scroll to according
* direction through programmatically clicking system's scroll buttons.
*
* @param glassPt Cursor position in TabbedPane coordinates.
*/
public void scrollIfNeeded(Point glassPt) {
Rectangle r = getTabAreaBounds();
boolean isHorizontal = isHorizontalTabPlacement(pane.getTabPlacement());
// Trying to avoid calculating two directions simultaneously. Forward first.
if (isHorizontal) {
rectForward.setBounds(r.x + r.width - SCROLL_AREA_SIZE - SCROLL_AREA_EXTRA,
r.y,
SCROLL_AREA_SIZE + SCROLL_AREA_EXTRA,
r.height);
} else {
rectForward.setBounds(r.x,
r.y + r.height - SCROLL_AREA_SIZE - SCROLL_AREA_EXTRA,
r.width,
SCROLL_AREA_SIZE + SCROLL_AREA_EXTRA);
}
rectForward = SwingUtilities.convertRectangle(pane.getParent(), rectForward, tabDndGhostPane);
if (rectForward.contains(glassPt)) {
clickScrollButton(ACTION_SCROLL_FORWARD);
}
// Backward.
if (isHorizontal) {
rectBackward.setBounds(r.x, r.y, SCROLL_AREA_SIZE, r.height);
} else {
rectBackward.setBounds(r.x, r.y, r.width, SCROLL_AREA_SIZE);
}
rectBackward = SwingUtilities.convertRectangle(pane.getParent(), rectBackward, tabDndGhostPane);
if (rectBackward.contains(glassPt)) {
clickScrollButton(ACTION_SCROLL_BACKWARD);
}
}
private void clickScrollButton(String actionKey) {
JButton forwardButton = null;
JButton backwardButton = null;
for (Component c : pane.getComponents()) {
if (c instanceof JButton) {
if (Objects.isNull(forwardButton)) {
forwardButton = (JButton) c;
} else {
backwardButton = (JButton) c;
break;
}
}
}
JButton scrollButton = ACTION_SCROLL_FORWARD.equals(actionKey) ? forwardButton : backwardButton;
if (scrollButton != null && scrollButton.isEnabled()) {
scrollButton.doClick();
}
}
/**
* Finds the tab index by cursor position. If tabs first half contains the point,
* then its index is returned. Second half means inserting at next index.
*
* @param glassPt Cursor position in TabbedPane coordinates.
* @return Tab index.
*/
protected int getTargetTabIndex(Point glassPt) {
Point tabPt = SwingUtilities.convertPoint(tabDndGhostPane, glassPt, pane);
boolean isHorizontal = isHorizontalTabPlacement(pane.getTabPlacement());
for (int i = 0; i < pane.getTabCount(); ++i) {
Rectangle r = pane.getBoundsAt(i);
// First half.
if (isHorizontal) {
r.width = r.width / 2 + 1;
} else {
r.height = r.height / 2 + 1;
}
if (r.contains(tabPt)) {
return i;
}
// Second half.
if (isHorizontal) {
r.x = r.x + r.width;
} else {
r.y = r.y + r.height;
}
if (r.contains(tabPt)) {
return i + 1;
}
}
int count = pane.getTabCount();
if (count == 0) {
return -1;
}
Rectangle lastRect = pane.getBoundsAt(count - 1);
Point d = isHorizontal ? new Point(1, 0) : new Point(0, 1);
lastRect.translate(lastRect.width * d.x, lastRect.height * d.y);
return lastRect.contains(tabPt) ? count : -1;
}
protected void swapTabs(int oldIdx, int newIdx) {
if (newIdx < 0 || oldIdx == newIdx) {
return;
}
final Component cmp = pane.getComponentAt(oldIdx);
final Component tab = pane.getTabComponentAt(oldIdx);
final String title = pane.getTitleAt(oldIdx);
final Icon icon = pane.getIconAt(oldIdx);
final String tip = pane.getToolTipTextAt(oldIdx);
final boolean isEnabled = pane.isEnabledAt(oldIdx);
newIdx = oldIdx > newIdx ? newIdx : (newIdx - 1);
pane.remove(oldIdx);
pane.insertTab(title, icon, cmp, tip, newIdx);
pane.setEnabledAt(newIdx, isEnabled);
if (isEnabled) {
pane.setSelectedIndex(newIdx);
}
pane.setTabComponentAt(newIdx, tab);
}
protected void updateTargetMark(int tabIdx) {
boolean isSideNeighbor = tabIdx < 0 || dragTabIndex == tabIdx || tabIdx == dragTabIndex + 1;
if (isSideNeighbor) {
tabDndGhostPane.setTargetRect(0, 0, 0, 0);
return;
}
Rectangle boundsRect = pane.getBoundsAt(Math.max(0, tabIdx - 1));
final Rectangle r = SwingUtilities.convertRectangle(pane, boundsRect, tabDndGhostPane);
int a = Math.min(tabIdx, 1);
if (isHorizontalTabPlacement(pane.getTabPlacement())) {
tabDndGhostPane.setTargetRect(r.x + r.width * a - DROP_TARGET_MARK_SIZE / 2,
r.y,
DROP_TARGET_MARK_SIZE,
r.height);
} else {
tabDndGhostPane.setTargetRect(r.x,
r.y + r.height * a - DROP_TARGET_MARK_SIZE / 2,
r.width,
DROP_TARGET_MARK_SIZE);
}
}
protected void initGlassPane(Point tabPt) {
pane.getRootPane().setGlassPane(tabDndGhostPane);
if (drawGhost) {
Component c = pane.getTabComponentAt(dragTabIndex);
if (c == null) {
return;
}
Dimension d = c.getPreferredSize();
switch (tabDndGhostPane.getGhostType()) {
case IMAGE: {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = env.getDefaultScreenDevice();
GraphicsConfiguration config = device.getDefaultConfiguration();
BufferedImage image = config.createCompatibleImage(d.width, d.height, BufferedImage.TRANSLUCENT);
Graphics2D g2 = image.createGraphics();
SwingUtilities.paintComponent(g2, c, tabDndGhostPane, 0, 0, d.width, d.height);
g2.dispose();
tabDndGhostPane.setGhostImage(image);
pane.setTabComponentAt(dragTabIndex, c);
break;
}
case OUTLINE: {
tabDndGhostPane.setGhostSize(d);
break;
}
case TARGET_MARK:
break;
}
}
Point glassPt = SwingUtilities.convertPoint(pane, tabPt, tabDndGhostPane);
tabDndGhostPane.setPoint(glassPt);
tabDndGhostPane.setVisible(true);
}
protected Rectangle getTabAreaBounds() {
Rectangle tabbedRect = pane.getBounds();
Rectangle compRect;
if (pane.getSelectedComponent() != null) {
compRect = pane.getSelectedComponent().getBounds();
} else {
compRect = new Rectangle();
}
int tabPlacement = pane.getTabPlacement();
if (isHorizontalTabPlacement(tabPlacement)) {
tabbedRect.height = tabbedRect.height - compRect.height;
if (tabPlacement == JTabbedPane.BOTTOM) {
tabbedRect.y += compRect.y + compRect.height;
}
} else {
tabbedRect.width = tabbedRect.width - compRect.width;
if (tabPlacement == JTabbedPane.RIGHT) {
tabbedRect.x += compRect.x + compRect.width;
}
}
tabbedRect.grow(2, 2);
return tabbedRect;
}
public void onPaintGlassPane(Graphics2D g) {
boolean isScrollLayout = pane.getTabLayoutPolicy() == JTabbedPane.SCROLL_TAB_LAYOUT;
if (isScrollLayout && paintScrollTriggerAreas) {
g.setPaint(tabDndGhostPane.getColor());
g.fill(rectBackward);
g.fill(rectForward);
}
}
public boolean onStartDrag(Point pt) {
setDragging(true);
int idx = pane.indexAtLocation(pt.x, pt.y);
int selIdx = pane.getSelectedIndex();
boolean isTabRunsRotated =
!(pane.getUI() instanceof MetalTabbedPaneUI) && pane.getTabLayoutPolicy() == JTabbedPane.WRAP_TAB_LAYOUT && idx != selIdx;
dragTabIndex = isTabRunsRotated ? selIdx : idx;
if (dragTabIndex >= 0 && pane.isEnabledAt(dragTabIndex)) {
initGlassPane(pt);
return true;
}
return false;
}
public void loadSettings() {
tabDndGhostPane.loadSettings();
}
public boolean isDragging() {
return isDragging;
}
public void setDragging(boolean dragging) {
isDragging = dragging;
}
public TabDndGhostPane getDndGhostPane() {
return tabDndGhostPane;
}
}
| 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/tab/dnd/TabDndGhostType.java | jadx-gui/src/main/java/jadx/gui/ui/tab/dnd/TabDndGhostType.java | package jadx.gui.ui.tab.dnd;
public enum TabDndGhostType {
/**
* Bitmap is rendered from tabs component and dragged along with cursor.
* May be impactful on performance.
*/
IMAGE,
/**
* Colored rect of tabs size is dragged along with cursor.
*/
OUTLINE,
/**
* Only insert mark is rendered.
*/
TARGET_MARK,
}
| 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/tab/dnd/TabDndSourceListener.java | jadx-gui/src/main/java/jadx/gui/ui/tab/dnd/TabDndSourceListener.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 TERAI Atsuhiro
* Copyright (c) 2024 Skylot
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jadx.gui.ui.tab.dnd;
import java.awt.Component;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import javax.swing.JComponent;
import javax.swing.JRootPane;
class TabDndSourceListener implements DragSourceListener {
private final transient TabDndController dnd;
public TabDndSourceListener(TabDndController dnd) {
this.dnd = dnd;
}
@Override
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
@Override
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
}
@Override
public void dragOver(DragSourceDragEvent e) {
}
@Override
public void dragDropEnd(DragSourceDropEvent e) {
dnd.setDragging(false);
Component c = e.getDragSourceContext().getComponent();
if (c instanceof JComponent) {
JRootPane rp = ((JComponent) c).getRootPane();
if (rp.getGlassPane() != null) {
rp.getGlassPane().setVisible(false);
}
}
}
@Override
public void dropActionChanged(DragSourceDragEvent 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/tab/dnd/TabDndTargetListener.java | jadx-gui/src/main/java/jadx/gui/ui/tab/dnd/TabDndTargetListener.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 TERAI Atsuhiro
* Copyright (c) 2024 Skylot
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jadx.gui.ui.tab.dnd;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
class TabDndTargetListener implements DropTargetListener {
private static final Point HIDDEN_POINT = new Point(0, -1000);
private final transient TabDndController dnd;
public TabDndTargetListener(TabDndController dnd) {
this.dnd = dnd;
}
@Override
public void dragEnter(DropTargetDragEvent e) {
TabDndGhostPane pane = dnd.getDndGhostPane();
if (pane == null || e.getDropTargetContext().getComponent() != pane) {
return;
}
Transferable t = e.getTransferable();
DataFlavor[] f = e.getCurrentDataFlavors();
if (t.isDataFlavorSupported(f[0])) {
e.acceptDrag(e.getDropAction());
} else {
e.rejectDrag();
}
}
@Override
public void dragExit(DropTargetEvent e) {
TabDndGhostPane pane = dnd.getDndGhostPane();
if (pane == null || e.getDropTargetContext().getComponent() != pane) {
return;
}
pane.setPoint(HIDDEN_POINT);
pane.setTargetRect(0, 0, 0, 0);
pane.repaint();
}
@Override
public void dropActionChanged(DropTargetDragEvent e) {
}
@Override
public void dragOver(DropTargetDragEvent e) {
TabDndGhostPane pane = dnd.getDndGhostPane();
if (pane == null || e.getDropTargetContext().getComponent() != pane) {
return;
}
Point glassPt = e.getLocation();
dnd.updateTargetMark(dnd.getTargetTabIndex(glassPt));
dnd.scrollIfNeeded(glassPt); // backward and forward scrolling
pane.setPoint(glassPt);
pane.repaint();
}
@Override
public void drop(DropTargetDropEvent e) {
TabDndGhostPane pane = dnd.getDndGhostPane();
if (pane == null || e.getDropTargetContext().getComponent() != pane) {
return;
}
Transferable t = e.getTransferable();
DataFlavor[] f = t.getTransferDataFlavors();
int oldIdx = dnd.dragTabIndex;
int newIdx = dnd.getTargetTabIndex(e.getLocation());
if (t.isDataFlavorSupported(f[0]) && oldIdx != newIdx) {
dnd.swapTabs(oldIdx, newIdx);
e.dropComplete(true);
} else {
e.dropComplete(false);
}
pane.setVisible(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/tab/dnd/TabDndGestureListener.java | jadx-gui/src/main/java/jadx/gui/ui/tab/dnd/TabDndGestureListener.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 TERAI Atsuhiro
* Copyright (c) 2024 Skylot
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jadx.gui.ui.tab.dnd;
import java.awt.Point;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.InvalidDnDOperationException;
public class TabDndGestureListener implements DragGestureListener {
private final transient TabDndController dnd;
public TabDndGestureListener(TabDndController dnd) {
this.dnd = dnd;
}
@Override
public void dragGestureRecognized(DragGestureEvent e) {
Point tabPt = getDragOrigin(e);
if (!dnd.onStartDrag(tabPt)) {
return;
}
try {
e.startDrag(DragSource.DefaultMoveDrop, new TabDndTransferable(), new TabDndSourceListener(dnd));
} catch (InvalidDnDOperationException ex) {
throw new IllegalStateException(ex);
}
}
protected Point getDragOrigin(DragGestureEvent e) {
return e.getDragOrigin();
}
}
| 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/tab/dnd/TabDndGhostPane.java | jadx-gui/src/main/java/jadx/gui/ui/tab/dnd/TabDndGhostPane.java | /*
* The MIT License (MIT)
* Copyright (c) 2015 TERAI Atsuhiro
* Copyright (c) 2024 Skylot
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jadx.gui.ui.tab.dnd;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.UIManager;
import jadx.gui.settings.JadxSettings;
public class TabDndGhostPane extends JComponent {
private final TabDndController dnd;
private final Rectangle lineRect = new Rectangle();
private final Point location = new Point();
private transient BufferedImage ghostImage;
private JadxSettings settings;
private TabDndGhostType tabDndGhostType = TabDndGhostType.OUTLINE;
private Dimension ghostSize;
private Color ghostColor;
private Insets insets;
protected TabDndGhostPane(TabDndController dnd, JadxSettings settings) {
super();
this.dnd = dnd;
this.settings = settings;
loadSettings();
}
public void loadSettings() {
Color systemColor = UIManager.getColor("Component.focusColor");
Color fallbackColor = new Color(0, 100, 255);
ghostColor = systemColor != null ? systemColor : fallbackColor;
Insets ins = UIManager.getInsets("TabbedPane.tabInsets");
insets = ins != null ? ins : new Insets(0, 0, 0, 0);
tabDndGhostType = settings.getTabDndGhostType();
}
public void setTargetRect(int x, int y, int width, int height) {
lineRect.setBounds(x, y, width, height);
}
public void setGhostImage(BufferedImage ghostImage) {
this.ghostImage = ghostImage;
}
public void setGhostSize(Dimension ghostSize) {
ghostSize.setSize(ghostSize.width + insets.left + insets.right, ghostSize.height + insets.top + insets.bottom);
this.ghostSize = ghostSize;
}
public void setGhostType(TabDndGhostType tabDndGhostType) {
this.tabDndGhostType = tabDndGhostType;
}
public TabDndGhostType getGhostType() {
return this.tabDndGhostType;
}
public void setColor(Color color) {
this.ghostColor = color;
}
public Color getColor() {
return this.ghostColor;
}
public void setPoint(Point pt) {
this.location.setLocation(pt);
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void setVisible(boolean v) {
super.setVisible(v);
if (!v) {
setTargetRect(0, 0, 0, 0);
setGhostImage(null);
setGhostSize(new Dimension());
}
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
dnd.onPaintGlassPane(g2);
renderMark(g2);
renderGhost(g2);
g2.dispose();
}
private void renderGhost(Graphics2D g) {
switch (tabDndGhostType) {
case IMAGE: {
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));
if (ghostImage == null) {
return;
}
double x = location.getX() - ghostImage.getWidth(this) / 2d;
double y = location.getY() - ghostImage.getHeight(this) / 2d;
g.drawImage(ghostImage, (int) x, (int) y, this);
break;
}
case OUTLINE: {
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .2f));
if (ghostSize == null) {
return;
}
double x = location.getX() - ghostSize.getWidth() / 2d;
double y = location.getY() - ghostSize.getHeight() / 2d;
g.setPaint(ghostColor);
g.fillRect((int) x, (int) y, ghostSize.width, ghostSize.height);
break;
}
case TARGET_MARK:
break;
}
}
private void renderMark(Graphics2D g) {
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .7f));
g.setPaint(ghostColor);
g.fill(lineRect);
}
}
| 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/tree/TreeExpansionService.java | jadx-gui/src/main/java/jadx/gui/tree/TreeExpansionService.java | package jadx.gui.tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.JTree;
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.api.metadata.ICodeNodeRef;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.jobs.LoadTask;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
import jadx.gui.treemodel.JPackage;
import jadx.gui.treemodel.JRoot;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.JNodeCache;
import jadx.gui.utils.UiUtils;
public class TreeExpansionService {
private static final Logger LOG = LoggerFactory.getLogger(TreeExpansionService.class);
private static final boolean DEBUG = false;
private static final Comparator<TreePath> PATH_LENGTH_REVERSE = Comparator.comparingInt(p -> -p.getPathCount());
private final MainWindow mainWindow;
private final JTree tree;
private final JNodeCache nodeCache;
public TreeExpansionService(MainWindow mainWindow, JTree tree) {
this.mainWindow = mainWindow;
this.tree = tree;
this.nodeCache = mainWindow.getCacheObject().getNodeCache();
}
public List<String> save() {
if (tree.getRowCount() == 0 || mainWindow.getWrapper().getCurrentDecompiler().isEmpty()) {
return Collections.emptyList();
}
List<TreePath> expandedPaths = collectExpandedPaths(tree);
List<String> list = new ArrayList<>();
for (TreePath expandedPath : expandedPaths) {
list.add(savePath(expandedPath));
}
if (DEBUG) {
LOG.debug("Saving tree expansions:\n {}", Utils.listToString(list, "\n "));
}
return list;
}
public void load(List<String> treeExpansions) {
mainWindow.getBackgroundExecutor().execute(new LoadTask<>(
() -> {
List<TreePath> expandedPaths = new ArrayList<>();
loadPaths(treeExpansions, expandedPaths);
// send expand event to load sub-nodes and wait for completion
UiUtils.uiRunAndWait(() -> expandedPaths.forEach(path -> {
try {
tree.fireTreeWillExpand(path);
} catch (Exception e) {
throw new JadxRuntimeException("Tree expand error", e);
}
}));
return expandedPaths;
},
expandedPaths -> {
// expand paths after a loading task is finished
expandedPaths.forEach(tree::expandPath);
}));
}
private void loadPaths(List<String> treeExpansions, List<TreePath> expandedPaths) {
if (DEBUG) {
LOG.debug("Restoring tree expansions:\n {}", Utils.listToString(treeExpansions, "\n "));
}
for (String treeExpansion : treeExpansions) {
try {
TreePath treePath = loadPath(treeExpansion);
if (treePath != null) {
expandedPaths.add(treePath);
}
} catch (Exception e) {
LOG.warn("Failed to load tree expansion entry: {}", treeExpansion, e);
}
}
if (DEBUG) {
LOG.debug("Restored expanded tree paths:\n {}", Utils.listToString(expandedPaths, "\n "));
}
}
private String savePath(TreePath path) {
JNode node = (JNode) path.getLastPathComponent();
if (node instanceof JPackage) {
return "p:" + ((JPackage) node).getPkg().getRawFullName();
}
if (node instanceof JClass) {
return "c:" + ((JClass) node).getCls().getRawName();
}
return Arrays.stream(path.getPath())
.map(p -> ((JNode) p).getID())
.skip(1) // skip root
.collect(Collectors.joining("//", "t:", ""));
}
private @Nullable TreePath loadPath(String pathStr) {
String pathData = pathStr.substring(2);
switch (pathStr.charAt(0)) {
case 'c':
return getTreePathForRef(getRoot().resolveRawClass(pathData));
case 'p':
return getTreePathForRef(getRoot().resolvePackage(pathData));
case 't':
return resolveTreePath(pathData.split("//"));
default:
throw new JadxRuntimeException("Unknown tree expansion path type: " + pathStr);
}
}
private @Nullable TreePath resolveTreePath(String[] pathArr) {
JNode current = (JNode) tree.getModel().getRoot();
for (String nodeStr : pathArr) {
JNode node = current.searchNode(n -> n.getID().equals(nodeStr));
if (node == null) {
if (DEBUG) {
List<String> children = current.childrenList().stream()
.map(n -> ((JNode) n).getID())
.collect(Collectors.toList());
LOG.warn("Failed to restore path: {}, node '{}' not found in '{}' children: {}",
Arrays.toString(pathArr), nodeStr, current, children);
}
return null;
}
current = node;
}
return new TreePath(current.getPath());
}
private @Nullable TreePath getTreePathForRef(@Nullable ICodeNodeRef ref) {
if (ref == null) {
return null;
}
JNode node = nodeCache.makeFrom(ref);
if (node.getParent() == null) {
if (DEBUG) {
LOG.warn("Resolving node not from tree: {}", node);
}
JNode treeNode = ((JRoot) tree.getModel().getRoot()).searchNode(node);
if (treeNode == null) {
if (DEBUG) {
LOG.error("Node not found in tree: {}", node);
}
return null;
}
node = treeNode;
}
TreeNode[] pathNodes = ((DefaultTreeModel) tree.getModel()).getPathToRoot(node);
if (pathNodes == null) {
return null;
}
return new TreePath(pathNodes);
}
private static List<TreePath> collectExpandedPaths(JTree tree) {
TreePath root = tree.getPathForRow(0);
Enumeration<TreePath> expandedDescendants = tree.getExpandedDescendants(root);
if (expandedDescendants == null) {
return Collections.emptyList();
}
List<TreePath> expandedPaths = new ArrayList<>();
while (expandedDescendants.hasMoreElements()) {
TreePath path = expandedDescendants.nextElement();
if (path.getPathCount() > 1) {
expandedPaths.add(path);
}
}
// filter out sub-paths
expandedPaths.sort(PATH_LENGTH_REVERSE); // put the longest paths before sub-paths
List<TreePath> result = new ArrayList<>();
for (TreePath path : expandedPaths) {
if (!isSubPath(result, path)) {
result.add(path);
}
}
return result;
}
private static boolean isSubPath(List<TreePath> paths, TreePath path) {
for (TreePath addedPath : paths) {
if (path.isDescendant(addedPath)) {
return true;
}
}
return false;
}
private RootNode getRoot() {
return mainWindow.getWrapper().getDecompiler().getRoot();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/NotYetImplemented.java | jadx-core/src/test/java/jadx/NotYetImplemented.java | package jadx;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates a test which is known to fail.
*
* <p>
* This would cause a failure to be considered as success and a success as failure,
* with the benefit of updating the related issue when it has been resolved even unintentionally.
* </p>
*
* <p>
* To have an effect, the test class must be annotated with:
*
* <code>
* @ExtendWith(NotYetImplementedExtension.class)
* </code>
* </p>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface NotYetImplemented {
String value() default "";
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/NotYetImplementedExtension.java | jadx-core/src/test/java/jadx/NotYetImplementedExtension.java | package jadx;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
public class NotYetImplementedExtension implements AfterTestExecutionCallback, TestExecutionExceptionHandler {
private final Set<Method> knownFailedMethods = new HashSet<>();
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
if (!isNotYetImplemented(context)) {
throw throwable;
}
knownFailedMethods.add(context.getTestMethod().get());
}
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
if (!knownFailedMethods.contains(context.getTestMethod().get())
&& isNotYetImplemented(context)
&& context.getExecutionException().isEmpty()) {
throw new AssertionError("Test "
+ context.getTestClass().get().getName() + '.' + context.getTestMethod().get().getName()
+ " is marked as @NotYetImplemented, but passes!");
}
}
private static boolean isNotYetImplemented(ExtensionContext context) {
return context.getTestMethod().get().getAnnotation(NotYetImplemented.class) != null
|| context.getTestClass().get().getAnnotation(NotYetImplemented.class) != null;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics.java | package jadx.tests.integration.generics;
import java.util.List;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestGenerics extends IntegrationTest {
public static class TestCls {
class A {
}
public static void mthWildcard(List<?> list) {
}
public static void mthExtends(List<? extends A> list) {
}
public static void mthSuper(List<? super A> list) {
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("mthWildcard(List<?> list)")
.contains("mthExtends(List<? extends A> list)")
.contains("mthSuper(List<? super A> list)");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestMissingGenericsTypes2.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestMissingGenericsTypes2.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestMissingGenericsTypes2 extends SmaliTest {
// @formatter:off
/*
package generics;
import java.util.Iterator;
public class TestMissingGenericsTypes2<T> implements Iterable<T> {
@Override
public Iterator<T> iterator() {
return null;
}
public void test(TestMissingGenericsTypes2<String> l) {
Iterator<String> i = l.iterator(); // <-- This generics type was removed in smali
while (i.hasNext()) {
String s = i.next();
doSomething(s);
}
}
private void doSomething(String s) {
}
}
*/
// @formatter:on
@Test
public void test() {
assertThat(getClassNodeFromSmali())
.code()
.doesNotContain("Iterator i")
.containsOne("for (String s : l) {");
}
@Test
public void testTypes() {
// prevent loop from converting to 'for-each' to keep iterator variable type in code
getArgs().getDisabledPasses().add("LoopRegionVisitor");
assertThat(getClassNodeFromSmali())
.code()
.doesNotContain("Iterator i")
.containsOne("Iterator<String> it = "); // variable name reject along with type
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGeneric8.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGeneric8.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestGeneric8 extends IntegrationTest {
public static class TestCls {
@SuppressWarnings("InnerClassMayBeStatic")
public class TestNumber<T extends Integer> {
private final T n;
public TestNumber(T n) {
this.n = n;
}
public boolean isEven() {
return n.intValue() % 2 == 0;
}
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("public TestNumber(T n");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics7.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics7.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestGenerics7 extends IntegrationTest {
public static class TestCls {
public void test() {
declare(String.class);
}
public <T> T declare(Class<T> cls) {
return null;
}
public void declare(Object cls) {
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("declare(String.class);");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestOuterGeneric.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestOuterGeneric.java | package jadx.tests.integration.generics;
import java.util.Set;
import org.junit.jupiter.api.Test;
import jadx.NotYetImplemented;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestOuterGeneric extends IntegrationTest {
public static class TestCls {
public static class A<T> {
public class B<V> {
}
public class C {
}
}
public static class D {
public class E {
}
}
public void test1() {
A<String> a = new A<>();
use(a);
A<String>.B<Exception> b = a.new B<Exception>();
use(b);
use(b);
A<String>.C c = a.new C();
use(c);
use(c);
use(new A<Set<String>>().new C());
}
public void test2() {
D d = new D();
D.E e = d.new E();
use(e);
use(e);
}
public void test3() {
use(A.class);
use(A.B.class);
use(A.C.class);
}
private void use(Object obj) {
}
}
@NotYetImplemented("Instance constructor for inner classes")
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.containsOne("A<String> a = new A<>();")
.containsOne("A<String>.B<Exception> b = a.new B<Exception>();")
.containsOne("A<String>.C c = a.new C();")
.containsOne("use(new A<Set<String>>().new C());")
.containsOne("D.E e = d.new E();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestImportGenericMap.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestImportGenericMap.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
import static jadx.tests.integration.generics.TestImportGenericMap.SuperClass.NotToImport;
import static jadx.tests.integration.generics.TestImportGenericMap.SuperClass.ToImport;
public class TestImportGenericMap extends IntegrationTest {
public static class SuperClass<O extends SuperClass.ToImport> {
interface ToImport {
}
interface NotToImport {
}
static final class Class1<C extends NotToImport> {
}
public <C extends NotToImport> SuperClass(Class1<C> zzf) {
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(SuperClass.class))
.code()
.contains("import " + ToImport.class.getName().replace("$ToImport", ".ToImport") + ';')
.doesNotContain("import " + NotToImport.class.getName().replace("NotToImport", ".NotToImport") + ';');
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics3.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics3.java | package jadx.tests.integration.generics;
import java.util.List;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestGenerics3 extends IntegrationTest {
public static class TestCls {
public static void mthExtendsArray(List<? extends byte[]> list) {
}
public static void mthSuperArray(List<? super int[]> list) {
}
public static void mthSuperInteger(List<? super Integer> list) {
}
public static void mthExtendsString(List<? super String> list) {
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("mthExtendsArray(List<? extends byte[]> list)")
.contains("mthSuperArray(List<? super int[]> list)")
.contains("mthSuperInteger(List<? super Integer> list)")
.contains("mthExtendsString(List<? super String> list)");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestMethodOverride.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestMethodOverride.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestMethodOverride extends SmaliTest {
@Test
public void test() {
disableCompilation();
assertThat(getClassNodeFromSmali())
.code()
.containsOne("String createFromParcel(Parcel parcel) {")
.containsOne("String[] newArray(int i) {")
.countString(2, "@Override");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics2.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics2.java | package jadx.tests.integration.generics;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Map;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestGenerics2 extends IntegrationTest {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
public static class TestCls {
public static class ItemReference<V> extends WeakReference<V> {
public Object id;
public ItemReference(V item, Object objId, ReferenceQueue<? super V> queue) {
super(item, queue);
this.id = objId;
}
}
public static class ItemReferences<V> {
private Map<Object, ItemReference<V>> items;
public V get(Object id) {
WeakReference<V> ref = this.items.get(id);
if (ref != null) {
return ref.get();
}
return null;
}
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("public ItemReference(V item, Object objId, ReferenceQueue<? super V> queue) {")
.containsOne("public V get(Object id) {")
.containsOne("WeakReference<V> ref = ")
.containsOne("return ref.get();");
}
@Test
public void testDebug() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("ItemReference<V> itemReference = this.items.get(obj);")
.containsOne("return itemReference.get();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestTypeVarsFromSuperClass.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestTypeVarsFromSuperClass.java | package jadx.tests.integration.generics;
import java.util.Objects;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestTypeVarsFromSuperClass extends IntegrationTest {
@SuppressWarnings("ResultOfMethodCallIgnored")
public static class TestCls {
public static class C1<A> {
}
public static class C2<B> extends C1<B> {
public B call() {
return null;
}
}
public static class C3<C> extends C2<C> {
}
public static class C4 extends C3<String> {
public Object test() {
String str = call();
Objects.nonNull(str);
return str;
}
}
}
@Test
public void test() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("= call();")
.doesNotContain("(String)");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics8.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics8.java | package jadx.tests.integration.generics;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestGenerics8 extends IntegrationTest {
@SuppressWarnings("IllegalType")
public static class TestCls<I> extends LinkedHashMap<I, Integer> implements Iterable<I> {
@Override
public Iterator<I> iterator() {
return keySet().iterator();
}
}
@Test
public void test() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("return keySet().iterator();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics4.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics4.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestGenerics4 extends IntegrationTest {
public static class TestCls {
public static Class<?> method(int i) {
Class<?>[] a = new Class<?>[0];
return a[a.length - i];
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("Class<?>[] a =")
.doesNotContain("Class[] a =");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestTypeVarsFromOuterClass.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestTypeVarsFromOuterClass.java | package jadx.tests.integration.generics;
import java.util.Map;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestTypeVarsFromOuterClass extends IntegrationTest {
public static class TestCls {
public interface I<X> {
Map.Entry<X, X> entry();
}
public static class Outer<Y> {
public class Inner implements I<Y> {
@Override
public Map.Entry<Y, Y> entry() {
return null;
}
}
public Inner getInner() {
return null;
}
}
private Outer<String> outer;
public void test() {
Outer<String>.Inner inner = this.outer.getInner();
use(inner, inner);
Map.Entry<String, String> entry = inner.entry();
use(entry.getKey(), entry.getValue());
}
public void test2() {
// force interface virtual call
I<String> base = this.outer.getInner();
use(base, base);
Map.Entry<String, String> entry = base.entry();
use(entry.getKey(), entry.getValue());
}
public void use(Object a, Object b) {
}
}
@Test
public void test() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.doesNotContain("Outer<Y>.Inner inner")
.doesNotContain("Object entry = ")
.countString(2, "Outer<String>.Inner inner = this.outer.getInner();")
.countString(2, "Map.Entry<String, String> entry = ");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenericFields.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenericFields.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestGenericFields extends IntegrationTest {
public static class TestCls {
public static class Summary {
Value<Amount> price;
}
public static class Value<T> {
T value;
}
public static class Amount {
String cur;
int val;
}
public String test(Summary summary) {
Amount amount = summary.price.value;
return amount.val + " " + amount.cur;
}
}
@Test
public void test() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.doesNotContain("T t = ")
.containsOne("Amount amount =");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestClassSignature.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestClassSignature.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestClassSignature extends SmaliTest {
// @formatter:off
/*
Incorrect class signature, super class is equals to this class: <T:Ljava/lang/Object;>Lgenerics/TestClassSignature<TT;>;
*/
// @formatter:on
@Test
public void test() {
allowWarnInCode();
assertThat(getClassNodeFromSmali())
.code()
.containsOne("Incorrect class signature")
.doesNotContain("StackOverflowError");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenericsMthOverride.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenericsMthOverride.java | package jadx.tests.integration.generics;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestGenericsMthOverride extends IntegrationTest {
public static class TestCls {
public interface I<X, Y> {
Y method(X x);
}
public static class A<X, Y> implements I<X, Y> {
@Override
public Y method(X x) {
return null;
}
}
public static class B<X, Y> implements I<X, Y> {
@Override
public Y method(Object x) {
return null;
}
}
public static class C<X extends Exception, Y> implements I<X, Y> {
@Override
public Y method(Exception x) {
return null;
}
}
@SuppressWarnings("unchecked")
public static class D<X, Y> implements I<X, Y> {
@Override
public Object method(Object x) {
return null;
}
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.containsOne("public Y method(X x) {")
.containsOne("public Y method(Object x) {")
.containsOne("public Y method(Exception x) {")
.containsOne("public Object method(Object x) {")
.countString(4, "@Override");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics6.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenerics6.java | package jadx.tests.integration.generics;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestGenerics6 extends IntegrationTest {
public static class TestCls {
public void test1(Collection<? extends A> as) {
for (A a : as) {
a.f();
}
}
public void test2(Collection<? extends A> is) {
for (I i : is) {
i.f();
}
}
private interface I {
void f();
}
private class A implements I {
public void f() {
}
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.containsOne("for (A a : as) {")
.containsOne("for (I i : is) {");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestGenericsInArgs.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestGenericsInArgs.java | package jadx.tests.integration.generics;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestGenericsInArgs extends IntegrationTest {
public static class TestCls {
public static <T> void test(List<? super T> genericList, Set<T> set) {
if (genericList == null) {
throw new RuntimeException("list is null");
}
if (set == null) {
throw new RuntimeException("set is null");
}
genericList.clear();
use(genericList);
set.clear();
}
private static void use(List<?> l) {
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("public static <T> void test(List<? super T> genericList, Set<T> set) {")
.contains("if (genericList == null) {");
}
@Test
public void testNoDebug() {
noDebugInfo();
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("public static <T> void test(List<? super T> list, Set<T> set) {")
.contains("if (list == null) {");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestConstructorGenerics.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestConstructorGenerics.java | package jadx.tests.integration.generics;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestConstructorGenerics extends IntegrationTest {
@SuppressWarnings({ "MismatchedQueryAndUpdateOfCollection", "RedundantOperationOnEmptyContainer" })
public static class TestCls {
public String test() {
Map<String, String> map = new HashMap<>();
return map.get("test");
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("Map<String, String> map = new HashMap<>();");
}
@Test
public void testNoDebug() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("return (String) new HashMap().get(\"test\");");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestUsageInGenerics.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestUsageInGenerics.java | package jadx.tests.integration.generics;
import java.util.List;
import org.junit.jupiter.api.Test;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestUsageInGenerics extends IntegrationTest {
public static class TestCls {
public static class A {
}
public static class B<T extends A> {
}
public static class C {
public List<? extends A> list;
}
public <T extends A> T test() {
return null;
}
}
@Test
public void test() {
ClassNode cls = getClassNode(TestCls.class);
ClassNode testCls = searchCls(cls.getInnerClasses(), "A");
ClassNode bCls = searchCls(cls.getInnerClasses(), "B");
ClassNode cCls = searchCls(cls.getInnerClasses(), "C");
MethodNode testMth = getMethod(cls, "test");
assertThat(testCls.getUseIn()).contains(cls, bCls, cCls);
assertThat(testCls.getUseInMth()).contains(testMth);
assertThat(cls)
.code()
.containsOne("public <T extends A> T test() {");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/generics/TestSyntheticOverride.java | jadx-core/src/test/java/jadx/tests/integration/generics/TestSyntheticOverride.java | package jadx.tests.integration.generics;
import java.util.List;
import org.junit.jupiter.api.Test;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSyntheticOverride extends SmaliTest {
// @formatter:off
/*
final class TestSyntheticOverride extends Lambda implements Function1<String, Unit> {
// fixing method types to match interface (i.e Unit invoke(String str))
// make duplicate methods signatures
public bridge synthetic Object invoke(Object str) {
invoke(str);
return Unit.INSTANCE;
}
public final void invoke(String str) {
...
}
}
*/
// @formatter:on
@Test
public void test() {
allowWarnInCode();
disableCompilation();
List<ClassNode> classNodes = loadFromSmaliFiles();
assertThat(searchCls(classNodes, "TestSyntheticOverride"))
.code()
.containsOne("invoke(String str)")
.containsOne("invoke2(String str)");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/synchronize/TestNestedSynchronize.java | jadx-core/src/test/java/jadx/tests/integration/synchronize/TestNestedSynchronize.java | package jadx.tests.integration.synchronize;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestNestedSynchronize extends SmaliTest {
// @formatter:off
/*
public final void test() {
Object obj = null;
Object obj2 = null;
synchronized (obj) {
synchronized (obj2) {
}
}
}
*/
// @formatter:on
@Test
public void test() {
assertThat(getClassNodeFromSmali())
.code()
.countString(2, "synchronized");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized2.java | jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized2.java | package jadx.tests.integration.synchronize;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSynchronized2 extends IntegrationTest {
@SuppressWarnings("unused")
public static class TestCls {
private static synchronized boolean test(Object obj) {
return obj.toString() != null;
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.contains("private static synchronized boolean test(Object obj) {")
.doesNotContain("synchronized (")
.contains("obj.toString() != null;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized5.java | jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized5.java | package jadx.tests.integration.synchronize;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSynchronized5 extends SmaliTest {
@Test
public void test() {
assertThat(getClassNodeFromSmali())
.code()
.contains("1 != 0")
.contains("System.gc();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized6.java | jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized6.java | package jadx.tests.integration.synchronize;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSynchronized6 extends SmaliTest {
public static class TestCls {
private final Object lock = new Object();
private boolean test(Object obj) {
synchronized (this.lock) {
return isA(obj) || isB(obj);
}
}
private boolean isA(Object obj) {
return false;
}
private boolean isB(Object obj) {
return false;
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("synchronized (this.lock) {")
.containsOne("isA(obj) || isB(obj);"); // TODO: "return isA(obj) || isB(obj);"
}
@Test
public void testSmali() {
assertThat(getClassNodeFromSmali())
.code()
.containsOne("synchronized (this.lock) {");
// TODO: .containsOne("return isA(obj) || isB(obj);");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized.java | jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized.java | package jadx.tests.integration.synchronize;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestSynchronized extends IntegrationTest {
public static class TestCls {
public boolean f = false;
public final Object o = new Object();
public int i = 7;
public synchronized boolean test1() {
return this.f;
}
public int test2() {
synchronized (this.o) {
return this.i;
}
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.doesNotContain("synchronized (this) {")
.containsOne("public synchronized boolean test1() {")
.containsOne("return this.f")
.containsOne("synchronized (this.o) {")
.doesNotContain(indent(3) + ';')
.doesNotContain("try {")
.doesNotContain("} catch (Throwable th) {")
.doesNotContain("throw th;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized3.java | jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized3.java | package jadx.tests.integration.synchronize;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSynchronized3 extends IntegrationTest {
public static class TestCls {
private int x;
public void f() {
}
public void test() {
while (true) {
synchronized (this) {
if (x == 0) {
throw new IllegalStateException();
}
x++;
if (x == 10) {
break;
}
}
this.x++;
f();
}
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsLines(3, "}", "this.x++;", "f();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized4.java | jadx-core/src/test/java/jadx/tests/integration/synchronize/TestSynchronized4.java | package jadx.tests.integration.synchronize;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSynchronized4 extends SmaliTest {
// @formatter:off
/*
public boolean test(int i) {
synchronized (this.obj) {
if (isZero(i)) {
return call(obj, i);
}
System.out.println();
return getField() == null;
}
}
*/
// @formatter:on
@Test
public void test() {
assertThat(getClassNodeFromSmali())
.code()
.containsOne("synchronized (this.obj) {")
.containsOne("return call(this.obj, i);")
.containsOne("return getField() == null;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotations2.java | jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotations2.java | package jadx.tests.integration.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestAnnotations2 extends IntegrationTest {
public static class TestCls {
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
int i();
float f();
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("@Target({ElementType.TYPE})")
.contains("@Retention(RetentionPolicy.RUNTIME)")
.contains("public @interface A {")
.contains("float f();")
.contains("int i();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsRename.java | jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsRename.java | package jadx.tests.integration.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestAnnotationsRename extends IntegrationTest {
public static class TestCls {
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
int x();
}
@A(x = 5)
void test() {
}
public void check() throws NoSuchMethodException {
Method test = TestCls.class.getDeclaredMethod("test");
A annotation = test.getAnnotation(A.class);
assertThat(annotation.x()).isEqualTo(5);
}
}
@Test
public void test() {
enableDeobfuscation();
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("public @interface ")
.doesNotContain("(x = 5)");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsRenameDef.java | jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsRenameDef.java | package jadx.tests.integration.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestAnnotationsRenameDef extends IntegrationTest {
public static class TestCls {
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
int value();
}
@A(5)
void test() {
}
}
@Test
public void test() {
enableDeobfuscation();
// force rename 'value' method
args.setDeobfuscationMinLength(20);
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("public @interface ")
.doesNotContain("int value();")
.doesNotContain("(5)");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsUsage.java | jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsUsage.java | package jadx.tests.integration.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestAnnotationsUsage extends IntegrationTest {
public static class TestCls {
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface A {
Class<?> c();
}
@A(c = TestCls.class)
public static class B {
}
public static class C {
@A(c = B.class)
public String field;
}
@A(c = B.class)
void test() {
}
void test2(@A(c = B.class) Integer value) {
}
}
@Test
public void test() {
ClassNode cls = getClassNode(TestCls.class);
ClassNode annCls = searchCls(cls.getInnerClasses(), "A");
ClassNode bCls = searchCls(cls.getInnerClasses(), "B");
ClassNode cCls = searchCls(cls.getInnerClasses(), "C");
MethodNode testMth = getMethod(cls, "test");
MethodNode testMth2 = getMethod(cls, "test2");
assertThat(annCls.getUseIn()).contains(cls, bCls, cCls);
assertThat(annCls.getUseInMth()).contains(testMth, testMth2);
assertThat(bCls.getUseIn()).contains(cCls);
assertThat(bCls.getUseInMth()).contains(testMth, testMth2);
assertThat(cls)
.code()
.countString(3, "@A(c = B.class)");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/annotations/TestParamAnnotations.java | jadx-core/src/test/java/jadx/tests/integration/annotations/TestParamAnnotations.java | package jadx.tests.integration.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestParamAnnotations extends IntegrationTest {
public static class TestCls {
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public static @interface A {
int i() default 7;
}
void test1(@A int i) {
}
void test2(int i, @A int j) {
}
void test3(@A(i = 5) int i) {
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("void test1(@A int i) {")
.contains("void test2(int i, @A int j) {")
.contains("void test3(@A(i = 5) int i) {");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsMix.java | jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotationsMix.java | package jadx.tests.integration.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
import static java.lang.Thread.State.TERMINATED;
import static org.assertj.core.api.Assertions.assertThat;
public class TestAnnotationsMix extends IntegrationTest {
public static class TestCls {
public boolean test() throws Exception {
Class<?> cls = TestCls.class;
new Thread();
Method err = cls.getMethod("error");
assertThat(err.getExceptionTypes().length > 0).isTrue();
assertThat(err.getExceptionTypes()[0]).isSameAs(Exception.class);
Method d = cls.getMethod("depr", String[].class);
assertThat(d.getAnnotations().length > 0).isTrue();
assertThat(d.getAnnotations()[0].annotationType()).isSameAs(Deprecated.class);
Method ma = cls.getMethod("test", String[].class);
assertThat(ma.getAnnotations().length > 0).isTrue();
MyAnnotation a = (MyAnnotation) ma.getAnnotations()[0];
assertThat(a.num()).isEqualTo(7);
assertThat(a.state()).isSameAs(TERMINATED);
return true;
}
@Deprecated
public int a;
public void error() throws Exception {
throw new Exception("error");
}
@Deprecated
public static Object depr(String[] a) {
return Arrays.asList(a);
}
@MyAnnotation(
name = "b",
num = 7,
cls = Exception.class,
doubles = { 0.0, 1.1 },
value = 9.87f,
simple = @SimpleAnnotation(false)
)
public static Object test(String[] a) {
return Arrays.asList(a);
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String name() default "a";
String str() default "str";
int num();
float value();
double[] doubles();
Class<?> cls();
SimpleAnnotation simple();
Thread.State state() default Thread.State.TERMINATED;
}
public @interface SimpleAnnotation {
boolean value();
}
public void check() throws Exception {
test();
}
}
@Test
public void test() {
// useDexInput();
assertThat(getClassNode(TestCls.class))
.code()
.doesNotContain("int i = false;");
}
@Test
public void testNoDebug() {
noDebugInfo();
getClassNode(TestCls.class);
}
@Test
public void testDeclaration() {
assertThat(getClassNode(TestCls.class))
.code()
.doesNotContain("Thread thread = new Thread();")
.contains("new Thread();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotations.java | jadx-core/src/test/java/jadx/tests/integration/annotations/TestAnnotations.java | package jadx.tests.integration.annotations;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestAnnotations extends IntegrationTest {
public static class TestCls {
private @interface A {
int a();
}
@A(a = -1)
public void methodA1() {
}
@A(a = -253)
public void methodA2() {
}
@A(a = -11253)
public void methodA3() {
}
private @interface V {
boolean value();
}
@V(false)
public void methodV() {
}
private @interface D {
float value() default 1.1f;
}
@D
public void methodD() {
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class)).code()
.doesNotContain("@A(a = 255)")
.containsOne("@A(a = -1)")
.containsOne("@A(a = -253)")
.containsOne("@A(a = -11253)")
.containsOne("@V(false)")
.doesNotContain("@D()")
.containsOne("@D")
.containsOne("int a();")
.containsOne("float value() default 1.1f;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestArith2.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestArith2.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestArith2 extends IntegrationTest {
public static class TestCls {
public int test1(int a) {
return (a + 2) * 3;
}
public int test2(int a, int b, int c) {
return a + b + c;
}
public boolean test3(boolean a, boolean b, boolean c) {
return a | b | c;
}
public boolean test4(boolean a, boolean b, boolean c) {
return a & b & c;
}
public int substract(int a, int b, int c) {
return a - (b - c);
}
public int divide(int a, int b, int c) {
return a / (b / c);
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("return (a + 2) * 3;")
.doesNotContain("a + 2 * 3")
.contains("return a + b + c;")
.doesNotContain("return (a + b) + c;")
.contains("return a | b | c;")
.doesNotContain("return (a | b) | c;")
.contains("return a & b & c;")
.doesNotContain("return (a & b) & c;")
.contains("return a - (b - c);")
.doesNotContain("return a - b - c;")
.contains("return a / (b / c);")
.doesNotContain("return a / b / c;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestSpecialValues2.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestSpecialValues2.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSpecialValues2 extends IntegrationTest {
public static class TestCls {
private static int compareUnsigned(final int x, final int y) {
return Integer.compare(x + Integer.MIN_VALUE, y + Integer.MIN_VALUE);
}
}
@Test
public void test() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.countString(2, "Integer.MIN_VALUE");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestArithNot.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestArithNot.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestArithNot extends SmaliTest {
// @formatter:off
/*
Smali Code equivalent:
public static class TestCls {
public int test1(int a) {
return ~a;
}
public long test2(long b) {
return ~b;
}
}
*/
// @formatter:on
@Test
public void test() {
assertThat(getClassNodeFromSmaliWithPath("arith", "TestArithNot"))
.code()
.contains("return ~a;")
.contains("return ~b;")
.doesNotContain("^");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestArithConst.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestArithConst.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestArithConst extends SmaliTest {
@Test
public void test() {
noDebugInfo();
assertThat(getClassNodeFromSmaliWithPath("arith", "TestArithConst"))
.code()
.containsOne("return i + CONST_INT;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestXor.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestXor.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.SmaliTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestXor extends SmaliTest {
@SuppressWarnings("PointlessBooleanExpression")
public static class TestCls {
public boolean test1() {
return test() ^ true;
}
public boolean test2(boolean v) {
return v ^ true;
}
public boolean test() {
return true;
}
public void check() {
assertThat(test1()).isFalse();
assertThat(test2(true)).isFalse();
assertThat(test2(false)).isTrue();
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("return !test();")
.containsOne("return !v;");
}
@Test
public void smali() {
// @formatter:off
/*
public boolean test1() {
return test() ^ true;
}
public boolean test2() {
return test() ^ false;
}
public boolean test() {
return true;
}
*/
// @formatter:on
assertThat(getClassNodeFromSmali())
.code()
.containsOne("return !test();")
.containsOne("return test();");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestPrimitivesNegate.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestPrimitivesNegate.java | package jadx.tests.integration.arith;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.extensions.profiles.TestProfile;
import jadx.tests.api.extensions.profiles.TestWithProfiles;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestPrimitivesNegate extends IntegrationTest {
@SuppressWarnings("UnnecessaryUnaryMinus")
public static class TestCls {
public double test() {
double[] arr = new double[5];
arr[0] = -20;
arr[0] += -79;
return arr[0];
}
public void check() {
assertThat(test()).isEqualTo(-99);
}
}
@TestWithProfiles({ TestProfile.DX_J8, TestProfile.JAVA8 })
public void test() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("dArr[0] = -20.0d;")
.containsOne("dArr[0] = dArr[0] - 79.0d;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestSpecialValues.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestSpecialValues.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestSpecialValues extends IntegrationTest {
public static class TestCls {
public void test() {
shorts(Short.MIN_VALUE, Short.MAX_VALUE);
ints(Integer.MIN_VALUE, Integer.MAX_VALUE);
longs(Long.MIN_VALUE, Long.MAX_VALUE);
floats(Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY,
Float.MIN_VALUE, Float.MAX_VALUE, Float.MIN_NORMAL);
doubles(Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY,
Double.MIN_VALUE, Double.MAX_VALUE, Double.MIN_NORMAL);
}
private void shorts(short... v) {
}
private void ints(int... v) {
}
private void longs(long... v) {
}
private void floats(float... v) {
}
private void doubles(double... v) {
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsOne(
"Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Float.MIN_VALUE, Float.MAX_VALUE, Float.MIN_NORMAL")
.containsOne("Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, "
+ "Double.MIN_VALUE, Double.MAX_VALUE, Double.MIN_NORMAL")
.containsOne("Short.MIN_VALUE, Short.MAX_VALUE")
.containsOne("Integer.MIN_VALUE, Integer.MAX_VALUE")
.containsOne("Long.MIN_VALUE, Long.MAX_VALUE");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestFieldIncrement3.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestFieldIncrement3.java | package jadx.tests.integration.arith;
import java.util.Random;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestFieldIncrement3 extends IntegrationTest {
public static class TestCls {
static int tileX;
static int tileY;
static Vector2 targetPos = new Vector2();
static Vector2 directVect = new Vector2();
static Vector2 newPos = new Vector2();
public static void test() {
Random rd = new Random();
int direction = rd.nextInt(7);
switch (direction) {
case 0:
targetPos.x = ((tileX + 1) * 55) + 55;
targetPos.y = ((tileY + 1) * 35) + 35;
break;
case 2:
targetPos.x = ((tileX + 1) * 55) + 55;
targetPos.y = ((tileY - 1) * 35) + 35;
break;
case 4:
targetPos.x = ((tileX - 1) * 55) + 55;
targetPos.y = ((tileY - 1) * 35) + 35;
break;
case 6:
targetPos.x = ((tileX - 1) * 55) + 55;
targetPos.y = ((tileY + 1) * 35) + 35;
break;
default:
break;
}
directVect.x = targetPos.x - newPos.x;
directVect.y = targetPos.y - newPos.y;
float hPos = (float) Math.sqrt((directVect.x * directVect.x) + (directVect.y * directVect.y));
directVect.x /= hPos;
directVect.y /= hPos;
}
static class Vector2 {
public float x;
public float y;
public Vector2() {
this.x = 0.0f;
this.y = 0.0f;
}
public boolean equals(Vector2 other) {
return (this.x == other.x && this.y == other.y);
}
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("directVect.x = targetPos.x - newPos.x;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestFieldIncrement.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestFieldIncrement.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestFieldIncrement extends IntegrationTest {
public static class TestCls {
public int instanceField = 1;
public static int staticField = 1;
public static String result = "";
public void method() {
instanceField++;
}
public void method2() {
staticField--;
}
public void method3(String s) {
result += s + '_';
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("instanceField++;")
.contains("staticField--;")
.contains("result += s + '_';");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestArith3.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestArith3.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestArith3 extends IntegrationTest {
public static class TestCls {
public int vp;
public void test(byte[] buffer) {
int n = ((buffer[3] & 255) + 4) + ((buffer[2] & 15) << 8);
while (n + 4 < buffer.length) {
int p = (buffer[n + 2] & 255) + ((buffer[n + 1] & 31) << 8);
int len = (buffer[n + 4] & 255) + ((buffer[n + 3] & 15) << 8);
int c = buffer[n] & 255;
switch (c) {
case 27:
this.vp = p;
break;
}
n += len + 5;
}
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.containsOne("while (n + 4 < buffer.length) {")
.containsOne(indent() + "n += len + 5;")
.doesNotContain("; n += len + 5) {")
.doesNotContain("default:");
}
@Test
public void testNoDebug() {
noDebugInfo();
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.containsOne("while (");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestNumbersFormat.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestNumbersFormat.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.api.args.IntegerFormat;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestNumbersFormat extends IntegrationTest {
@SuppressWarnings({ "FieldCanBeLocal", "UnusedAssignment", "unused" })
public static class TestCls {
private Object obj;
public void test() {
obj = new byte[] { 0, -1, -0xA, (byte) 0xff, Byte.MIN_VALUE, Byte.MAX_VALUE };
obj = new short[] { 0, -1, -0xA, (short) 0xffff, Short.MIN_VALUE, Short.MAX_VALUE };
obj = new int[] { 0, -1, -0xA, 0xffff_ffff, Integer.MIN_VALUE, Integer.MAX_VALUE };
obj = new long[] { 0, -1, -0xA, 0xffff_ffff_ffff_ffffL, Long.MIN_VALUE, Long.MAX_VALUE };
}
}
@Test
public void test() {
getArgs().setIntegerFormat(IntegerFormat.AUTO);
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("new byte[]{0, -1, -10, -1, -128, 127}")
.containsOne("new short[]{0, -1, -10, -1, Short.MIN_VALUE, Short.MAX_VALUE}")
.containsOne("new int[]{0, -1, -10, -1, Integer.MIN_VALUE, Integer.MAX_VALUE}")
.containsOne("new long[]{0, -1, -10, -1, Long.MIN_VALUE, Long.MAX_VALUE}");
}
@Test
public void testDecimalFormat() {
getArgs().setIntegerFormat(IntegerFormat.DECIMAL);
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("new byte[]{0, -1, -10, -1, -128, 127}")
.containsOne("new short[]{0, -1, -10, -1, -32768, 32767}")
.containsOne("new int[]{0, -1, -10, -1, -2147483648, 2147483647}")
.containsOne("new long[]{0, -1, -10, -1, -9223372036854775808L, 9223372036854775807L}");
}
@Test
public void testHexFormat() {
getArgs().setIntegerFormat(IntegerFormat.HEXADECIMAL);
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("new byte[]{0x0, (byte) 0xff, (byte) 0xf6, (byte) 0xff, (byte) 0x80, 0x7f}")
.containsOne("new short[]{0x0, (short) 0xffff, (short) 0xfff6, (short) 0xffff, (short) 0x8000, 0x7fff}")
.containsOne("new int[]{0x0, (int) 0xffffffff, (int) 0xfffffff6, (int) 0xffffffff, (int) 0x80000000, 0x7fffffff}")
.containsOne(
"new long[]{0x0, 0xffffffffffffffffL, 0xfffffffffffffff6L, 0xffffffffffffffffL, 0x8000000000000000L, 0x7fffffffffffffffL}");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestFieldIncrement2.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestFieldIncrement2.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
public class TestFieldIncrement2 extends IntegrationTest {
public static class TestCls {
private static class A {
int f = 5;
}
public A a;
public void test1(int n) {
this.a.f = this.a.f + n;
}
public void test2(int n) {
this.a.f *= n;
}
}
@Test
public void test() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("this.a.f += n;")
.contains("this.a.f *= n;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestArith.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestArith.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.NotYetImplemented;
import jadx.tests.api.IntegrationTest;
import jadx.tests.api.utils.assertj.JadxAssertions;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestArith extends IntegrationTest {
public static class TestCls {
public static final int F = 7;
public int test(int a) {
a += 2;
use(a);
return a;
}
public int test2(int a) {
a++;
use(a);
return a;
}
private static void use(int i) {
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code();
}
@Test
@NotYetImplemented
public void test2() {
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("a += 2;")
.contains("a++;");
}
@Test
public void testNoDebug() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code();
}
@Test
@NotYetImplemented
public void testNoDebug2() {
noDebugInfo();
JadxAssertions.assertThat(getClassNode(TestCls.class))
.code()
.contains("i += 2;")
.contains("i++;");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-core/src/test/java/jadx/tests/integration/arith/TestArith4.java | jadx-core/src/test/java/jadx/tests/integration/arith/TestArith4.java | package jadx.tests.integration.arith;
import org.junit.jupiter.api.Test;
import jadx.tests.api.IntegrationTest;
import static jadx.tests.api.utils.assertj.JadxAssertions.assertThat;
public class TestArith4 extends IntegrationTest {
public static class TestCls {
public static byte test(byte b) {
int k = b & 7;
return (byte) (((b & 255) >>> (8 - k)) | (b << k));
}
public static int test2(String str) {
int k = 'a' | str.charAt(0);
return (1 - k) & (1 + k);
}
}
@Test
public void test() {
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("int k = b & 7;")
.containsOne("& 255")
.containsOneOf("return (1 - k) & (1 + k);", "return (1 - k) & (k + 1);");
}
@Test
public void testNoDebug() {
noDebugInfo();
assertThat(getClassNode(TestCls.class))
.code()
.containsOne("& 255");
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.