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/settings/data/TabViewState.java | jadx-gui/src/main/java/jadx/gui/settings/data/TabViewState.java | package jadx.gui.settings.data;
public class TabViewState {
private String type;
private String tabPath;
private String subPath;
private int caret;
private ViewPoint view;
boolean active;
boolean pinned;
boolean bookmarked;
boolean hidden;
boolean previewTab;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTabPath() {
return tabPath;
}
public void setTabPath(String tabPath) {
this.tabPath = tabPath;
}
public String getSubPath() {
return subPath;
}
public void setSubPath(String subPath) {
this.subPath = subPath;
}
public int getCaret() {
return caret;
}
public void setCaret(int caret) {
this.caret = caret;
}
public ViewPoint getView() {
return view;
}
public void setView(ViewPoint view) {
this.view = view;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isPinned() {
return pinned;
}
public void setPinned(boolean pinned) {
this.pinned = pinned;
}
public boolean isBookmarked() {
return bookmarked;
}
public void setBookmarked(boolean bookmarked) {
this.bookmarked = bookmarked;
}
public boolean isHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public boolean isPreviewTab() {
return previewTab;
}
public void setPreviewTab(boolean previewTab) {
this.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/settings/data/SaveOptionEnum.java | jadx-gui/src/main/java/jadx/gui/settings/data/SaveOptionEnum.java | package jadx.gui.settings.data;
public enum SaveOptionEnum {
ASK,
NEVER,
ALWAYS
}
| 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/settings/data/ProjectData.java | jadx-gui/src/main/java/jadx/gui/settings/data/ProjectData.java | package jadx.gui.settings.data;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import jadx.api.data.impl.JadxCodeData;
import jadx.gui.search.providers.ResourceFilter;
public class ProjectData {
private int projectVersion = 2;
private List<Path> files = new ArrayList<>();
private List<String> treeExpansionsV2 = new ArrayList<>();
private JadxCodeData codeData = new JadxCodeData();
private List<TabViewState> openTabs = Collections.emptyList();
private @Nullable Path mappingsPath;
private @Nullable String cacheDir; // don't use relative path adapter
private boolean enableLiveReload = false;
private List<String> searchHistory = new ArrayList<>();
private String searchResourcesFilter = ResourceFilter.DEFAULT_STR;
private int searchResourcesSizeLimit = 0; // in MB
protected Map<String, String> pluginOptions = new HashMap<>();
public List<Path> getFiles() {
return files;
}
public void setFiles(List<Path> files) {
this.files = Objects.requireNonNull(files);
}
public List<String> getTreeExpansionsV2() {
return treeExpansionsV2;
}
public void setTreeExpansionsV2(List<String> treeExpansionsV2) {
this.treeExpansionsV2 = treeExpansionsV2;
}
public JadxCodeData getCodeData() {
return codeData;
}
public void setCodeData(JadxCodeData codeData) {
this.codeData = codeData;
}
public int getProjectVersion() {
return projectVersion;
}
public void setProjectVersion(int projectVersion) {
this.projectVersion = projectVersion;
}
public List<TabViewState> getOpenTabs() {
return openTabs;
}
public boolean setOpenTabs(List<TabViewState> openTabs) {
if (this.openTabs.equals(openTabs)) {
return false;
}
this.openTabs = openTabs;
return true;
}
@Nullable
public Path getMappingsPath() {
return mappingsPath;
}
public void setMappingsPath(Path mappingsPath) {
this.mappingsPath = mappingsPath;
}
public @Nullable String getCacheDir() {
return cacheDir;
}
public void setCacheDir(@Nullable String cacheDir) {
this.cacheDir = cacheDir;
}
public boolean isEnableLiveReload() {
return enableLiveReload;
}
public void setEnableLiveReload(boolean enableLiveReload) {
this.enableLiveReload = enableLiveReload;
}
public List<String> getSearchHistory() {
return searchHistory;
}
public void setSearchHistory(List<String> searchHistory) {
this.searchHistory = searchHistory;
}
public String getSearchResourcesFilter() {
return searchResourcesFilter;
}
public void setSearchResourcesFilter(String searchResourcesFilter) {
this.searchResourcesFilter = searchResourcesFilter;
}
public int getSearchResourcesSizeLimit() {
return searchResourcesSizeLimit;
}
public void setSearchResourcesSizeLimit(int searchResourcesSizeLimit) {
this.searchResourcesSizeLimit = searchResourcesSizeLimit;
}
public Map<String, String> getPluginOptions() {
return pluginOptions;
}
}
| 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/settings/data/ShortcutsWrapper.java | jadx-gui/src/main/java/jadx/gui/settings/data/ShortcutsWrapper.java | package jadx.gui.settings.data;
import java.util.Map;
import jadx.gui.ui.action.ActionModel;
import jadx.gui.utils.shortcut.Shortcut;
public class ShortcutsWrapper {
private Map<ActionModel, Shortcut> shortcuts;
public void updateShortcuts(Map<ActionModel, Shortcut> shortcuts) {
this.shortcuts = shortcuts;
}
public Shortcut get(ActionModel actionModel) {
return shortcuts.getOrDefault(actionModel, actionModel.getDefaultShortcut());
}
public void put(ActionModel actionModel, Shortcut shortcut) {
shortcuts.put(actionModel, shortcut);
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/ui/JadxSettingsWindow.java | jadx-gui/src/main/java/jadx/gui/settings/ui/JadxSettingsWindow.java | package jadx.gui.settings.ui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.CommentsLevel;
import jadx.api.DecompilationMode;
import jadx.api.JadxArgs;
import jadx.api.JadxArgs.UseKotlinMethodsForVarNames;
import jadx.api.JadxDecompiler;
import jadx.api.args.GeneratedRenamesMappingFileMode;
import jadx.api.args.IntegerFormat;
import jadx.api.args.ResourceNameSource;
import jadx.api.args.UseSourceNameAsClassNameAlias;
import jadx.api.plugins.events.JadxEvents;
import jadx.api.plugins.events.types.ReloadSettingsWindow;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.core.utils.StringUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.JadxSettingsData;
import jadx.gui.settings.JadxUpdateChannel;
import jadx.gui.settings.LineNumbersMode;
import jadx.gui.settings.XposedCodegenLanguage;
import jadx.gui.settings.data.SaveOptionEnum;
import jadx.gui.settings.font.FontAdapter;
import jadx.gui.settings.font.FontSettings;
import jadx.gui.settings.ui.cache.CacheSettingsGroup;
import jadx.gui.settings.ui.font.JadxFontDialog;
import jadx.gui.settings.ui.plugins.PluginSettings;
import jadx.gui.settings.ui.shortcut.ShortcutsSettingsGroup;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.codearea.theme.EditorThemeManager;
import jadx.gui.ui.codearea.theme.ThemeIdAndName;
import jadx.gui.ui.tab.dnd.TabDndGhostType;
import jadx.gui.utils.FontUtils;
import jadx.gui.utils.LafManager;
import jadx.gui.utils.LangLocale;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.ActionHandler;
public class JadxSettingsWindow extends JDialog {
private static final long serialVersionUID = -1804570470377354148L;
private static final Logger LOG = LoggerFactory.getLogger(JadxSettingsWindow.class);
private final transient MainWindow mainWindow;
private final transient JadxSettings settings;
private final transient String startSettings;
private final transient String startSettingsHash;
private final transient LangLocale prevLang;
private final transient Consumer<ReloadSettingsWindow> reloadListener;
private transient boolean needReload = false;
private transient SettingsTree tree;
private List<ISettingsGroup> groups;
private JPanel wrapGroupPanel;
public JadxSettingsWindow(MainWindow mainWindow, JadxSettings settings) {
this.mainWindow = mainWindow;
this.settings = settings;
this.startSettings = settings.getSettingsJsonString();
this.startSettingsHash = calcSettingsHash();
this.prevLang = settings.getLangLocale();
initUI();
setTitle(NLS.str("preferences.title"));
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
pack();
UiUtils.setWindowIcons(this);
setLocationRelativeTo(null);
if (!mainWindow.getSettings().loadWindowPos(this)) {
setSize(700, 800);
}
reloadListener = ev -> UiUtils.uiRun(this::reloadUI);
mainWindow.events().global().addListener(JadxEvents.RELOAD_SETTINGS_WINDOW, reloadListener);
}
private void reloadUI() {
int[] selection = tree.getSelectionRows();
closeGroups(false);
getContentPane().removeAll();
initUI();
// wait for other events to process
UiUtils.uiRun(() -> {
tree.setSelectionRows(selection);
SwingUtilities.updateComponentTreeUI(this);
});
}
private void initUI() {
wrapGroupPanel = new JPanel(new BorderLayout(10, 10));
groups = new ArrayList<>();
groups.add(makeDecompilationGroup());
groups.add(makeDeobfuscationGroup());
groups.add(makeRenameGroup());
groups.add(new CacheSettingsGroup(this));
groups.add(makeAppearanceGroup());
groups.add(new ShortcutsSettingsGroup(this, settings));
groups.add(makeProjectGroup());
groups.add(new PluginSettings(mainWindow, settings).build());
groups.add(makeOtherGroup());
tree = new SettingsTree(this);
tree.init(groups);
tree.setFocusable(true);
JScrollPane leftPane = new JScrollPane(tree);
leftPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 3, 3));
JScrollPane rightPane = new JScrollPane(wrapGroupPanel);
rightPane.getVerticalScrollBar().setUnitIncrement(16);
rightPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
rightPane.setBorder(BorderFactory.createEmptyBorder(10, 3, 3, 10));
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.2);
splitPane.setLeftComponent(leftPane);
splitPane.setRightComponent(rightPane);
Container contentPane = getContentPane();
contentPane.add(splitPane, BorderLayout.CENTER);
contentPane.add(buildButtonsPane(), BorderLayout.PAGE_END);
KeyStroke strokeEsc = KeyStroke.getKeyStroke("ESCAPE");
InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(strokeEsc, "ESCAPE");
getRootPane().getActionMap().put("ESCAPE", new ActionHandler(this::cancel));
}
private JPanel buildButtonsPane() {
JButton saveBtn = new JButton(NLS.str("preferences.save"));
saveBtn.addActionListener(event -> save());
JButton cancelButton = new JButton(NLS.str("preferences.cancel"));
cancelButton.addActionListener(event -> cancel());
JButton resetBtn = new JButton(NLS.str("preferences.reset"));
resetBtn.addActionListener(event -> reset());
JButton copyBtn = new JButton(NLS.str("preferences.copy"));
copyBtn.addActionListener(event -> copySettings());
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
buttonPane.add(resetBtn);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(copyBtn);
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(saveBtn);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(cancelButton);
getRootPane().setDefaultButton(saveBtn);
return buttonPane;
}
/**
* Activate the settings page by location.
*
* @param location - can be title of a settings group or settings group class implementation (end
* with .class)
*/
public void activatePage(String location) {
if (location.endsWith(".class")) {
String clsName = StringUtils.removeSuffix(location, ".class");
for (ISettingsGroup group : groups) {
String groupCls = group.getClass().getSimpleName();
if (groupCls.equals(clsName)) {
selectGroup(group);
return;
}
}
throw new JadxRuntimeException("No setting group class: " + location);
} else {
for (ISettingsGroup group : groups) {
if (group.getTitle().equals(location)) {
selectGroup(group);
return;
}
}
throw new JadxRuntimeException("No setting group with title: " + location);
}
}
public void selectGroup(ISettingsGroup group) {
tree.selectGroup(group);
}
public void activateGroup(@Nullable ISettingsGroup group) {
wrapGroupPanel.removeAll();
if (group != null) {
wrapGroupPanel.add(group.buildComponent());
}
wrapGroupPanel.updateUI();
}
private static void enableComponents(Container container, boolean enable) {
for (Component component : container.getComponents()) {
if (component instanceof Container) {
enableComponents((Container) component, enable);
}
component.setEnabled(enable);
}
}
private SettingsGroup makeDeobfuscationGroup() {
JCheckBox deobfOn = new JCheckBox();
deobfOn.setSelected(settings.isDeobfuscationOn());
deobfOn.addItemListener(e -> {
settings.setDeobfuscationOn(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
SpinnerNumberModel minLenModel = new SpinnerNumberModel(settings.getDeobfuscationMinLength(), 0, Integer.MAX_VALUE, 1);
JSpinner minLenSpinner = new JSpinner(minLenModel);
minLenSpinner.addChangeListener(e -> {
settings.setDeobfuscationMinLength((Integer) minLenSpinner.getValue());
needReload();
});
SpinnerNumberModel maxLenModel = new SpinnerNumberModel(settings.getDeobfuscationMaxLength(), 0, Integer.MAX_VALUE, 1);
JSpinner maxLenSpinner = new JSpinner(maxLenModel);
maxLenSpinner.addChangeListener(e -> {
settings.setDeobfuscationMaxLength((Integer) maxLenSpinner.getValue());
needReload();
});
JComboBox<ResourceNameSource> resNamesSource = new JComboBox<>(ResourceNameSource.values());
resNamesSource.setSelectedItem(settings.getResourceNameSource());
resNamesSource.addActionListener(e -> {
settings.setResourceNameSource((ResourceNameSource) resNamesSource.getSelectedItem());
needReload();
});
JCheckBox useHeaders = new JCheckBox();
useHeaders.setSelected(settings.isUseHeadersForDetectResourceExtensions());
useHeaders.addItemListener(e -> {
settings.setUseHeadersForDetectResourceExtensions(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JComboBox<GeneratedRenamesMappingFileMode> generatedRenamesMappingFileModeCB =
new JComboBox<>(GeneratedRenamesMappingFileMode.values());
generatedRenamesMappingFileModeCB.setSelectedItem(settings.getGeneratedRenamesMappingFileMode());
generatedRenamesMappingFileModeCB.addActionListener(e -> {
GeneratedRenamesMappingFileMode newValue =
(GeneratedRenamesMappingFileMode) generatedRenamesMappingFileModeCB.getSelectedItem();
if (newValue != settings.getGeneratedRenamesMappingFileMode()) {
settings.setGeneratedRenamesMappingFileMode(newValue);
needReload();
}
});
JButton editWhitelistedEntities = new JButton(NLS.str("preferences.excludedPackages.button"));
editWhitelistedEntities.addActionListener(event -> {
String prevWhitelistedEntities = settings.getDeobfuscationWhitelistStr();
String result = JOptionPane.showInputDialog(this,
NLS.str("preferences.deobfuscation_whitelist.editDialog"),
prevWhitelistedEntities);
if (result != null) {
settings.setDeobfuscationWhitelistStr(result);
if (!prevWhitelistedEntities.equals(result)) {
needReload();
}
}
});
SettingsGroup deobfGroup = new SettingsGroup(NLS.str("preferences.deobfuscation"));
deobfGroup.addRow(NLS.str("preferences.deobfuscation_on"), deobfOn);
deobfGroup.addRow(NLS.str("preferences.deobfuscation_min_len"), minLenSpinner);
deobfGroup.addRow(NLS.str("preferences.deobfuscation_max_len"), maxLenSpinner);
deobfGroup.addRow(NLS.str("preferences.deobfuscation_res_name_source"), resNamesSource);
deobfGroup.addRow(NLS.str("preferences.deobfuscation_res_use_headers"), useHeaders);
deobfGroup.addRow(NLS.str("preferences.generated_renames_mapping_file_mode"), generatedRenamesMappingFileModeCB);
deobfGroup.addRow(NLS.str("preferences.deobfuscation_whitelist"),
NLS.str("preferences.deobfuscation_whitelist.tooltip"), editWhitelistedEntities);
deobfGroup.end();
Collection<JComponent> connectedComponents = Arrays.asList(minLenSpinner, maxLenSpinner);
deobfOn.addItemListener(e -> enableComponentList(connectedComponents, e.getStateChange() == ItemEvent.SELECTED));
enableComponentList(connectedComponents, settings.isDeobfuscationOn());
return deobfGroup;
}
private SettingsGroup makeRenameGroup() {
JCheckBox renameCaseSensitive = new JCheckBox();
renameCaseSensitive.setSelected(settings.isRenameCaseSensitive());
renameCaseSensitive.addItemListener(e -> {
settings.updateRenameFlag(JadxArgs.RenameEnum.CASE, e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox renameValid = new JCheckBox();
renameValid.setSelected(settings.isRenameValid());
renameValid.addItemListener(e -> {
settings.updateRenameFlag(JadxArgs.RenameEnum.VALID, e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox renamePrintable = new JCheckBox();
renamePrintable.setSelected(settings.isRenamePrintable());
renamePrintable.addItemListener(e -> {
settings.updateRenameFlag(JadxArgs.RenameEnum.PRINTABLE, e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JComboBox<UseSourceNameAsClassNameAlias> useSourceNameAsClassNameAlias = new JComboBox<>(UseSourceNameAsClassNameAlias.values());
useSourceNameAsClassNameAlias.setSelectedItem(settings.getUseSourceNameAsClassNameAlias());
useSourceNameAsClassNameAlias.addActionListener(e -> {
settings.setUseSourceNameAsClassNameAlias((UseSourceNameAsClassNameAlias) useSourceNameAsClassNameAlias.getSelectedItem());
needReload();
});
JSpinner repeatLimit = new JSpinner(new SpinnerNumberModel(settings.getSourceNameRepeatLimit(), 1, Integer.MAX_VALUE, 1));
repeatLimit.addChangeListener(e -> {
settings.setSourceNameRepeatLimit((Integer) repeatLimit.getValue());
needReload();
});
SettingsGroup group = new SettingsGroup(NLS.str("preferences.rename"));
group.addRow(NLS.str("preferences.rename_case"), renameCaseSensitive);
group.addRow(NLS.str("preferences.rename_valid"), renameValid);
group.addRow(NLS.str("preferences.rename_printable"), renamePrintable);
group.addRow(NLS.str("preferences.rename_use_source_name_as_class_name_alias"), useSourceNameAsClassNameAlias);
group.addRow(NLS.str("preferences.rename_source_name_repeat_limit"), repeatLimit);
return group;
}
private void enableComponentList(Collection<JComponent> connectedComponents, boolean enabled) {
connectedComponents.forEach(comp -> comp.setEnabled(enabled));
}
private SettingsGroup makeProjectGroup() {
JComboBox<SaveOptionEnum> dropdown = new JComboBox<>(SaveOptionEnum.values());
dropdown.setSelectedItem(settings.getSaveOption());
dropdown.addActionListener(e -> {
settings.setSaveOption((SaveOptionEnum) dropdown.getSelectedItem());
needReload();
});
SettingsGroup group = new SettingsGroup(NLS.str("preferences.project"));
group.addRow(NLS.str("preferences.saveOption"), dropdown);
return group;
}
private SettingsGroup makeAppearanceGroup() {
JComboBox<LangLocale> languageCbx = new JComboBox<>(NLS.getLangLocales());
for (LangLocale locale : NLS.getLangLocales()) {
if (locale.equals(settings.getLangLocale())) {
languageCbx.setSelectedItem(locale);
break;
}
}
languageCbx.addActionListener(e -> settings.setLangLocale((LangLocale) languageCbx.getSelectedItem()));
EditorThemeManager editorThemeManager = mainWindow.getEditorThemeManager();
JComboBox<ThemeIdAndName> themesCbx = new JComboBox<>(editorThemeManager.getThemeIdNameArray());
themesCbx.setSelectedItem(editorThemeManager.getCurrentThemeIdName());
themesCbx.addActionListener(evt -> {
ThemeIdAndName selected = (ThemeIdAndName) themesCbx.getSelectedItem();
if (selected != null) {
settings.setEditorTheme(selected.getId());
mainWindow.loadSettings();
}
});
JComboBox<String> lafCbx = new JComboBox<>(LafManager.getThemes());
lafCbx.setSelectedItem(settings.getLafTheme());
lafCbx.addActionListener(e -> {
settings.setLafTheme((String) lafCbx.getSelectedItem());
mainWindow.loadSettings();
});
JSpinner uiZoomSpinner = new JSpinner(new SpinnerNumberModel(settings.getUiZoom(), 0.1, 10.0, 0.25));
uiZoomSpinner.addChangeListener(e -> {
float zoomValue = ((Double) uiZoomSpinner.getValue()).floatValue();
settings.setUiZoom(zoomValue);
mainWindow.loadSettings();
});
JCheckBox applyUiZoomToFontsChB = new JCheckBox();
applyUiZoomToFontsChB.setSelected(settings.isApplyUiZoomToFonts());
applyUiZoomToFontsChB.addItemListener(e -> {
settings.setApplyUiZoomToFonts(e.getStateChange() == ItemEvent.SELECTED);
mainWindow.loadSettings();
});
SettingsGroup group = new SettingsGroup(NLS.str("preferences.appearance"));
group.addRow(NLS.str("preferences.language"), languageCbx);
group.addRow(NLS.str("preferences.ui_zoom"), uiZoomSpinner);
group.addRow(NLS.str("preferences.apply_ui_zoom_to_fonts"), applyUiZoomToFontsChB);
FontSettings fontSettings = settings.getFontSettings();
addFontEditor(group, NLS.str("preferences.ui_font"), fontSettings.getUiFontAdapter(), false);
addFontEditor(group, NLS.str("preferences.code_font"), fontSettings.getCodeFontAdapter(), false);
addFontEditor(group, NLS.str("preferences.smali_font"), fontSettings.getSmaliFontAdapter(), true);
group.addRow(NLS.str("preferences.laf_theme"), lafCbx);
group.addRow(NLS.str("preferences.theme"), themesCbx);
JComboBox<TabDndGhostType> tabDndGhostTypeCbx = new JComboBox<>(TabDndGhostType.values());
tabDndGhostTypeCbx.setSelectedItem(settings.getTabDndGhostType());
tabDndGhostTypeCbx.addActionListener(e -> {
settings.setTabDndGhostType((TabDndGhostType) tabDndGhostTypeCbx.getSelectedItem());
mainWindow.loadSettings();
});
group.addRow(NLS.str("preferences.tab_dnd_appearance"), tabDndGhostTypeCbx);
return group;
}
private void addFontEditor(SettingsGroup group, String title, FontAdapter fontAdapter, boolean monospace) {
JLabel fontLabel = new JLabel(getFontLabelStr(fontAdapter.getFont()));
JButton fontBtn = new JButton(NLS.str("preferences.select_font"));
fontBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Font font = new JadxFontDialog(JadxSettingsWindow.this, settings, title)
.select(fontAdapter.getFont(), monospace);
if (font != null) {
fontLabel.setText(getFontLabelStr(font));
fontAdapter.setFont(font);
mainWindow.loadSettings();
}
}
});
JPanel fontPanel = new JPanel();
fontPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
fontPanel.add(fontLabel);
fontPanel.add(fontBtn);
group.addRow(title, fontPanel);
}
private static String getFontLabelStr(Font font) {
return font.getFamily()
+ ' ' + FontUtils.convertFontStyleToString(font.getStyle())
+ ' ' + font.getSize();
}
private SettingsGroup makeDecompilationGroup() {
JCheckBox useDx = new JCheckBox();
useDx.setSelected(settings.isUseDx());
useDx.addItemListener(e -> {
settings.setUseDx(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JComboBox<DecompilationMode> decompilationModeComboBox = new JComboBox<>(DecompilationMode.values());
decompilationModeComboBox.setSelectedItem(settings.getDecompilationMode());
decompilationModeComboBox.addActionListener(e -> {
settings.setDecompilationMode((DecompilationMode) decompilationModeComboBox.getSelectedItem());
needReload();
});
JCheckBox showInconsistentCode = new JCheckBox();
showInconsistentCode.setSelected(settings.isShowInconsistentCode());
showInconsistentCode.addItemListener(e -> {
settings.setShowInconsistentCode(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox resourceDecode = new JCheckBox();
resourceDecode.setSelected(settings.isSkipResources());
resourceDecode.addItemListener(e -> {
settings.setSkipResources(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
// fix for #1331
int threadsCountValue = settings.getThreadsCount();
int threadsCountMax = Math.max(2, Math.max(threadsCountValue, Runtime.getRuntime().availableProcessors() * 2));
SpinnerNumberModel spinnerModel = new SpinnerNumberModel(threadsCountValue, 1, threadsCountMax, 1);
JSpinner threadsCount = new JSpinner(spinnerModel);
threadsCount.addChangeListener(e -> {
settings.setThreadsCount((Integer) threadsCount.getValue());
needReload();
});
JButton editExcludedPackages = new JButton(NLS.str("preferences.excludedPackages.button"));
editExcludedPackages.addActionListener(event -> {
String oldExcludedPackages = settings.getExcludedPackages();
String result = JOptionPane.showInputDialog(this, NLS.str("preferences.excludedPackages.editDialog"),
settings.getExcludedPackages());
if (result != null) {
settings.setExcludedPackages(result);
if (!oldExcludedPackages.equals(result)) {
needReload();
}
}
});
JCheckBox autoStartJobs = new JCheckBox();
autoStartJobs.setSelected(settings.isAutoStartJobs());
autoStartJobs.addItemListener(e -> settings.setAutoStartJobs(e.getStateChange() == ItemEvent.SELECTED));
JCheckBox escapeUnicode = new JCheckBox();
escapeUnicode.setSelected(settings.isEscapeUnicode());
escapeUnicode.addItemListener(e -> {
settings.setEscapeUnicode(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox replaceConsts = new JCheckBox();
replaceConsts.setSelected(settings.isReplaceConsts());
replaceConsts.addItemListener(e -> {
settings.setReplaceConsts(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox respectBytecodeAccessModifiers = new JCheckBox();
respectBytecodeAccessModifiers.setSelected(settings.isRespectBytecodeAccessModifiers());
respectBytecodeAccessModifiers.addItemListener(e -> {
settings.setRespectBytecodeAccessModifiers(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox useImports = new JCheckBox();
useImports.setSelected(settings.isUseImports());
useImports.addItemListener(e -> {
settings.setUseImports(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox useDebugInfo = new JCheckBox();
useDebugInfo.setSelected(settings.isDebugInfo());
useDebugInfo.addItemListener(e -> {
settings.setDebugInfo(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox inlineAnonymous = new JCheckBox();
inlineAnonymous.setSelected(settings.isInlineAnonymousClasses());
inlineAnonymous.addItemListener(e -> {
settings.setInlineAnonymousClasses(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox inlineMethods = new JCheckBox();
inlineMethods.setSelected(settings.isInlineMethods());
inlineMethods.addItemListener(e -> {
settings.setInlineMethods(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox inlineKotlinLambdas = new JCheckBox();
inlineKotlinLambdas.setSelected(settings.isAllowInlineKotlinLambda());
inlineKotlinLambdas.addItemListener(e -> {
settings.setAllowInlineKotlinLambda(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox moveInnerClasses = new JCheckBox();
moveInnerClasses.setSelected(settings.isMoveInnerClasses());
moveInnerClasses.addItemListener(e -> {
settings.setMoveInnerClasses(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox extractFinally = new JCheckBox();
extractFinally.setSelected(settings.isExtractFinally());
extractFinally.addItemListener(e -> {
settings.setExtractFinally(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox restoreSwitchOverString = new JCheckBox();
restoreSwitchOverString.setSelected(settings.isRestoreSwitchOverString());
restoreSwitchOverString.addItemListener(e -> {
settings.setRestoreSwitchOverString(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox fsCaseSensitive = new JCheckBox();
fsCaseSensitive.setSelected(settings.isFsCaseSensitive());
fsCaseSensitive.addItemListener(e -> {
settings.setFsCaseSensitive(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JComboBox<UseKotlinMethodsForVarNames> kotlinRenameVars = new JComboBox<>(UseKotlinMethodsForVarNames.values());
kotlinRenameVars.setSelectedItem(settings.getUseKotlinMethodsForVarNames());
kotlinRenameVars.addActionListener(e -> {
settings.setUseKotlinMethodsForVarNames((UseKotlinMethodsForVarNames) kotlinRenameVars.getSelectedItem());
needReload();
});
JComboBox<CommentsLevel> commentsLevel = new JComboBox<>(CommentsLevel.values());
commentsLevel.setSelectedItem(settings.getCommentsLevel());
commentsLevel.addActionListener(e -> {
settings.setCommentsLevel((CommentsLevel) commentsLevel.getSelectedItem());
needReload();
});
JComboBox<IntegerFormat> integerFormat = new JComboBox<>(IntegerFormat.values());
integerFormat.setSelectedItem(settings.getIntegerFormat());
integerFormat.addActionListener(e -> {
settings.setIntegerFormat((IntegerFormat) integerFormat.getSelectedItem());
needReload();
});
JSpinner typeUpdatesLimitCount = new JSpinner(
new SpinnerNumberModel(settings.getTypeUpdatesLimitCount(), 1, Short.MAX_VALUE, 1));
typeUpdatesLimitCount.addChangeListener(e -> {
int newValue = (Integer) typeUpdatesLimitCount.getValue();
if (newValue < 1) {
UiUtils.uiRun(() -> typeUpdatesLimitCount.setValue(1));
} else {
settings.setTypeUpdatesLimitCount(newValue);
needReload();
}
});
SettingsGroup other = new SettingsGroup(NLS.str("preferences.decompile"));
other.addRow(NLS.str("preferences.threads"), threadsCount);
other.addRow(NLS.str("preferences.excludedPackages"),
NLS.str("preferences.excludedPackages.tooltip"), editExcludedPackages);
other.addRow(NLS.str("preferences.start_jobs"), autoStartJobs);
other.addRow(NLS.str("preferences.decompilationMode"), decompilationModeComboBox);
other.addRow(NLS.str("preferences.showInconsistentCode"), showInconsistentCode);
other.addRow(NLS.str("preferences.escapeUnicode"), escapeUnicode);
other.addRow(NLS.str("preferences.replaceConsts"), replaceConsts);
other.addRow(NLS.str("preferences.respectBytecodeAccessModifiers"), respectBytecodeAccessModifiers);
other.addRow(NLS.str("preferences.useImports"), useImports);
other.addRow(NLS.str("preferences.useDebugInfo"), useDebugInfo);
other.addRow(NLS.str("preferences.inlineAnonymous"), inlineAnonymous);
other.addRow(NLS.str("preferences.inlineMethods"), inlineMethods);
other.addRow(NLS.str("preferences.inlineKotlinLambdas"), inlineKotlinLambdas);
other.addRow(NLS.str("preferences.moveInnerClasses"), moveInnerClasses);
other.addRow(NLS.str("preferences.extractFinally"), extractFinally);
other.addRow(NLS.str("preferences.restoreSwitchOverString"), restoreSwitchOverString);
other.addRow(NLS.str("preferences.fsCaseSensitive"), fsCaseSensitive);
other.addRow(NLS.str("preferences.useDx"), useDx);
other.addRow(NLS.str("preferences.skipResourcesDecode"), resourceDecode);
other.addRow(NLS.str("preferences.useKotlinMethodsForVarNames"), kotlinRenameVars);
other.addRow(NLS.str("preferences.commentsLevel"), commentsLevel);
other.addRow(NLS.str("preferences.integerFormat"), integerFormat);
other.addRow(NLS.str("preferences.typeUpdatesCountLimit"), typeUpdatesLimitCount);
return other;
}
private SettingsGroup makeOtherGroup() {
JComboBox<LineNumbersMode> lineNumbersMode = new JComboBox<>(LineNumbersMode.values());
lineNumbersMode.setSelectedItem(settings.getLineNumbersMode());
lineNumbersMode.addActionListener(e -> {
settings.setLineNumbersMode((LineNumbersMode) lineNumbersMode.getSelectedItem());
mainWindow.loadSettings();
});
JCheckBox jumpOnDoubleClick = new JCheckBox();
jumpOnDoubleClick.setSelected(settings.isJumpOnDoubleClick());
jumpOnDoubleClick.addItemListener(e -> settings.setJumpOnDoubleClick(e.getStateChange() == ItemEvent.SELECTED));
JSpinner resultsPerPage = new JSpinner(
new SpinnerNumberModel(settings.getSearchResultsPerPage(), 0, Integer.MAX_VALUE, 1));
resultsPerPage.addChangeListener(ev -> settings.setSearchResultsPerPage((Integer) resultsPerPage.getValue()));
JCheckBox useAltFileDialog = new JCheckBox();
useAltFileDialog.setSelected(settings.isUseAlternativeFileDialog());
useAltFileDialog.addItemListener(e -> settings.setUseAlternativeFileDialog(e.getStateChange() == ItemEvent.SELECTED));
JCheckBox update = new JCheckBox();
update.setSelected(settings.isCheckForUpdates());
update.addItemListener(e -> settings.setCheckForUpdates(e.getStateChange() == ItemEvent.SELECTED));
JCheckBox disableTooltipOnHover = new JCheckBox();
disableTooltipOnHover.setSelected(settings.isDisableTooltipOnHover());
disableTooltipOnHover.addItemListener(e -> settings.setDisableTooltipOnHover(e.getStateChange() == ItemEvent.SELECTED));
JCheckBox cfg = new JCheckBox();
cfg.setSelected(settings.isCfgOutput());
cfg.addItemListener(e -> {
settings.setCfgOutput(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JCheckBox rawCfg = new JCheckBox();
rawCfg.setSelected(settings.isRawCfgOutput());
rawCfg.addItemListener(e -> {
settings.setRawCfgOutput(e.getStateChange() == ItemEvent.SELECTED);
needReload();
});
JComboBox<XposedCodegenLanguage> xposedCodegenLanguage = new JComboBox<>(XposedCodegenLanguage.values());
xposedCodegenLanguage.setSelectedItem(settings.getXposedCodegenLanguage());
xposedCodegenLanguage.addActionListener(e -> {
settings.setXposedCodegenLanguage((XposedCodegenLanguage) xposedCodegenLanguage.getSelectedItem());
mainWindow.loadSettings();
});
JComboBox<JadxUpdateChannel> updateChannel = new JComboBox<>(JadxUpdateChannel.values());
updateChannel.setSelectedItem(settings.getJadxUpdateChannel());
updateChannel.addActionListener(e -> {
settings.setJadxUpdateChannel((JadxUpdateChannel) updateChannel.getSelectedItem());
mainWindow.loadSettings();
});
SettingsGroup group = new SettingsGroup(NLS.str("preferences.other"));
group.addRow(NLS.str("preferences.lineNumbersMode"), lineNumbersMode);
group.addRow(NLS.str("preferences.jumpOnDoubleClick"), jumpOnDoubleClick);
group.addRow(NLS.str("preferences.disable_tooltip_on_hover"), disableTooltipOnHover);
group.addRow(NLS.str("preferences.search_results_per_page"), resultsPerPage);
group.addRow(NLS.str("preferences.useAlternativeFileDialog"), useAltFileDialog);
group.addRow(NLS.str("preferences.cfg"), cfg);
group.addRow(NLS.str("preferences.raw_cfg"), rawCfg);
group.addRow(NLS.str("preferences.xposed_codegen_language"), xposedCodegenLanguage);
group.addRow(NLS.str("preferences.check_for_updates"), update);
group.addRow(NLS.str("preferences.update_channel"), updateChannel);
return group;
}
private void closeGroups(boolean save) {
for (ISettingsGroup group : groups) {
group.close(save);
}
}
private void save() {
closeGroups(true);
settings.sync();
enableComponents(this, false);
SwingUtilities.invokeLater(() -> {
if (shouldReload()) {
mainWindow.getShortcutsController().loadSettings();
mainWindow.reopen();
}
if (!settings.getLangLocale().equals(prevLang)) {
JOptionPane.showMessageDialog(
this,
NLS.str("msg.language_changed", settings.getLangLocale()),
NLS.str("msg.language_changed_title", settings.getLangLocale()),
JOptionPane.INFORMATION_MESSAGE);
}
dispose();
});
}
private void cancel() {
closeGroups(false);
settings.loadSettingsFromJsonString(startSettings);
mainWindow.loadSettings();
dispose();
}
private void reset() {
int res = JOptionPane.showConfirmDialog(
JadxSettingsWindow.this,
NLS.str("preferences.reset_message"),
NLS.str("preferences.reset_title"),
JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.YES_OPTION) {
settings.loadSettingsData(new JadxSettingsData());
mainWindow.loadSettings();
needReload();
getContentPane().removeAll();
initUI();
pack();
repaint();
}
}
private void copySettings() {
String settingsText = settings.exportSettingsString();
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(settingsText);
clipboard.setContents(selection, selection);
JOptionPane.showMessageDialog(
JadxSettingsWindow.this,
NLS.str("preferences.copy_message"));
}
public void needReload() {
needReload = true;
}
private boolean shouldReload() {
return needReload || !startSettingsHash.equals(calcSettingsHash());
}
@SuppressWarnings("resource")
private String calcSettingsHash() {
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | true |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/ui/SettingsTreeNode.java | jadx-gui/src/main/java/jadx/gui/settings/ui/SettingsTreeNode.java | package jadx.gui.settings.ui;
import javax.swing.tree.DefaultMutableTreeNode;
import jadx.api.plugins.gui.ISettingsGroup;
public class SettingsTreeNode extends DefaultMutableTreeNode {
private final ISettingsGroup group;
public SettingsTreeNode(ISettingsGroup group) {
this.group = group;
}
public ISettingsGroup getGroup() {
return group;
}
@Override
public String toString() {
return group.getTitle();
}
}
| 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/settings/ui/SettingsGroup.java | jadx-gui/src/main/java/jadx/gui/settings/ui/SettingsGroup.java | package jadx.gui.settings.ui;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import jadx.api.plugins.gui.ISettingsGroup;
public class SettingsGroup implements ISettingsGroup {
private final String title;
private final JPanel panel;
private final JPanel gridPanel;
private final GridBagConstraints c;
private int row;
public SettingsGroup(String title) {
this.title = title;
gridPanel = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.weighty = 1.0;
panel = new JPanel();
panel.setLayout(new BorderLayout(5, 5));
panel.setBorder(BorderFactory.createTitledBorder(title));
panel.add(gridPanel, BorderLayout.PAGE_START);
}
public JLabel addRow(String label, JComponent comp) {
return addRow(label, null, comp);
}
public JLabel addRow(String label, String tooltip, JComponent comp) {
JLabel rowLbl = new JLabel(label);
rowLbl.setLabelFor(comp);
rowLbl.setHorizontalAlignment(SwingConstants.LEFT);
if (tooltip != null) {
rowLbl.setToolTipText(tooltip);
comp.setToolTipText(tooltip);
} else {
comp.setToolTipText(label);
}
comp.getAccessibleContext().setAccessibleName(label);
c.gridy = row++;
c.gridx = 0;
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.1;
c.fill = GridBagConstraints.LINE_START;
gridPanel.add(rowLbl, c);
c.gridx = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.7;
c.fill = GridBagConstraints.LINE_START;
gridPanel.add(comp, c);
comp.addPropertyChangeListener("enabled", evt -> rowLbl.setEnabled((boolean) evt.getNewValue()));
return rowLbl;
}
public void end() {
gridPanel.add(Box.createVerticalGlue());
}
@Override
public JComponent buildComponent() {
return panel;
}
@Override
public String getTitle() {
return title;
}
public JPanel getGridPanel() {
return gridPanel;
}
@Override
public String toString() {
return title;
}
}
| 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/settings/ui/SubSettingsGroup.java | jadx-gui/src/main/java/jadx/gui/settings/ui/SubSettingsGroup.java | package jadx.gui.settings.ui;
import java.util.ArrayList;
import java.util.List;
import jadx.api.plugins.gui.ISettingsGroup;
public class SubSettingsGroup extends SettingsGroup {
private final List<ISettingsGroup> groups = new ArrayList<>();
public SubSettingsGroup(String title) {
super(title);
}
@Override
public List<ISettingsGroup> getSubGroups() {
return groups;
}
}
| 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/settings/ui/SettingsTree.java | jadx-gui/src/main/java/jadx/gui/settings/ui/SettingsTree.java | package jadx.gui.settings.ui;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.utils.NLS;
public class SettingsTree extends JTree {
private final JadxSettingsWindow settingsWindow;
public SettingsTree(JadxSettingsWindow settingsWindow) {
this.settingsWindow = settingsWindow;
}
public void init(List<ISettingsGroup> groups) {
DefaultMutableTreeNode treeRoot = new DefaultMutableTreeNode(NLS.str("preferences.title"));
addGroups(treeRoot, groups);
setModel(new DefaultTreeModel(treeRoot));
getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
setFocusable(false);
addTreeSelectionListener(ev -> switchGroup());
// expand all nodes and disallow collapsing
setNodeExpandedState(this, treeRoot, true);
addTreeWillExpandListener(new DisableRootCollapseListener(treeRoot));
addSelectionRow(1);
}
private static void addGroups(DefaultMutableTreeNode base, List<ISettingsGroup> groups) {
for (ISettingsGroup group : groups) {
SettingsTreeNode node = new SettingsTreeNode(group);
base.add(node);
addGroups(node, group.getSubGroups());
}
}
public void selectGroup(ISettingsGroup group) {
SettingsTreeNode node = searchTreeNode(group);
if (node == null) {
throw new JadxRuntimeException("Settings group not found: " + group);
}
setSelectionPath(new TreePath(node.getPath()));
}
private @Nullable SettingsTreeNode searchTreeNode(ISettingsGroup group) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getModel().getRoot();
Enumeration<TreeNode> enumeration = root.children();
while (enumeration.hasMoreElements()) {
SettingsTreeNode node = (SettingsTreeNode) enumeration.nextElement();
if (node.getGroup() == group) {
return node;
}
}
return null;
}
private void switchGroup() {
Object selected = getLastSelectedPathComponent();
if (selected instanceof SettingsTreeNode) {
ISettingsGroup group = ((SettingsTreeNode) selected).getGroup();
settingsWindow.activateGroup(group);
} else {
settingsWindow.activateGroup(null);
}
}
private static void setNodeExpandedState(JTree tree, TreeNode node, boolean expanded) {
List<? extends TreeNode> list = Collections.list(node.children());
for (TreeNode treeNode : list) {
setNodeExpandedState(tree, treeNode, expanded);
}
DefaultMutableTreeNode mutableTreeNode = (DefaultMutableTreeNode) node;
if (!expanded && mutableTreeNode.isRoot()) {
return;
}
TreePath path = new TreePath(mutableTreeNode.getPath());
if (expanded) {
tree.expandPath(path);
} else {
tree.collapsePath(path);
}
}
private static class DisableRootCollapseListener implements TreeWillExpandListener {
private final DefaultMutableTreeNode treeRoot;
public DisableRootCollapseListener(DefaultMutableTreeNode treeRoot) {
this.treeRoot = treeRoot;
}
@Override
public void treeWillExpand(TreeExpansionEvent event) {
}
@Override
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
Object current = event.getPath().getLastPathComponent();
if (Objects.equals(current, treeRoot)) {
throw new ExpandVetoException(event, "Root collapsing not allowed");
}
}
}
}
| 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/settings/ui/font/FontChooserHack.java | jadx-gui/src/main/java/jadx/gui/settings/ui/font/FontChooserHack.java | package jadx.gui.settings.ui.font;
import java.lang.reflect.Field;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import org.drjekyll.fontchooser.FontChooser;
import org.drjekyll.fontchooser.panes.FamilyPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FontChooserHack {
private static final Logger LOG = LoggerFactory.getLogger(FontChooserHack.class);
public static void setOnlyMonospace(FontChooser fontChooser) {
try {
FamilyPane familyPane = (FamilyPane) getPrivateField(fontChooser, "familyPane");
JCheckBox monospacedCheckBox = (JCheckBox) getPrivateField(familyPane, "monospacedCheckBox");
monospacedCheckBox.setSelected(true);
monospacedCheckBox.setEnabled(false);
} catch (Throwable e) {
LOG.debug("Failed to set only monospace check box", e);
}
}
public static void hidePreview(FontChooser fontChooser) {
try {
JPanel previewPanel = (JPanel) getPrivateField(fontChooser, "previewPanel");
previewPanel.setVisible(false);
} catch (Throwable e) {
LOG.debug("Failed to hide preview panel", e);
}
}
private static Object getPrivateField(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(fieldName);
f.setAccessible(true);
return f.get(obj);
}
}
| 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/settings/ui/font/JadxFontDialog.java | jadx-gui/src/main/java/jadx/gui/settings/ui/font/JadxFontDialog.java | package jadx.gui.settings.ui.font;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import org.drjekyll.fontchooser.FontChooser;
import org.jetbrains.annotations.Nullable;
import jadx.gui.settings.JadxSettings;
import jadx.gui.utils.NLS;
public class JadxFontDialog extends JDialog {
private static final long serialVersionUID = 7609857698785777587L;
private final FontChooser fontChooser = new FontChooser();
private final JadxSettings settings;
private boolean selected = false;
public JadxFontDialog(Dialog parent, JadxSettings settings, String title) {
super(parent, title, true);
this.settings = settings;
initComponents();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
if (!settings.loadWindowPos(this)) {
pack();
}
}
public @Nullable Font select(Font currentFont, boolean onlyMonospace) {
fontChooser.setSelectedFont(currentFont);
if (onlyMonospace) {
FontChooserHack.setOnlyMonospace(fontChooser);
}
setVisible(true);
Font selectedFont = fontChooser.getSelectedFont();
if (selected && !selectedFont.equals(currentFont)) {
return selectedFont;
}
return null;
}
private void initComponents() {
JPanel chooserPanel = new JPanel();
chooserPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
chooserPanel.setLayout(new BorderLayout(0, 10));
chooserPanel.add(fontChooser);
JPanel controlPanel = new JPanel();
controlPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
controlPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));
JButton okBtn = new JButton();
okBtn.setText(NLS.str("common_dialog.ok"));
okBtn.setMnemonic('o');
okBtn.addActionListener(event -> {
selected = true;
dispose();
});
JButton cancelBtn = new JButton();
cancelBtn.setText(NLS.str("common_dialog.cancel"));
cancelBtn.setMnemonic('c');
cancelBtn.addActionListener(event -> dispose());
controlPanel.add(okBtn);
controlPanel.add(cancelBtn);
add(chooserPanel);
add(controlPanel, BorderLayout.PAGE_END);
getRootPane().setDefaultButton(okBtn);
}
@Override
public void dispose() {
settings.saveWindowPos(this);
super.dispose();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/ui/cache/CacheSettingsGroup.java | jadx-gui/src/main/java/jadx/gui/settings/ui/cache/CacheSettingsGroup.java | package jadx.gui.settings.ui.cache;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import org.jetbrains.annotations.Nullable;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.gui.cache.code.CodeCacheMode;
import jadx.gui.cache.usage.UsageCacheMode;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.ui.JadxSettingsWindow;
import jadx.gui.settings.ui.SettingsGroup;
import jadx.gui.ui.filedialog.FileDialogWrapper;
import jadx.gui.ui.filedialog.FileOpenMode;
import jadx.gui.utils.NLS;
import jadx.gui.utils.files.JadxFiles;
import jadx.gui.utils.ui.DocumentUpdateListener;
public class CacheSettingsGroup implements ISettingsGroup {
private final String title = NLS.str("preferences.cache");
private final JadxSettingsWindow settingsWindow;
private JTextField customDirField;
private JButton selectDirBtn;
public CacheSettingsGroup(JadxSettingsWindow settingsWindow) {
this.settingsWindow = settingsWindow;
}
@Override
public String getTitle() {
return title;
}
@Override
public JComponent buildComponent() {
JPanel options = new JPanel();
options.setLayout(new BoxLayout(options, BoxLayout.PAGE_AXIS));
options.add(buildBaseOptions());
options.add(buildLocationSelector());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(options, BorderLayout.PAGE_START);
mainPanel.add(buildCachesView(), BorderLayout.CENTER);
return mainPanel;
}
private JPanel buildCachesView() {
CachesTable cachesTable = new CachesTable(settingsWindow.getMainWindow());
JScrollPane scrollPane = new JScrollPane(cachesTable);
cachesTable.setFillsViewportHeight(true);
cachesTable.updateData();
JButton calcUsage = new JButton(NLS.str("preferences.cache.btn.usage"));
calcUsage.addActionListener(ev -> cachesTable.updateSizes());
JButton deleteSelected = new JButton(NLS.str("preferences.cache.btn.delete_selected"));
deleteSelected.addActionListener(ev -> cachesTable.deleteSelected());
JButton deleteAll = new JButton(NLS.str("preferences.cache.btn.delete_all"));
deleteAll.addActionListener(ev -> cachesTable.deleteAll());
JPanel buttons = new JPanel();
buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
buttons.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
buttons.add(calcUsage);
buttons.add(Box.createHorizontalGlue());
buttons.add(deleteSelected);
buttons.add(deleteAll);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder(NLS.str("preferences.cache.table.title")));
panel.add(scrollPane, BorderLayout.CENTER);
panel.add(buttons, BorderLayout.PAGE_END);
return panel;
}
private JComponent buildLocationSelector() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(NLS.str("preferences.cache.location")),
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
customDirField = new JTextField();
customDirField.setColumns(10);
customDirField.getDocument().addDocumentListener(new DocumentUpdateListener(ev -> {
settingsWindow.getMainWindow().getSettings().setCacheDir(customDirField.getText());
}));
selectDirBtn = new JButton();
selectDirBtn.setIcon(UIManager.getIcon("Tree.closedIcon"));
selectDirBtn.addActionListener(e -> {
FileDialogWrapper fd = new FileDialogWrapper(settingsWindow.getMainWindow(), FileOpenMode.CUSTOM_OPEN);
fd.setFileExtList(Collections.emptyList());
fd.setSelectionMode(JFileChooser.DIRECTORIES_ONLY);
List<Path> paths = fd.show();
if (!paths.isEmpty()) {
String dir = paths.get(0).toAbsolutePath().toString();
customDirField.setText(dir);
settingsWindow.getMainWindow().getSettings().setCacheDir(dir);
}
});
JRadioButton defOpt = new JRadioButton(NLS.str("preferences.cache.location_default"));
defOpt.setToolTipText(JadxFiles.CACHE_DIR.toString());
defOpt.addActionListener(e -> changeCacheLocation(null));
JRadioButton localOpt = new JRadioButton(NLS.str("preferences.cache.location_local"));
localOpt.addActionListener(e -> changeCacheLocation("."));
JRadioButton customOpt = new JRadioButton(NLS.str("preferences.cache.location_custom"));
customOpt.addActionListener(e -> changeCacheLocation(""));
ButtonGroup group = new ButtonGroup();
group.add(defOpt);
group.add(localOpt);
group.add(customOpt);
panel.add(defOpt);
panel.add(localOpt);
JPanel custom = new JPanel();
custom.setLayout(new BoxLayout(custom, BoxLayout.LINE_AXIS));
custom.add(customOpt);
custom.add(Box.createHorizontalStrut(15));
custom.add(customDirField);
custom.add(selectDirBtn);
panel.add(custom);
String cacheDir = settingsWindow.getMainWindow().getSettings().getCacheDir();
if (cacheDir == null) {
defOpt.setSelected(true);
changeCacheLocation(null);
} else if (cacheDir.equals(".")) {
localOpt.setSelected(true);
changeCacheLocation(cacheDir);
} else {
customOpt.setSelected(true);
customDirField.setText(cacheDir);
changeCacheLocation("");
}
JLabel notice = new JLabel(NLS.str("preferences.cache.change_notice"));
notice.setEnabled(false);
panel.add(notice);
return panel;
}
private void changeCacheLocation(@Nullable String locValue) {
boolean custom = Objects.equals(locValue, "");
customDirField.setEnabled(custom);
selectDirBtn.setEnabled(custom);
if (!custom) {
settingsWindow.getMainWindow().getSettings().setCacheDir(locValue);
}
}
private JComponent buildBaseOptions() {
JadxSettings settings = settingsWindow.getMainWindow().getSettings();
JComboBox<CodeCacheMode> codeCacheModeComboBox = new JComboBox<>(CodeCacheMode.values());
codeCacheModeComboBox.setSelectedItem(settings.getCodeCacheMode());
codeCacheModeComboBox.addActionListener(e -> {
settings.setCodeCacheMode((CodeCacheMode) codeCacheModeComboBox.getSelectedItem());
settingsWindow.needReload();
});
JComboBox<UsageCacheMode> usageCacheModeComboBox = new JComboBox<>(UsageCacheMode.values());
usageCacheModeComboBox.setSelectedItem(settings.getUsageCacheMode());
usageCacheModeComboBox.addActionListener(e -> {
settings.setUsageCacheMode((UsageCacheMode) usageCacheModeComboBox.getSelectedItem());
settingsWindow.needReload();
});
SettingsGroup group = new SettingsGroup(title);
group.addRow(NLS.str("preferences.codeCacheMode"), CodeCacheMode.buildToolTip(), codeCacheModeComboBox);
group.addRow(NLS.str("preferences.usageCacheMode"), usageCacheModeComboBox);
return group.buildComponent();
}
}
| 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/settings/ui/cache/CachesTableRenderer.java | jadx-gui/src/main/java/jadx/gui/settings/ui/cache/CachesTableRenderer.java | package jadx.gui.settings.ui.cache;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class CachesTableRenderer implements TableCellRenderer {
private final JLabel label;
public CachesTableRenderer() {
label = new JLabel();
label.setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
TableRow obj = (TableRow) value;
switch (column) {
case 0:
label.setText(obj.getProject());
break;
case 1:
label.setText(obj.getUsage());
break;
}
label.setToolTipText(obj.getCacheEntry().getCache());
if (obj.isSelected()) {
label.setBackground(table.getSelectionBackground());
label.setForeground(table.getSelectionForeground());
} else {
label.setBackground(table.getBackground());
label.setForeground(table.getForeground());
}
return label;
}
}
| 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/settings/ui/cache/TableRow.java | jadx-gui/src/main/java/jadx/gui/settings/ui/cache/TableRow.java | package jadx.gui.settings.ui.cache;
import java.nio.file.Paths;
import jadx.api.plugins.utils.CommonFileUtils;
import jadx.gui.cache.manager.CacheEntry;
final class TableRow {
private final CacheEntry cacheEntry;
private final String project;
private String usage;
private boolean selected = false;
public TableRow(CacheEntry cacheEntry) {
this.cacheEntry = cacheEntry;
this.project = cutProjectName(cacheEntry.getProject());
this.usage = "-";
}
private String cutProjectName(String project) {
if (project.startsWith("tmp:")) {
int hashStart = project.lastIndexOf('-');
int endIdx = hashStart != -1 ? hashStart : project.length();
return project.substring(4, endIdx) + " (Temp)";
}
return CommonFileUtils.removeFileExtension(Paths.get(project).getFileName().toString());
}
public CacheEntry getCacheEntry() {
return cacheEntry;
}
public String getProject() {
return project;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
| 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/settings/ui/cache/CachesTable.java | jadx-gui/src/main/java/jadx/gui/settings/ui/cache/CachesTable.java | package jadx.gui.settings.ui.cache;
import java.awt.Dimension;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.events.types.ReloadProject;
import jadx.core.utils.ListUtils;
import jadx.core.utils.Utils;
import jadx.gui.cache.manager.CacheManager;
import jadx.gui.settings.JadxProject;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.MousePressedHandler;
public class CachesTable extends JTable {
private static final long serialVersionUID = 5984107298264276049L;
private static final Logger LOG = LoggerFactory.getLogger(CachesTable.class);
private final MainWindow mainWindow;
private final CachesTableModel dataModel;
public CachesTable(MainWindow mainWindow) {
this.mainWindow = mainWindow;
this.dataModel = new CachesTableModel();
setModel(dataModel);
setDefaultRenderer(Object.class, new CachesTableRenderer());
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
setShowHorizontalLines(true);
setDragEnabled(false);
setColumnSelectionAllowed(false);
setAutoscrolls(true);
setFocusable(false);
addMouseListener(new MousePressedHandler(ev -> {
int row = rowAtPoint(ev.getPoint());
if (row != -1) {
dataModel.changeSelection(row);
UiUtils.uiRun(this::updateUI);
}
}));
}
public void updateData() {
List<TableRow> rows = mainWindow.getCacheManager().getCachesList().stream()
.map(TableRow::new)
.collect(Collectors.toList());
updateRows(rows);
}
public void reloadData() {
Map<String, String> prevUsageMap = dataModel.getRows().stream()
.collect(Collectors.toMap(TableRow::getProject, TableRow::getUsage));
List<TableRow> rows = mainWindow.getCacheManager().getCachesList().stream()
.map(TableRow::new)
.peek(r -> r.setUsage(Utils.getOrElse(prevUsageMap.get(r.getProject()), "-")))
.collect(Collectors.toList());
updateRows(rows);
}
private void updateRows(List<TableRow> rows) {
dataModel.setRows(rows);
// fix allocated space for default 20 rows
int width = getPreferredSize().width;
int height = rows.size() * getRowHeight();
setPreferredScrollableViewportSize(new Dimension(width, height));
UiUtils.uiRun(this::updateUI);
}
public void updateSizes() {
List<Runnable> list = dataModel.getRows().stream()
.map(row -> (Runnable) () -> calcSize(row))
.collect(Collectors.toList());
mainWindow.getBackgroundExecutor().execute(
NLS.str("preferences.cache.task.usage"),
list,
status -> updateUI());
}
private void calcSize(TableRow row) {
String cacheDir = row.getCacheEntry().getCache();
try {
Path dir = Paths.get(cacheDir);
if (Files.isDirectory(dir)) {
long size = calcSizeOfDirectory(dir);
row.setUsage(FileUtils.byteCountToDisplaySize(size));
} else {
row.setUsage("not found");
}
} catch (Exception e) {
LOG.warn("Failed to calculate size of directory: {}", cacheDir, e);
row.setUsage("error");
}
}
private static long calcSizeOfDirectory(Path dir) {
try (Stream<Path> stream = Files.walk(dir)) {
long blockSize = Files.getFileStore(dir).getBlockSize();
return stream.mapToLong(p -> {
if (Files.isRegularFile(p)) {
try {
long fileSize = Files.size(p);
// ceil round to blockSize
return (fileSize / blockSize + 1L) * blockSize;
} catch (Exception e) {
LOG.error("Failed to get file size: {}", p, e);
}
}
return 0;
}).sum();
} catch (Exception e) {
LOG.error("Failed to calculate directory size: {}", dir, e);
return 0;
}
}
public void deleteSelected() {
delete(ListUtils.filter(dataModel.getRows(), TableRow::isSelected));
}
public void deleteAll() {
delete(dataModel.getRows());
}
private void delete(List<TableRow> rows) {
// force reload if cache for current project is deleted
boolean reload = searchCurrentProject(rows);
List<Runnable> list = rows.stream()
.map(TableRow::getCacheEntry)
.map(entry -> (Runnable) () -> mainWindow.getCacheManager().removeCacheEntry(entry))
.collect(Collectors.toList());
mainWindow.getBackgroundExecutor().execute(
NLS.str("preferences.cache.task.delete"),
list,
status -> {
reloadData();
if (reload) {
mainWindow.events().send(ReloadProject.EVENT);
}
});
}
private boolean searchCurrentProject(List<TableRow> rows) {
JadxProject project = mainWindow.getProject();
if (!project.getFilePaths().isEmpty()) {
String cacheStr = CacheManager.pathToString(project.getCacheDir());
for (TableRow row : rows) {
if (row.getCacheEntry().getCache().equals(cacheStr)) {
project.resetCacheDir();
LOG.debug("Found current project in cache delete list -> request full reload");
return true;
}
}
}
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/settings/ui/cache/CachesTableModel.java | jadx-gui/src/main/java/jadx/gui/settings/ui/cache/CachesTableModel.java | package jadx.gui.settings.ui.cache;
import java.util.Collections;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import jadx.gui.utils.NLS;
public class CachesTableModel extends AbstractTableModel {
private static final long serialVersionUID = -7725573085995496397L;
private static final String[] COLUMN_NAMES = {
NLS.str("preferences.cache.table.project"),
NLS.str("preferences.cache.table.size")
};
private transient List<TableRow> rows = Collections.emptyList();
public void setRows(List<TableRow> list) {
this.rows = list;
}
public List<TableRow> getRows() {
return rows;
}
@Override
public int getRowCount() {
return rows.size();
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getColumnName(int index) {
return COLUMN_NAMES[index];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return TableRow.class;
}
@Override
public TableRow getValueAt(int rowIndex, int columnIndex) {
return rows.get(rowIndex);
}
public void changeSelection(int idx) {
TableRow row = rows.get(idx);
row.setSelected(!row.isSelected());
}
}
| 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/settings/ui/shortcut/ShortcutsSettingsGroup.java | jadx-gui/src/main/java/jadx/gui/settings/ui/shortcut/ShortcutsSettingsGroup.java | package jadx.gui.settings.ui.shortcut;
import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.ui.JadxSettingsWindow;
import jadx.gui.settings.ui.SettingsGroup;
import jadx.gui.ui.action.ActionCategory;
import jadx.gui.ui.action.ActionModel;
import jadx.gui.utils.NLS;
import jadx.gui.utils.shortcut.Shortcut;
public class ShortcutsSettingsGroup implements ISettingsGroup {
private final JadxSettingsWindow settingsWindow;
private final JadxSettings settings;
public ShortcutsSettingsGroup(JadxSettingsWindow settingsWindow, JadxSettings settings) {
this.settingsWindow = settingsWindow;
this.settings = settings;
}
@Override
public String getTitle() {
return NLS.str("preferences.shortcuts");
}
@Override
public JComponent buildComponent() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JLabel(NLS.str("preferences.select_shortcuts")), BorderLayout.NORTH);
return panel;
}
@Override
public List<ISettingsGroup> getSubGroups() {
return Arrays.stream(ActionCategory.values())
.map(this::makeShortcutsGroup)
.collect(Collectors.toUnmodifiableList());
}
private SettingsGroup makeShortcutsGroup(ActionCategory category) {
SettingsGroup group = new SettingsGroup(category.getName());
for (ActionModel actionModel : ActionModel.select(category)) {
Shortcut shortcut = settings.getShortcuts().get(actionModel);
ShortcutEdit edit = new ShortcutEdit(actionModel, settingsWindow, settings);
edit.setShortcut(shortcut);
group.addRow(actionModel.getName(), edit);
}
return group;
}
}
| 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/settings/ui/shortcut/ShortcutEdit.java | jadx-gui/src/main/java/jadx/gui/settings/ui/shortcut/ShortcutEdit.java | package jadx.gui.settings.ui.shortcut;
import java.awt.AWTEvent;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.ui.JadxSettingsWindow;
import jadx.gui.ui.action.ActionModel;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.shortcut.Shortcut;
public class ShortcutEdit extends JPanel {
private static final Icon CLEAR_ICON = UiUtils.openSvgIcon("ui/close");
private final ActionModel actionModel;
private final JadxSettingsWindow settingsWindow;
private final JadxSettings settings;
private final TextField textField;
public Shortcut shortcut;
public ShortcutEdit(ActionModel actionModel, JadxSettingsWindow settingsWindow, JadxSettings settings) {
this.actionModel = actionModel;
this.settings = settings;
this.settingsWindow = settingsWindow;
textField = new TextField();
JButton clearButton = new JButton(CLEAR_ICON);
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(textField);
add(clearButton);
clearButton.addActionListener(e -> {
setShortcut(Shortcut.none());
saveShortcut();
});
}
public void setShortcut(Shortcut shortcut) {
this.shortcut = shortcut;
textField.reload();
}
private void saveShortcut() {
settings.getShortcuts().put(actionModel, shortcut);
settingsWindow.needReload();
}
private boolean verifyShortcut(Shortcut shortcut) {
ActionModel otherAction = null;
for (ActionModel a : ActionModel.values()) {
if (actionModel != a && shortcut.equals(settings.getShortcuts().get(a))) {
otherAction = a;
break;
}
}
if (otherAction != null) {
int dialogResult = JOptionPane.showConfirmDialog(
this,
NLS.str("msg.duplicate_shortcut",
shortcut,
otherAction.getName(),
otherAction.getCategory().getName()),
NLS.str("msg.warning_title"),
JOptionPane.YES_NO_OPTION);
if (dialogResult != 0) {
return false;
}
}
return true;
}
private class TextField extends JTextField {
private Shortcut tempShortcut;
public TextField() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(ev -> {
if (!isListening()) {
return false;
}
if (ev.getID() == KeyEvent.KEY_PRESSED) {
Shortcut pressedShortcut = Shortcut.keyboard(ev.getKeyCode(), ev.getModifiersEx());
if (pressedShortcut.isValidKeyboard()) {
tempShortcut = pressedShortcut;
refresh(tempShortcut);
} else {
tempShortcut = null;
}
} else if (ev.getID() == KeyEvent.KEY_RELEASED) {
removeFocus();
}
ev.consume();
return true;
});
addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent ev) {
}
@Override
public void focusLost(FocusEvent ev) {
if (tempShortcut != null) {
if (verifyShortcut(tempShortcut)) {
shortcut = tempShortcut;
saveShortcut();
} else {
reload();
}
tempShortcut = null;
}
}
});
Toolkit.getDefaultToolkit().addAWTEventListener(event -> {
if (!isListening()) {
return;
}
if (event instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) event;
if (mouseEvent.getID() == MouseEvent.MOUSE_PRESSED) {
int mouseButton = mouseEvent.getButton();
if (mouseButton <= MouseEvent.BUTTON1) {
return;
}
if (mouseButton <= MouseEvent.BUTTON3) {
int dialogResult = JOptionPane.showConfirmDialog(
this,
NLS.str("msg.common_mouse_shortcut"),
NLS.str("msg.warning_title"),
JOptionPane.YES_NO_OPTION);
if (dialogResult != 0) {
((MouseEvent) event).consume();
tempShortcut = null;
removeFocus();
return;
}
}
((MouseEvent) event).consume();
tempShortcut = Shortcut.mouse(mouseButton);
refresh(tempShortcut);
removeFocus();
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
public void reload() {
refresh(shortcut);
}
private void refresh(Shortcut displayedShortcut) {
if (displayedShortcut == null || displayedShortcut.isNone()) {
setText("None");
setForeground(UIManager.getColor("TextArea.inactiveForeground"));
return;
}
setText(displayedShortcut.toString());
setForeground(UIManager.getColor("TextArea.foreground"));
}
private void removeFocus() {
// triggers focusLost
getRootPane().requestFocus();
}
private boolean isListening() {
return isFocusOwner();
}
}
}
| 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/settings/ui/plugins/TitleNode.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/TitleNode.java | package jadx.gui.settings.ui.plugins;
public class TitleNode extends BasePluginListNode {
private final String title;
public TitleNode(String title) {
this.title = title;
}
@Override
public String getTitle() {
return title;
}
@Override
public boolean hasDetails() {
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/settings/ui/plugins/PluginSettings.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/PluginSettings.java | package jadx.gui.settings.ui.plugins;
import java.awt.event.ItemEvent;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.IntSupplier;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import jadx.api.plugins.events.types.ReloadProject;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.api.plugins.gui.JadxGuiContext;
import jadx.api.plugins.options.JadxPluginOptions;
import jadx.api.plugins.options.OptionDescription;
import jadx.api.plugins.options.OptionFlag;
import jadx.api.plugins.options.OptionType;
import jadx.core.plugins.PluginContext;
import jadx.core.utils.Utils;
import jadx.gui.logs.LogOptions;
import jadx.gui.plugins.context.GuiPluginContext;
import jadx.gui.settings.JadxProject;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.ui.SettingsGroup;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.NLS;
import jadx.gui.utils.plugins.CloseablePlugins;
import jadx.gui.utils.plugins.CollectPlugins;
import jadx.gui.utils.plugins.SettingsGroupPluginWrap;
import jadx.gui.utils.ui.DocumentUpdateListener;
import jadx.plugins.tools.JadxPluginsTools;
import jadx.plugins.tools.data.JadxPluginMetadata;
import jadx.plugins.tools.data.JadxPluginUpdate;
public class PluginSettings {
private static final Logger LOG = LoggerFactory.getLogger(PluginSettings.class);
private final MainWindow mainWindow;
private final JadxSettings settings;
public PluginSettings(MainWindow mainWindow, JadxSettings settings) {
this.mainWindow = mainWindow;
this.settings = settings;
}
public ISettingsGroup build() {
CloseablePlugins collectedPlugins = new CollectPlugins(mainWindow).build();
ISettingsGroup pluginsGroup = new PluginSettingsGroup(this, mainWindow, collectedPlugins);
for (PluginContext context : collectedPlugins.getList()) {
ISettingsGroup pluginGroup = addPluginGroup(context);
if (pluginGroup != null) {
pluginsGroup.getSubGroups().add(new SettingsGroupPluginWrap(context.getPluginId(), pluginGroup));
}
}
return pluginsGroup;
}
public void addPlugin() {
new InstallPluginDialog(mainWindow, this).setVisible(true);
}
private void requestReload() {
mainWindow.events().send(ReloadProject.EVENT);
}
public void install(String locationId) {
mainWindow.getBackgroundExecutor().execute(NLS.str("preferences.plugins.task.installing"),
() -> {
try {
JadxPluginMetadata metadata = JadxPluginsTools.getInstance().install(locationId);
LOG.info("Plugin installed: {}", metadata);
requestReload();
} catch (Exception e) {
LOG.error("Plugin install failed", e);
mainWindow.showLogViewer(LogOptions.forLevel(Level.ERROR));
}
});
}
public void uninstall(String pluginId) {
mainWindow.getBackgroundExecutor().execute(NLS.str("preferences.plugins.task.uninstalling"), () -> {
boolean success = JadxPluginsTools.getInstance().uninstall(pluginId);
if (success) {
LOG.info("Uninstall complete");
requestReload();
} else {
LOG.warn("Uninstall failed");
}
});
}
public void changeDisableStatus(String pluginId, boolean disabled) {
mainWindow.getBackgroundExecutor().execute(
NLS.str("preferences.plugins.task.status"),
() -> JadxPluginsTools.getInstance().changeDisabledStatus(pluginId, disabled),
s -> requestReload());
}
void updateAll() {
mainWindow.getBackgroundExecutor().execute(NLS.str("preferences.plugins.task.updating"), () -> {
List<JadxPluginUpdate> updates = JadxPluginsTools.getInstance().updateAll();
if (!updates.isEmpty()) {
LOG.info("Updates: {}\n ", Utils.listToString(updates, "\n "));
requestReload();
} else {
LOG.info("No updates found");
}
});
}
private ISettingsGroup addPluginGroup(PluginContext context) {
JadxGuiContext guiContext = context.getGuiContext();
if (guiContext instanceof GuiPluginContext) {
GuiPluginContext pluginGuiContext = (GuiPluginContext) guiContext;
ISettingsGroup customSettingsGroup = pluginGuiContext.getCustomSettingsGroup();
if (customSettingsGroup != null) {
return customSettingsGroup;
}
}
JadxPluginOptions options = context.getOptions();
if (options == null) {
return null;
}
List<OptionDescription> optionsDescriptions = options.getOptionsDescriptions();
if (optionsDescriptions.isEmpty()) {
return null;
}
SettingsGroup settingsGroup = new SettingsGroup(context.getPluginInfo().getName());
addOptions(settingsGroup, optionsDescriptions);
return settingsGroup;
}
public void addOptions(SettingsGroup pluginGroup, List<OptionDescription> optionsDescriptions) {
for (OptionDescription opt : optionsDescriptions) {
if (opt.getFlags().contains(OptionFlag.HIDE_IN_GUI)) {
continue;
}
String optName = opt.name();
String title = opt.description();
Consumer<String> updateFunc;
String curValue;
if (opt.getFlags().contains(OptionFlag.PER_PROJECT)) {
JadxProject project = mainWindow.getProject();
updateFunc = value -> project.updatePluginOptions(m -> m.put(optName, value));
curValue = project.getPluginOption(optName);
} else {
Map<String, String> optionsMap = settings.getPluginOptions();
updateFunc = value -> optionsMap.put(optName, value);
curValue = optionsMap.get(optName);
}
String value = curValue != null ? curValue : opt.defaultValue();
JComponent editor = null;
if (opt.values().isEmpty() || opt.getType() == OptionType.BOOLEAN) {
try {
editor = getPluginOptionEditor(opt, value, updateFunc);
} catch (Exception e) {
LOG.error("Failed to add editor for plugin option: {}", optName, e);
}
} else {
JComboBox<String> combo = new JComboBox<>(opt.values().toArray(new String[0]));
combo.setSelectedItem(value);
combo.addActionListener(e -> updateFunc.accept((String) combo.getSelectedItem()));
editor = combo;
}
if (editor != null) {
JLabel label = pluginGroup.addRow(title, editor);
boolean enabled = !opt.getFlags().contains(OptionFlag.DISABLE_IN_GUI);
if (!enabled) {
label.setEnabled(false);
editor.setEnabled(false);
}
}
}
}
private JComponent getPluginOptionEditor(OptionDescription opt, String value, Consumer<String> updateFunc) {
switch (opt.getType()) {
case STRING:
JTextField textField = new JTextField();
textField.setText(value == null ? "" : value);
textField.getDocument().addDocumentListener(
new DocumentUpdateListener(event -> updateFunc.accept(textField.getText())));
return textField;
case NUMBER:
JSpinner numberField = new JSpinner();
numberField.setValue(safeStringToInt(value, () -> safeStringToInt(opt.defaultValue(), () -> {
throw new IllegalArgumentException("Failed to parse integer default value: " + opt.defaultValue());
})));
numberField.addChangeListener(e -> updateFunc.accept(numberField.getValue().toString()));
return numberField;
case BOOLEAN:
JCheckBox boolField = new JCheckBox();
boolField.setSelected(Objects.equals(value, "yes") || Objects.equals(value, "true"));
boolField.addItemListener(e -> {
boolean editorValue = e.getStateChange() == ItemEvent.SELECTED;
updateFunc.accept(editorValue ? "yes" : "no");
});
return boolField;
}
return null;
}
private static int safeStringToInt(String value, IntSupplier defValueSupplier) {
if (value == null) {
return defValueSupplier.getAsInt();
}
try {
return Integer.parseInt(value);
} catch (Exception e) {
LOG.warn("Failed parse string to int: {}", value, e);
return defValueSupplier.getAsInt();
}
}
}
| 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/settings/ui/plugins/BasePluginListNode.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/BasePluginListNode.java | package jadx.gui.settings.ui.plugins;
import org.jetbrains.annotations.Nullable;
abstract class BasePluginListNode {
public abstract String getTitle();
public abstract boolean hasDetails();
public String getPluginId() {
return null;
}
public String getDescription() {
return null;
}
public String getHomepage() {
return null;
}
public @Nullable String getLocationId() {
return null;
}
public @Nullable String getVersion() {
return null;
}
public boolean isDisabled() {
return false;
}
public PluginAction getAction() {
return PluginAction.NONE;
}
}
| 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/settings/ui/plugins/PluginAction.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/PluginAction.java | package jadx.gui.settings.ui.plugins;
public enum PluginAction {
NONE,
INSTALL,
UNINSTALL
}
| 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/settings/ui/plugins/AvailablePluginNode.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/AvailablePluginNode.java | package jadx.gui.settings.ui.plugins;
import jadx.plugins.tools.data.JadxPluginListEntry;
public class AvailablePluginNode extends BasePluginListNode {
private final JadxPluginListEntry metadata;
public AvailablePluginNode(JadxPluginListEntry metadata) {
this.metadata = metadata;
}
@Override
public String getTitle() {
return metadata.getName();
}
@Override
public boolean hasDetails() {
return true;
}
@Override
public String getPluginId() {
return metadata.getPluginId();
}
@Override
public String getDescription() {
return metadata.getDescription();
}
@Override
public String getHomepage() {
return metadata.getHomepage();
}
@Override
public String getLocationId() {
return metadata.getLocationId();
}
@Override
public PluginAction getAction() {
return PluginAction.INSTALL;
}
}
| 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/settings/ui/plugins/PluginSettingsGroup.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/PluginSettingsGroup.java | package jadx.gui.settings.ui.plugins;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.core.plugins.PluginContext;
import jadx.core.utils.StringUtils;
import jadx.core.utils.Utils;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.Link;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.plugins.CloseablePlugins;
import jadx.plugins.tools.JadxPluginsList;
import jadx.plugins.tools.JadxPluginsTools;
import jadx.plugins.tools.data.JadxPluginMetadata;
class PluginSettingsGroup implements ISettingsGroup {
private static final Logger LOG = LoggerFactory.getLogger(PluginSettingsGroup.class);
private final PluginSettings pluginsSettings;
private final MainWindow mainWindow;
private final String title;
private final List<ISettingsGroup> subGroups = new ArrayList<>();
private final CloseablePlugins collectedPlugins;
private JPanel detailsPanel;
public PluginSettingsGroup(PluginSettings pluginSettings, MainWindow mainWindow, CloseablePlugins collectedPlugins) {
this.pluginsSettings = pluginSettings;
this.mainWindow = mainWindow;
this.title = NLS.str("preferences.plugins");
this.collectedPlugins = collectedPlugins;
}
@Override
public String getTitle() {
return title;
}
@Override
public List<ISettingsGroup> getSubGroups() {
return subGroups;
}
@Override
public JComponent buildComponent() {
// lazy load main page
return buildMainSettingsPage();
}
@Override
public void close(boolean save) {
subGroups.forEach(subGroup -> subGroup.close(save));
collectedPlugins.close();
}
private JPanel buildMainSettingsPage() {
JButton installPluginBtn = new JButton(NLS.str("preferences.plugins.install"));
installPluginBtn.addActionListener(ev -> pluginsSettings.addPlugin());
JButton updateAllBtn = new JButton(NLS.str("preferences.plugins.update_all"));
updateAllBtn.addActionListener(ev -> pluginsSettings.updateAll());
JPanel actionsPanel = new JPanel();
actionsPanel.setLayout(new BoxLayout(actionsPanel, BoxLayout.LINE_AXIS));
actionsPanel.add(installPluginBtn);
actionsPanel.add(Box.createRigidArea(new Dimension(5, 0)));
actionsPanel.add(updateAllBtn);
DefaultListModel<BasePluginListNode> listModel = new DefaultListModel<>();
JList<BasePluginListNode> pluginList = new JList<>(listModel);
pluginList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
pluginList.setCellRenderer(new PluginsListCellRenderer());
pluginList.addListSelectionListener(ev -> onSelection(pluginList.getSelectedValue()));
pluginList.setFocusable(true);
JScrollPane scrollPane = new JScrollPane(pluginList);
scrollPane.setMinimumSize(new Dimension(80, 120));
detailsPanel = new JPanel(new BorderLayout(5, 5));
detailsPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(NLS.str("preferences.plugins.details")),
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
detailsPanel.setLayout(new BoxLayout(detailsPanel, BoxLayout.PAGE_AXIS));
JSplitPane splitPanel = new JSplitPane();
splitPanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 2, 2));
splitPanel.setLeftComponent(scrollPane);
splitPanel.setRightComponent(detailsPanel);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.setBorder(BorderFactory.createTitledBorder(title));
mainPanel.add(actionsPanel, BorderLayout.PAGE_START);
mainPanel.add(splitPanel, BorderLayout.CENTER);
applyData(listModel);
return mainPanel;
}
private void applyData(DefaultListModel<BasePluginListNode> listModel) {
List<JadxPluginMetadata> installed = JadxPluginsTools.getInstance().getInstalled();
List<BasePluginListNode> nodes = new ArrayList<>(installed.size() + collectedPlugins.getList().size());
Set<String> installedSet = new HashSet<>(installed.size());
for (JadxPluginMetadata pluginMetadata : installed) {
installedSet.add(pluginMetadata.getPluginId());
nodes.add(new InstalledPluginNode(pluginMetadata));
}
for (PluginContext plugin : collectedPlugins.getList()) {
if (!installedSet.contains(plugin.getPluginId())) {
nodes.add(new LoadedPluginNode(plugin));
}
}
nodes.sort(Comparator.comparing(BasePluginListNode::getTitle));
fillListModel(listModel, nodes, Collections.emptyList());
loadAvailablePlugins(listModel, nodes, installedSet);
}
private static void fillListModel(DefaultListModel<BasePluginListNode> listModel,
List<BasePluginListNode> nodes, List<AvailablePluginNode> available) {
listModel.clear();
listModel.addElement(new TitleNode("Installed"));
nodes.stream().filter(n -> n.getAction() == PluginAction.UNINSTALL).forEach(listModel::addElement);
listModel.addElement(new TitleNode("Available"));
listModel.addAll(available);
listModel.addElement(new TitleNode("Bundled"));
nodes.stream().filter(n -> n.getAction() == PluginAction.NONE).forEach(listModel::addElement);
}
private void loadAvailablePlugins(DefaultListModel<BasePluginListNode> listModel,
List<BasePluginListNode> nodes, Set<String> installedSet) {
mainWindow.getBackgroundExecutor().execute(
NLS.str("preferences.plugins.task.downloading_list"),
() -> {
try {
JadxPluginsList.getInstance().get(availablePlugins -> {
List<AvailablePluginNode> availableNodes = availablePlugins.stream()
.filter(availablePlugin -> !installedSet.contains(availablePlugin.getPluginId()))
.map(AvailablePluginNode::new)
.collect(Collectors.toList());
UiUtils.uiRunAndWait(() -> fillListModel(listModel, nodes, availableNodes));
});
} catch (Exception e) {
LOG.warn("Failed to load available plugins list", e);
}
});
}
private void onSelection(BasePluginListNode node) {
detailsPanel.removeAll();
if (node.hasDetails()) {
JLabel nameLbl = new JLabel(node.getTitle());
Font baseFont = nameLbl.getFont();
nameLbl.setFont(baseFont.deriveFont(Font.BOLD, baseFont.getSize2D() + 2));
JLabel homeLink = null;
String homepage = node.getHomepage();
if (StringUtils.notBlank(homepage)) {
homeLink = new Link("Homepage: " + homepage, homepage);
homeLink.setHorizontalAlignment(SwingConstants.LEFT);
}
JTextPane descArea = new JTextPane();
descArea.setText(node.getDescription());
descArea.setFont(baseFont.deriveFont(baseFont.getSize2D() + 1));
descArea.setEditable(false);
descArea.setBorder(BorderFactory.createEmptyBorder());
descArea.setOpaque(true);
JPanel top = new JPanel();
top.setLayout(new BoxLayout(top, BoxLayout.LINE_AXIS));
top.setBorder(BorderFactory.createEmptyBorder(10, 2, 10, 2));
top.add(nameLbl);
top.add(Box.createHorizontalGlue());
JButton actionBtn = makeActionButton(node);
if (actionBtn != null) {
top.add(actionBtn);
}
if (node.getAction() == PluginAction.UNINSTALL) {
// TODO: allow disable bundled plugins
boolean disabled = node.isDisabled();
String statusChangeLabel = disabled
? NLS.str("preferences.plugins.enable_btn")
: NLS.str("preferences.plugins.disable_btn");
JButton statusBtn = new JButton(statusChangeLabel);
statusBtn.addActionListener(ev -> pluginsSettings.changeDisableStatus(node.getPluginId(), !disabled));
top.add(Box.createHorizontalStrut(10));
top.add(statusBtn);
}
JPanel center = new JPanel();
center.setLayout(new BoxLayout(center, BoxLayout.PAGE_AXIS));
center.setBorder(BorderFactory.createEmptyBorder(10, 2, 10, 2));
center.add(descArea);
if (homeLink != null) {
JPanel link = new JPanel();
link.setLayout(new BoxLayout(link, BoxLayout.LINE_AXIS));
link.add(homeLink);
link.add(Box.createHorizontalGlue());
center.add(link);
}
center.add(Box.createVerticalGlue());
detailsPanel.add(top, BorderLayout.PAGE_START);
detailsPanel.add(center, BorderLayout.CENTER);
}
detailsPanel.updateUI();
}
private @Nullable JButton makeActionButton(BasePluginListNode node) {
switch (node.getAction()) {
case NONE:
return null;
case INSTALL: {
JButton installBtn = new JButton(NLS.str("preferences.plugins.install_btn"));
installBtn.addActionListener(ev -> pluginsSettings.install(node.getLocationId()));
return installBtn;
}
case UNINSTALL: {
JButton uninstallBtn = new JButton(NLS.str("preferences.plugins.uninstall_btn"));
uninstallBtn.addActionListener(ev -> pluginsSettings.uninstall(node.getPluginId()));
return uninstallBtn;
}
}
return null;
}
private static class PluginsListCellRenderer implements ListCellRenderer<BasePluginListNode> {
private final JPanel panel;
private final JLabel nameLbl;
private final JLabel versionLbl;
private final JLabel titleLbl;
public PluginsListCellRenderer() {
panel = new JPanel();
panel.setOpaque(true);
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 10));
nameLbl = new JLabel("");
nameLbl.setFont(nameLbl.getFont().deriveFont(Font.BOLD));
nameLbl.setOpaque(true);
versionLbl = new JLabel("");
versionLbl.setOpaque(true);
versionLbl.setPreferredSize(new Dimension(40, 10));
panel.add(nameLbl);
panel.add(Box.createHorizontalStrut(20));
panel.add(Box.createHorizontalGlue());
panel.add(versionLbl);
panel.add(Box.createHorizontalStrut(10));
titleLbl = new JLabel();
titleLbl.setHorizontalAlignment(SwingConstants.CENTER);
titleLbl.setPreferredSize(new Dimension(40, 10));
}
@Override
public Component getListCellRendererComponent(JList<? extends BasePluginListNode> list,
BasePluginListNode plugin, int index, boolean isSelected, boolean cellHasFocus) {
if (!plugin.hasDetails()) {
titleLbl.setText(plugin.getTitle());
return titleLbl;
}
nameLbl.setText(plugin.getTitle());
nameLbl.setToolTipText(plugin.getLocationId());
versionLbl.setText(Utils.getOrElse(plugin.getVersion(), ""));
panel.getAccessibleContext().setAccessibleName(plugin.getTitle());
boolean enabled = !plugin.isDisabled();
nameLbl.setEnabled(enabled);
versionLbl.setEnabled(enabled);
if (isSelected) {
panel.setBackground(list.getSelectionBackground());
nameLbl.setBackground(list.getSelectionBackground());
nameLbl.setForeground(list.getSelectionForeground());
versionLbl.setBackground(list.getSelectionBackground());
} else {
panel.setBackground(list.getBackground());
nameLbl.setBackground(list.getBackground());
nameLbl.setForeground(list.getForeground());
versionLbl.setBackground(list.getBackground());
}
return panel;
}
}
}
| 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/settings/ui/plugins/InstallPluginDialog.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/InstallPluginDialog.java | package jadx.gui.settings.ui.plugins;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.formdev.flatlaf.FlatClientProperties;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.filedialog.FileDialogWrapper;
import jadx.gui.ui.filedialog.FileOpenMode;
import jadx.gui.utils.NLS;
import jadx.gui.utils.TextStandardActions;
import jadx.gui.utils.UiUtils;
public class InstallPluginDialog extends JDialog {
private static final Logger LOG = LoggerFactory.getLogger(InstallPluginDialog.class);
private static final long serialVersionUID = 5304314264730563853L;
private final MainWindow mainWindow;
private final PluginSettings pluginsSettings;
private JTextField locationFld;
public InstallPluginDialog(MainWindow mainWindow, PluginSettings pluginsSettings) {
super(mainWindow, NLS.str("preferences.plugins.install"));
this.mainWindow = mainWindow;
this.pluginsSettings = pluginsSettings;
init();
}
private void init() {
locationFld = new JTextField();
locationFld.setAlignmentX(LEFT_ALIGNMENT);
locationFld.setColumns(50);
TextStandardActions.attach(locationFld);
locationFld.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true);
JLabel locationLbl = new JLabel(NLS.str("preferences.plugins.location_id_label"));
locationLbl.setLabelFor(locationFld);
JPanel locationPanel = new JPanel();
locationPanel.setLayout(new BoxLayout(locationPanel, BoxLayout.LINE_AXIS));
locationPanel.add(locationLbl);
locationPanel.add(Box.createRigidArea(new Dimension(5, 0)));
locationPanel.add(locationFld);
JButton fileBtn = new JButton(NLS.str("preferences.plugins.plugin_jar"));
fileBtn.addActionListener(ev -> openPluginJar());
JLabel fileLbl = new JLabel(NLS.str("preferences.plugins.plugin_jar_label"));
fileLbl.setLabelFor(fileBtn);
JPanel filePanel = new JPanel();
filePanel.setLayout(new BoxLayout(filePanel, BoxLayout.LINE_AXIS));
filePanel.add(fileLbl);
filePanel.add(Box.createRigidArea(new Dimension(5, 0)));
filePanel.add(fileBtn);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(locationPanel);
mainPanel.add(Box.createRigidArea(new Dimension(0, 5)));
mainPanel.add(filePanel);
JButton installBtn = new JButton(NLS.str("preferences.plugins.install_btn"));
installBtn.addActionListener(ev -> install());
JButton cancelBtn = new JButton(NLS.str("preferences.cancel"));
cancelBtn.addActionListener(ev -> dispose());
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
// TODO: add operation progress
buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(installBtn);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(cancelBtn);
getRootPane().setDefaultButton(installBtn);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BorderLayout(5, 5));
contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPanel.add(mainPanel, BorderLayout.PAGE_START);
contentPanel.add(buttonPane, BorderLayout.PAGE_END);
getContentPane().add(contentPanel);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
UiUtils.addEscapeShortCutToDispose(this);
}
private void openPluginJar() {
FileDialogWrapper fd = new FileDialogWrapper(mainWindow, FileOpenMode.CUSTOM_OPEN);
fd.setTitle(NLS.str("preferences.plugins.plugin_jar"));
fd.setFileExtList(Collections.singletonList("jar"));
fd.setSelectionMode(JFileChooser.FILES_ONLY);
List<Path> files = fd.show();
if (files.size() == 1) {
locationFld.setText("file:" + files.get(0).toAbsolutePath());
}
}
private void install() {
pluginsSettings.install(locationFld.getText());
dispose();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/LoadedPluginNode.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/LoadedPluginNode.java | package jadx.gui.settings.ui.plugins;
import org.jetbrains.annotations.Nullable;
import jadx.core.plugins.PluginContext;
public class LoadedPluginNode extends BasePluginListNode {
private final PluginContext plugin;
public LoadedPluginNode(PluginContext plugin) {
this.plugin = plugin;
}
@Override
public @Nullable String getTitle() {
return plugin.getPluginInfo().getName();
}
@Override
public boolean hasDetails() {
return true;
}
@Override
public String getPluginId() {
return plugin.getPluginId();
}
@Override
public String getDescription() {
return plugin.getPluginInfo().getDescription();
}
@Override
public String getHomepage() {
return plugin.getPluginInfo().getHomepage();
}
@Override
public String toString() {
return plugin.getPluginInfo().getName();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/InstalledPluginNode.java | jadx-gui/src/main/java/jadx/gui/settings/ui/plugins/InstalledPluginNode.java | package jadx.gui.settings.ui.plugins;
import org.jetbrains.annotations.Nullable;
import jadx.plugins.tools.data.JadxPluginMetadata;
public class InstalledPluginNode extends BasePluginListNode {
private final JadxPluginMetadata metadata;
public InstalledPluginNode(JadxPluginMetadata metadata) {
this.metadata = metadata;
}
@Override
public @Nullable String getTitle() {
return metadata.getName();
}
@Override
public boolean hasDetails() {
return true;
}
@Override
public String getPluginId() {
return metadata.getPluginId();
}
@Override
public String getDescription() {
return metadata.getDescription();
}
@Override
public String getHomepage() {
return metadata.getHomepage();
}
@Override
public PluginAction getAction() {
return PluginAction.UNINSTALL;
}
@Override
public @Nullable String getVersion() {
return metadata.getVersion();
}
@Override
public boolean isDisabled() {
return metadata.isDisabled();
}
@Override
public String toString() {
return metadata.getName();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/utils/JNodeCache.java | jadx-gui/src/main/java/jadx/gui/utils/JNodeCache.java | package jadx.gui.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import jadx.api.JavaClass;
import jadx.api.JavaField;
import jadx.api.JavaMethod;
import jadx.api.JavaNode;
import jadx.api.JavaPackage;
import jadx.api.JavaVariable;
import jadx.api.metadata.ICodeNodeRef;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.JadxWrapper;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JField;
import jadx.gui.treemodel.JMethod;
import jadx.gui.treemodel.JNode;
import jadx.gui.treemodel.JPackage;
import jadx.gui.treemodel.JVariable;
public class JNodeCache {
private final JadxWrapper wrapper;
private final Map<ICodeNodeRef, JNode> cache = new ConcurrentHashMap<>();
public JNodeCache(JadxWrapper wrapper) {
this.wrapper = wrapper;
}
public JNode makeFrom(ICodeNodeRef nodeRef) {
if (nodeRef == null) {
return null;
}
// don't use 'computeIfAbsent' method here, it will cause 'Recursive update' exception
JNode jNode = cache.get(nodeRef);
if (jNode == null || jNode.getJavaNode().getCodeNodeRef() != nodeRef) {
jNode = convert(nodeRef);
cache.put(nodeRef, jNode);
}
return jNode;
}
public void put(ICodeNodeRef nodeRef, JNode jNode) {
cache.put(nodeRef, jNode);
}
public void put(JavaNode javaNode, JNode jNode) {
cache.put(javaNode.getCodeNodeRef(), jNode);
}
public JNode makeFrom(JavaNode javaNode) {
if (javaNode == null) {
return null;
}
return makeFrom(javaNode.getCodeNodeRef());
}
public JClass makeFrom(JavaClass javaCls) {
if (javaCls == null) {
return null;
}
ICodeNodeRef nodeRef = javaCls.getCodeNodeRef();
JClass jCls = (JClass) cache.get(nodeRef);
if (jCls == null || jCls.getCls() != javaCls) {
jCls = convert(javaCls);
cache.put(nodeRef, jCls);
}
return jCls;
}
public JPackage newJPackage(JavaPackage javaPkg, boolean synthetic, boolean pkgEnabled, List<JClass> classes) {
JPackage jPackage = new JPackage(javaPkg, pkgEnabled, classes, new ArrayList<>(), synthetic);
put(javaPkg, jPackage);
return jPackage;
}
public void remove(JavaNode javaNode) {
cache.remove(javaNode.getCodeNodeRef());
}
public void removeWholeClass(JavaClass javaCls) {
remove(javaCls);
javaCls.getMethods().forEach(this::remove);
javaCls.getFields().forEach(this::remove);
javaCls.getInnerClasses().forEach(this::remove);
javaCls.getInlinedClasses().forEach(this::remove);
}
public void reset() {
cache.clear();
}
private JClass convert(JavaClass cls) {
JavaClass parentCls = cls.getDeclaringClass();
if (parentCls == cls) {
return new JClass(cls, null, this);
}
return new JClass(cls, makeFrom(parentCls), this);
}
private JNode convert(ICodeNodeRef nodeRef) {
JavaNode javaNode = wrapper.getDecompiler().getJavaNodeByRef(nodeRef);
return convert(javaNode);
}
private JNode convert(JavaNode node) {
if (node == null) {
return null;
}
if (node instanceof JavaClass) {
return convert((JavaClass) node);
}
if (node instanceof JavaMethod) {
return new JMethod((JavaMethod) node, makeFrom(node.getDeclaringClass()));
}
if (node instanceof JavaField) {
return new JField((JavaField) node, makeFrom(node.getDeclaringClass()));
}
if (node instanceof JavaVariable) {
JavaVariable javaVar = (JavaVariable) node;
JMethod jMth = (JMethod) makeFrom(javaVar.getMth());
return new JVariable(jMth, javaVar);
}
if (node instanceof JavaPackage) {
throw new JadxRuntimeException("Unexpected JPackage (missing from cache): " + node);
}
throw new JadxRuntimeException("Unknown type for JavaNode: " + node.getClass());
}
}
| 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/utils/CaretPositionFix.java | jadx-gui/src/main/java/jadx/gui/utils/CaretPositionFix.java | package jadx.gui.utils;
import java.util.Map;
import javax.swing.text.BadLocationException;
import org.fife.ui.rsyntaxtextarea.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.api.metadata.ICodeAnnotation;
import jadx.api.metadata.ICodeMetadata;
import jadx.api.metadata.ICodeNodeRef;
import jadx.api.metadata.annotations.InsnCodeOffset;
import jadx.gui.treemodel.JClass;
import jadx.gui.ui.codearea.AbstractCodeArea;
/**
* After class refresh (rename, comment, etc) the change of document is undetectable.
* So use Token index or offset in line to calculate the new caret position.
*/
public class CaretPositionFix {
private static final Logger LOG = LoggerFactory.getLogger(CaretPositionFix.class);
private final AbstractCodeArea codeArea;
private int linesCount;
private int line;
private int pos;
private int lineOffset;
private TokenInfo tokenInfo;
private int javaNodePos = -1;
private int codeRawOffset = -1;
public CaretPositionFix(AbstractCodeArea codeArea) {
this.codeArea = codeArea;
}
/**
* Save caret position by anchor to token under caret
*/
public void save() {
try {
linesCount = codeArea.getLineCount();
pos = codeArea.getCaretPosition();
line = codeArea.getLineOfOffset(pos);
lineOffset = pos - codeArea.getLineStartOffset(line);
tokenInfo = getTokenInfoByOffset(codeArea.getTokenListForLine(line), pos);
ICodeInfo codeInfo = codeArea.getCodeInfo();
if (codeInfo.hasMetadata()) {
ICodeMetadata metadata = codeInfo.getCodeMetadata();
ICodeAnnotation ann = metadata.getAt(pos);
if (ann instanceof InsnCodeOffset) {
codeRawOffset = ((InsnCodeOffset) ann).getOffset();
ICodeNodeRef javaNode = metadata.getNodeAt(pos);
if (javaNode != null) {
javaNodePos = javaNode.getDefPosition();
}
}
}
LOG.debug("Saved position data: line={}, lineOffset={}, token={}, codeRawOffset={}, javaNodeLine={}",
line, lineOffset, tokenInfo, codeRawOffset, javaNodePos);
} catch (Exception e) {
LOG.error("Failed to save caret position before refresh", e);
line = -1;
}
}
/**
* Restore caret position in refreshed code.
* Expected to be called in UI thread.
*/
public void restore() {
if (line == -1) {
return;
}
try {
int newPos = getNewPos();
int newLine = codeArea.getLineOfOffset(newPos);
Token token = codeArea.getTokenListForLine(newLine);
int tokenPos = getOffsetFromTokenInfo(tokenInfo, token);
if (tokenPos == -1) {
int lineStartOffset = codeArea.getLineStartOffset(newLine);
int lineEndOffset = codeArea.getLineEndOffset(newLine) - 1;
int lineLength = lineEndOffset - lineStartOffset;
// can't restore using token -> just restore by line offset
if (lineOffset < lineLength) {
tokenPos = lineStartOffset + lineOffset;
} else {
// line truncated -> set caret at line end
tokenPos = lineEndOffset;
}
}
codeArea.setCaretPosition(tokenPos);
LOG.debug("Restored caret position: {}", tokenPos);
} catch (Exception e) {
LOG.warn("Failed to restore caret position", e);
}
}
private int getNewPos() throws BadLocationException {
int newLinesCount = codeArea.getLineCount();
if (linesCount == newLinesCount) {
return pos;
}
// lines count changes, try find line by raw offset
ICodeInfo codeInfo = codeArea.getCodeInfo();
if (javaNodePos != -1 && codeInfo.hasMetadata()) {
JClass cls = codeArea.getJClass();
if (cls != null) {
ICodeMetadata codeMetadata = codeInfo.getCodeMetadata();
for (Map.Entry<Integer, ICodeAnnotation> entry : codeMetadata.getAsMap().entrySet()) {
int annPos = entry.getKey();
if (annPos >= javaNodePos) {
ICodeAnnotation ann = entry.getValue();
if (ann instanceof InsnCodeOffset
&& ((InsnCodeOffset) ann).getOffset() == codeRawOffset) {
return annPos;
}
}
}
}
}
// fallback: assume lines added/removed before caret
int newLine = line - (linesCount - newLinesCount);
return codeArea.getLineStartOffset(newLine);
}
private TokenInfo getTokenInfoByOffset(Token token, int offset) {
if (token == null) {
return null;
}
int index = 1;
while (token.getEndOffset() < offset) {
token = token.getNextToken();
if (token == null) {
return null;
}
index++;
}
return new TokenInfo(index, token.getType());
}
private int getOffsetFromTokenInfo(TokenInfo tokenInfo, Token token) {
if (tokenInfo == null || token == null) {
return -1;
}
int index = tokenInfo.getIndex();
if (index == -1) {
return -1;
}
for (int i = 0; i < index; i++) {
token = token.getNextToken();
if (token == null) {
return -1;
}
}
if (token.getType() != tokenInfo.getType()) {
return -1;
}
return token.getOffset();
}
private static final class TokenInfo {
private final int index;
private final int type;
public TokenInfo(int index, int type) {
this.index = index;
this.type = type;
}
public int getIndex() {
return index;
}
public int getType() {
return type;
}
@Override
public String toString() {
return "Token{index=" + index + ", type=" + type + '}';
}
}
}
| 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/utils/SimpleListener.java | jadx-gui/src/main/java/jadx/gui/utils/SimpleListener.java | package jadx.gui.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class SimpleListener<T> {
private final List<Consumer<T>> listeners = new ArrayList<>();
public void sendUpdate(T data) {
for (Consumer<T> listener : listeners) {
listener.accept(data);
}
}
public void addListener(Consumer<T> listener) {
listeners.add(listener);
}
public boolean removeListener(Consumer<T> listener) {
return listeners.remove(listener);
}
}
| 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/utils/ObjectPool.java | jadx-gui/src/main/java/jadx/gui/utils/ObjectPool.java | package jadx.gui.utils;
import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ObjectPool<T> {
private final ConcurrentLinkedQueue<WeakReference<T>> pool = new ConcurrentLinkedQueue<>();
private final Creator<T> creator;
public interface Creator<T> {
T create();
}
public ObjectPool(Creator<T> creator) {
this.creator = creator;
}
public T get() {
T node;
do {
WeakReference<T> wNode = pool.poll();
if (wNode == null) {
return creator.create();
}
node = wNode.get();
} while (node == null);
return node;
}
public void put(T node) {
pool.add(new WeakReference<>(node));
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/utils/CacheObject.java | jadx-gui/src/main/java/jadx/gui/utils/CacheObject.java | package jadx.gui.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.Nullable;
import jadx.gui.JadxWrapper;
import jadx.gui.ui.dialog.SearchDialog;
import jadx.gui.utils.pkgs.PackageHelper;
public class CacheObject {
private final JadxWrapper wrapper;
private final JNodeCache jNodeCache;
private final PackageHelper packageHelper;
private String lastSearch;
private Map<SearchDialog.SearchPreset, Set<SearchDialog.SearchOptions>> lastSearchOptions;
private String lastSearchPackage;
private int maxPkgLength;
private volatile boolean fullDecompilationFinished;
public CacheObject(JadxWrapper wrapper) {
this.wrapper = wrapper;
this.jNodeCache = new JNodeCache(wrapper);
this.packageHelper = new PackageHelper(wrapper, jNodeCache);
reset();
}
public void reset() {
lastSearch = null;
jNodeCache.reset();
lastSearchOptions = new HashMap<>();
lastSearchPackage = null;
fullDecompilationFinished = false;
}
@Nullable
public String getLastSearch() {
return lastSearch;
}
@Nullable
public String getLastSearchPackage() {
return lastSearchPackage;
}
public void setLastSearch(String lastSearch) {
this.lastSearch = lastSearch;
}
public void setLastSearchPackage(String lastSearchPackage) {
this.lastSearchPackage = lastSearchPackage;
}
public int getMaxPkgLength() {
return maxPkgLength;
}
public void setMaxPkgLength(int maxPkgLength) {
this.maxPkgLength = maxPkgLength;
}
public JNodeCache getNodeCache() {
return jNodeCache;
}
public Map<SearchDialog.SearchPreset, Set<SearchDialog.SearchOptions>> getLastSearchOptions() {
return lastSearchOptions;
}
public PackageHelper getPackageHelper() {
return packageHelper;
}
public boolean isFullDecompilationFinished() {
return fullDecompilationFinished;
}
public void setFullDecompilationFinished(boolean fullDecompilationFinished) {
this.fullDecompilationFinished = fullDecompilationFinished;
}
}
| 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/utils/Icons.java | jadx-gui/src/main/java/jadx/gui/utils/Icons.java | package jadx.gui.utils;
import javax.swing.ImageIcon;
import static jadx.gui.utils.UiUtils.openSvgIcon;
public class Icons {
public static final ImageIcon OPEN = openSvgIcon("ui/openDisk");
public static final ImageIcon OPEN_PROJECT = openSvgIcon("ui/projectDirectory");
public static final ImageIcon NEW_PROJECT = openSvgIcon("ui/newFolder");
public static final ImageIcon CLOSE = openSvgIcon("ui/closeHovered");
public static final ImageIcon CLOSE_INACTIVE = openSvgIcon("ui/close");
public static final ImageIcon SAVE_ALL = UiUtils.openSvgIcon("ui/menu-saveall");
public static final ImageIcon FLAT_PKG = UiUtils.openSvgIcon("ui/moduleGroup");
public static final ImageIcon QUICK_TABS = UiUtils.openSvgIcon("ui/dataView");
public static final ImageIcon PIN = UiUtils.openSvgIcon("nodes/pin");
public static final ImageIcon PIN_DARK = UiUtils.openSvgIcon("nodes/pin_dark");
public static final ImageIcon PIN_HOVERED = UiUtils.openSvgIcon("nodes/pinHovered");
public static final ImageIcon PIN_HOVERED_DARK = UiUtils.openSvgIcon("nodes/pinHovered_dark");
public static final ImageIcon BOOKMARK = UiUtils.openSvgIcon("nodes/bookmark");
public static final ImageIcon BOOKMARK_OVERLAY = UiUtils.openSvgIcon("nodes/bookmark_overlay");
public static final ImageIcon BOOKMARK_DARK = UiUtils.openSvgIcon("nodes/bookmark_dark");
public static final ImageIcon BOOKMARK_OVERLAY_DARK = UiUtils.openSvgIcon("nodes/bookmark_overlay_dark");
public static final ImageIcon STATIC = openSvgIcon("nodes/staticMark");
public static final ImageIcon FINAL = openSvgIcon("nodes/finalMark");
public static final ImageIcon START_PAGE = openSvgIcon("nodes/newWindow");
public static final ImageIcon FOLDER = UiUtils.openSvgIcon("nodes/folder");
public static final ImageIcon FILE = UiUtils.openSvgIcon("nodes/file_any_type");
public static final ImageIcon PACKAGE = UiUtils.openSvgIcon("nodes/package");
public static final ImageIcon CLASS = UiUtils.openSvgIcon("nodes/class");
public static final ImageIcon METHOD = UiUtils.openSvgIcon("nodes/method");
public static final ImageIcon FIELD = UiUtils.openSvgIcon("nodes/field");
public static final ImageIcon PROPERTY = UiUtils.openSvgIcon("nodes/property");
public static final ImageIcon PARAMETER = UiUtils.openSvgIcon("nodes/parameter");
public static final ImageIcon RUN = UiUtils.openSvgIcon("ui/run");
public static final ImageIcon CHECK = UiUtils.openSvgIcon("ui/checkConstraint");
public static final ImageIcon FORMAT = UiUtils.openSvgIcon("ui/toolWindowMessages");
public static final ImageIcon RESET = UiUtils.openSvgIcon("ui/reset");
public static final ImageIcon FONT = UiUtils.openSvgIcon("nodes/fontFile");
public static final ImageIcon ICON_MARK = UiUtils.openSvgIcon("search/mark");
public static final ImageIcon ICON_MARK_SELECTED = UiUtils.openSvgIcon("search/previewSelected");
public static final ImageIcon ICON_REGEX = UiUtils.openSvgIcon("search/regexHovered");
public static final ImageIcon ICON_REGEX_SELECTED = UiUtils.openSvgIcon("search/regexSelected");
public static final ImageIcon ICON_WORDS = UiUtils.openSvgIcon("search/wordsHovered");
public static final ImageIcon ICON_WORDS_SELECTED = UiUtils.openSvgIcon("search/wordsSelected");
public static final ImageIcon ICON_MATCH = UiUtils.openSvgIcon("search/matchCaseHovered");
public static final ImageIcon ICON_MATCH_SELECTED = UiUtils.openSvgIcon("search/matchCaseSelected");
public static final ImageIcon ICON_UP = UiUtils.openSvgIcon("ui/top");
public static final ImageIcon ICON_DOWN = UiUtils.openSvgIcon("ui/bottom");
public static final ImageIcon ICON_CLOSE = UiUtils.openSvgIcon("ui/close");
public static final ImageIcon ICON_FIND_TYPE_TXT = UiUtils.openSvgIcon("search/text");
public static final ImageIcon ICON_FIND_TYPE_HEX = UiUtils.openSvgIcon("search/hexSerial");
public static final ImageIcon ICON_ACTIVE_TAB = UiUtils.openSvgIcon("search/activeTab");
public static final ImageIcon ICON_ACTIVE_TAB_SELECTED = UiUtils.openSvgIcon("search/activeTabSelected");
}
| 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/utils/OverlayIcon.java | jadx-gui/src/main/java/jadx/gui/utils/OverlayIcon.java | package jadx.gui.utils;
import java.awt.Component;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.Icon;
public class OverlayIcon implements Icon {
private final Icon icon;
private final List<Icon> icons = new ArrayList<>(4);
private static final double A = 0.8;
private static final double B = 0.2;
private static final double[] OVERLAY_POS = new double[] { A, B, B, B, A, A, B, A };
public OverlayIcon(Icon icon) {
this.icon = icon;
}
public OverlayIcon(Icon icon, Icon... ovrIcons) {
this.icon = icon;
Collections.addAll(icons, ovrIcons);
}
@Override
public int getIconHeight() {
return icon.getIconHeight();
}
@Override
public int getIconWidth() {
return icon.getIconWidth();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
int w = getIconWidth();
int h = getIconHeight();
icon.paintIcon(c, g, x, y);
int k = 0;
for (Icon subIcon : icons) {
int dx = (int) (OVERLAY_POS[k++] * (w - subIcon.getIconWidth()));
int dy = (int) (OVERLAY_POS[k++] * (h - subIcon.getIconHeight()));
subIcon.paintIcon(c, g, x + dx, y + dy);
}
}
public void add(Icon icon) {
icons.add(icon);
}
public void remove(Icon icon) {
icons.remove(icon);
}
public void clear() {
icons.clear();
}
public List<Icon> getIcons() {
return icons;
}
}
| 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/utils/UiUtils.java | jadx-gui/src/main/java/jadx/gui/utils/UiUtils.java | package jadx.gui.utils;
import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.TestOnly;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.formdev.flatlaf.extras.FlatSVGIcon;
import jadx.commons.app.JadxCommonEnv;
import jadx.commons.app.JadxSystemInfo;
import jadx.core.dex.info.AccessInfo;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.utils.StringUtils;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.jobs.ITaskProgress;
import jadx.gui.ui.codearea.AbstractCodeArea;
public class UiUtils {
private static final Logger LOG = LoggerFactory.getLogger(UiUtils.class);
public static final boolean JADX_GUI_DEBUG = JadxCommonEnv.getBool("JADX_GUI_DEBUG", false);
/**
* The minimum about of memory in bytes we are trying to keep free, otherwise the application may
* run out of heap
* which ends up in a Java garbage collector running "amok" (CPU utilization 100% for each core and
* the UI is
* not responsive).
* <p>
* We can calculate and store this value here as the maximum heap is fixed for each JVM instance
* and can't be changed at runtime.
*/
public static final long MIN_FREE_MEMORY = calculateMinFreeMemory();
public static final Runnable EMPTY_RUNNABLE = new Runnable() {
@Override
public void run() {
}
@Override
public String toString() {
return "EMPTY_RUNNABLE";
}
};
private static final ExecutorService BACKGROUND_THREAD = Executors.newSingleThreadExecutor(Utils.simpleThreadFactory("utils-bg"));
private UiUtils() {
}
public static FlatSVGIcon openSvgIcon(String name) {
String iconPath = "icons/" + name + ".svg";
FlatSVGIcon icon = new FlatSVGIcon(iconPath);
boolean found;
try {
found = icon.hasFound();
} catch (Exception e) {
throw new JadxRuntimeException("Failed to load icon: " + iconPath, e);
}
if (!found) {
throw new JadxRuntimeException("Icon not found: " + iconPath);
}
return icon;
}
public static ImageIcon openIcon(String name) {
String iconPath = "/icons-16/" + name + ".png";
URL resource = UiUtils.class.getResource(iconPath);
if (resource == null) {
throw new JadxRuntimeException("Icon not found: " + iconPath);
}
return new ImageIcon(resource);
}
public static Image openImage(String path) {
URL resource = UiUtils.class.getResource(path);
if (resource == null) {
throw new JadxRuntimeException("Image not found: " + path);
}
return Toolkit.getDefaultToolkit().createImage(resource);
}
public static void addKeyBinding(JComponent comp, KeyStroke key, String id, Runnable action) {
addKeyBinding(comp, key, id, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
action.run();
}
});
}
public static void addKeyBinding(JComponent comp, KeyStroke key, String id, Action action) {
comp.getInputMap().put(key, id);
comp.getActionMap().put(id, action);
}
public static void removeKeyBinding(JComponent comp, KeyStroke key, String id) {
comp.getInputMap().remove(key);
comp.getActionMap().remove(id);
}
public static String typeFormat(String name, ArgType type) {
return name + " " + typeStr(type);
}
public static String typeFormatHtml(String name, ArgType type) {
return wrapHtml(escapeHtml(name) + ' ' + fadeHtml(escapeHtml(typeStr(type))));
}
public static String fadeHtml(String htmlStr) {
return "<span style='color:#888888;'>" + htmlStr + "</span>"; // TODO: get color from theme
}
public static String wrapHtml(String htmlStr) {
return "<html><body><nobr>" + htmlStr + "</nobr></body></html>";
}
public static String escapeHtml(String str) {
return str.replace("<", "<").replace(">", ">");
}
public static String typeStr(ArgType type) {
if (type == null) {
return "null";
}
if (type.isObject()) {
if (type.isGenericType()) {
return type.getObject();
}
ArgType wt = type.getWildcardType();
if (wt != null) {
ArgType.WildcardBound bound = type.getWildcardBound();
if (bound == ArgType.WildcardBound.UNBOUND) {
return bound.getStr();
}
return bound.getStr() + typeStr(wt);
}
String objName = objectShortName(type.getObject());
ArgType outerType = type.getOuterType();
if (outerType != null) {
return typeStr(outerType) + '.' + objName;
}
List<ArgType> genericTypes = type.getGenericTypes();
if (genericTypes != null) {
String generics = Utils.listToString(genericTypes, ", ", UiUtils::typeStr);
return objName + '<' + generics + '>';
}
return objName;
}
if (type.isArray()) {
return typeStr(type.getArrayElement()) + "[]";
}
return type.toString();
}
private static String objectShortName(String obj) {
int dot = obj.lastIndexOf('.');
if (dot != -1) {
return obj.substring(dot + 1);
}
return obj;
}
public static OverlayIcon makeIcon(AccessInfo af, Icon pub, Icon pri, Icon pro, Icon def) {
Icon icon;
if (af.isPublic()) {
icon = pub;
} else if (af.isPrivate()) {
icon = pri;
} else if (af.isProtected()) {
icon = pro;
} else {
icon = def;
}
OverlayIcon overIcon = new OverlayIcon(icon);
if (af.isFinal()) {
overIcon.add(Icons.FINAL);
}
if (af.isStatic()) {
overIcon.add(Icons.STATIC);
}
return overIcon;
}
/**
* @return 20% of the maximum heap size limited to 512 MB (bytes)
*/
public static long calculateMinFreeMemory() {
Runtime runtime = Runtime.getRuntime();
long minFree = (long) (runtime.maxMemory() * 0.2);
return Math.min(minFree, 512 * 1024L * 1024L);
}
public static boolean isFreeMemoryAvailable() {
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long totalFree = runtime.freeMemory() + (maxMemory - runtime.totalMemory());
return totalFree > MIN_FREE_MEMORY;
}
public static String memoryInfo() {
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
return "heap: " + format(allocatedMemory - freeMemory)
+ ", allocated: " + format(allocatedMemory)
+ ", free: " + format(freeMemory)
+ ", total free: " + format(freeMemory + maxMemory - allocatedMemory)
+ ", max: " + format(maxMemory);
}
private static String format(long mem) {
return (long) (mem / (double) (1024L * 1024L)) + "MB";
}
public static void setClipboardString(String text) {
try {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = new StringSelection(text);
clipboard.setContents(transferable, null);
LOG.debug("String '{}' copied to clipboard", text);
} catch (Exception e) {
LOG.error("Failed copy string '{}' to clipboard", text, e);
}
}
public static void setWindowIcons(Window window) {
List<Image> icons = new ArrayList<>();
icons.add(UiUtils.openImage("/logos/jadx-logo-16px.png"));
icons.add(UiUtils.openImage("/logos/jadx-logo-32px.png"));
icons.add(UiUtils.openImage("/logos/jadx-logo-48px.png"));
icons.add(UiUtils.openImage("/logos/jadx-logo.png"));
window.setIconImages(icons);
}
public static final int CTRL_BNT_KEY = getCtrlButton();
@SuppressWarnings("deprecation")
@MagicConstant(flagsFromClass = InputEvent.class)
private static int getCtrlButton() {
if (JadxSystemInfo.IS_MAC) {
return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
} else {
return InputEvent.CTRL_DOWN_MASK;
}
}
@MagicConstant(flagsFromClass = InputEvent.class)
public static int ctrlButton() {
return CTRL_BNT_KEY;
}
public static boolean isCtrlDown(KeyEvent keyEvent) {
return keyEvent.getModifiersEx() == CTRL_BNT_KEY;
}
public static <T extends Window & RootPaneContainer> void addEscapeShortCutToDispose(T window) {
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
window.getRootPane().registerKeyboardAction(e -> window.dispose(), stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
}
/**
* Get closest offset at mouse position
*
* @return -1 on error
*/
@SuppressWarnings("deprecation")
public static int getOffsetAtMousePosition(AbstractCodeArea codeArea) {
try {
Point mousePos = getMousePosition(codeArea);
return codeArea.viewToModel(mousePos);
} catch (Exception e) {
LOG.error("Failed to get offset at mouse position", e);
return -1;
}
}
public static Point getMousePosition(Component comp) {
Point pos = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(pos, comp);
return pos;
}
public static TreeNode getTreeNodeUnderMouse(JTree tree, MouseEvent mouseEvent) {
TreePath path = tree.getClosestPathForLocation(mouseEvent.getX(), mouseEvent.getY());
if (path == null) {
return null;
}
// allow 'closest' path only at the right of the item row
Rectangle pathBounds = tree.getPathBounds(path);
if (pathBounds != null) {
int y = mouseEvent.getY();
if (y < pathBounds.y || y > (pathBounds.y + pathBounds.height)) {
return null;
}
if (mouseEvent.getX() < pathBounds.x) {
// exclude expand/collapse events
return null;
}
}
Object obj = path.getLastPathComponent();
if (obj instanceof TreeNode) {
tree.setSelectionPath(path);
return (TreeNode) obj;
}
return null;
}
public static void showMessageBox(Component parent, String msg) {
JOptionPane.showMessageDialog(parent, msg);
}
public static void errorMessage(Component parent, String message) {
LOG.error(message);
JOptionPane.showMessageDialog(parent, message,
NLS.str("message.errorTitle"), JOptionPane.ERROR_MESSAGE);
}
public static void copyToClipboard(String text) {
if (StringUtils.isEmpty(text)) {
return;
}
try {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(text);
clipboard.setContents(selection, selection);
} catch (Exception e) {
LOG.error("Failed copy text to clipboard", e);
}
}
/**
* Owner field in Clipboard class can store reference to CodeArea.
* This prevents from garbage collection whole jadx object tree and cause memory leak.
* Trying to lost ownership by new empty selection.
*/
public static void resetClipboardOwner() {
try {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemSelection();
if (clipboard != null) {
StringSelection selection = new StringSelection("");
clipboard.setContents(selection, selection);
}
} catch (Exception e) {
LOG.error("Failed to reset clipboard owner", e);
}
}
public static int calcProgress(ITaskProgress taskProgress) {
return calcProgress(taskProgress.progress(), taskProgress.total());
}
public static int calcProgress(long done, long total) {
if (done > total) {
LOG.debug("Task progress has invalid values: done={}, total={}", done, total);
return 100;
}
return Math.round(done * 100 / (float) total);
}
public static void sleep(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
// ignore
}
}
public static void uiRun(Runnable runnable) {
SwingUtilities.invokeLater(runnable);
}
public static void uiRunAndWait(Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
return;
}
try {
SwingUtilities.invokeAndWait(runnable);
} catch (InterruptedException e) {
LOG.warn("UI thread interrupted, runnable: {}", runnable, e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Run task in background thread.
* Uses single thread, so all tasks are ordered.
*/
public static void bgRun(Runnable runnable) {
BACKGROUND_THREAD.execute(runnable);
}
public static void uiThreadGuard() {
if (JADX_GUI_DEBUG && !SwingUtilities.isEventDispatchThread()) {
LOG.warn("Expect UI thread, got: {}", Thread.currentThread(), new JadxRuntimeException());
}
}
public static void notUiThreadGuard() {
if (JADX_GUI_DEBUG && SwingUtilities.isEventDispatchThread()) {
LOG.warn("Expect background thread, got: {}", Thread.currentThread(), new JadxRuntimeException());
}
}
@TestOnly
public static void debugTimer(int periodInSeconds, Runnable action) {
if (!LOG.isDebugEnabled()) {
return;
}
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
action.run();
}
}, 0, periodInSeconds * 1000L);
}
@TestOnly
public static void printStackTrace(String label) {
LOG.debug("StackTrace: {}", label, new Exception(label));
}
public static boolean isDarkTheme(Color background) {
double brightness = (background.getRed() * 0.299
+ background.getGreen() * 0.587
+ background.getBlue() * 0.114) / 255;
return brightness < 0.5;
}
/**
* Adjusts the brightness of a given {@code Color} object without altering its hue or saturation.
*
* <p>
* This method converts the input RGB color to the HSB (Hue, Saturation, Brightness) color model,
* multiplies its brightness component by the specified {@code factor}, and then converts it back
* to a new RGB {@code Color} object.
* </p>
*
* <p>
* The new brightness value is capped at {@code 1.0f} (maximum HSB brightness) to prevent
* colors from becoming invalid or exceeding full brightness.
* </p>
*
* How to use:
* <ul>
* <li>To make a color **brighter**: Use a {@code factor} greater than {@code 1.0f} (e.g.,
* {@code 1.2f}, {@code 1.5f}).</li>
* <li>To make a color **darker**: Use a {@code factor} less than {@code 1.0f} (e.g., {@code 0.8f},
* {@code 0.5f}).</li>
* <li>To keep the brightness **unchanged**: Use a {@code factor} of {@code 1.0f}.</li>
* </ul>
*
* <pre>{@code
* // Example usage:
* Color originalColor = Color.BLUE;
*
* // Make the blue color 50% brighter (factor 1.5)
* Color brighterBlue = adjustBrightness(originalColor, 1.5f);
*
* // Make the blue color 30% darker (factor 0.7)
* Color darkerBlue = adjustBrightness(originalColor, 0.7f);
*
* // Get the brightest possible version of the color (will cap at 1.0 brightness)
* Color maxBrightnessBlue = adjustBrightness(originalColor, 10.0f);
*
* // Get a very dark, almost black version
* Color veryDarkBlue = adjustBrightness(originalColor, 0.1f);
* }</pre>
*
* @param color The original {@code Color} object whose brightness needs to be adjusted.
* @param factor The multiplier for the brightness.
* @return A new {@code Color} object with the adjusted brightness.
* @see java.awt.Color#RGBtoHSB(int, int, int, float[])
* @see java.awt.Color#getHSBColor(float, float, float)
*/
public static Color adjustBrightness(Color color, float factor) {
float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
hsb[2] = Math.min(1.0f, hsb[2] * factor); // Adjust brightness
return Color.getHSBColor(hsb[0], hsb[1], hsb[2]);
}
public static void highlightAsErrorField(final JTextField field, boolean isError) {
if (isError) {
field.putClientProperty("JComponent.outline", "error");
} else {
field.putClientProperty("JComponent.outline", "");
}
field.repaint();
}
public static boolean nearlyEqual(float a, float b) {
return Math.abs(a - b) < 1E-6f;
}
}
| 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/utils/ILoadListener.java | jadx-gui/src/main/java/jadx/gui/utils/ILoadListener.java | package jadx.gui.utils;
public interface ILoadListener {
/**
* Update files/project loaded state
*
* @return true to remove listener
*/
boolean update(boolean loaded);
}
| 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/utils/FontUtils.java | jadx-gui/src/main/java/jadx/gui/utils/FontUtils.java | package jadx.gui.utils;
import java.awt.Font;
import java.io.InputStream;
import javax.swing.text.StyleContext;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class FontUtils {
private static final Logger LOG = LoggerFactory.getLogger(FontUtils.class);
public static Font loadByStr(String fontDesc) {
String[] parts = fontDesc.split("/");
if (parts.length != 3) {
throw new JadxRuntimeException("Unsupported font description format: " + fontDesc);
}
String family = parts[0];
int style = parseFontStyle(parts[1]);
int size = Integer.parseInt(parts[2]);
StyleContext sc = StyleContext.getDefaultStyleContext();
Font font = sc.getFont(family, style, size);
if (font == null) {
throw new JadxRuntimeException("Font not found: " + fontDesc);
}
return font;
}
public static String convertToStr(@Nullable Font font) {
if (font == null) {
return "";
}
if (font.getSize() < 1) {
throw new JadxRuntimeException("Bad font size: " + font.getSize());
}
return font.getFamily()
+ '/' + convertFontStyleToString(font.getStyle())
+ '/' + font.getSize();
}
public static String convertFontStyleToString(int style) {
if (style == 0) {
return "plain";
}
StringBuilder sb = new StringBuilder();
if ((style & Font.BOLD) != 0) {
sb.append("bold");
}
if ((style & Font.ITALIC) != 0) {
sb.append(" italic");
}
return sb.toString().trim();
}
private static int parseFontStyle(String str) {
int style = 0;
if (str.contains("bold")) {
style |= Font.BOLD;
}
if (str.contains("italic")) {
style |= Font.ITALIC;
}
return style;
}
@Nullable
public static Font openFontTTF(String name) {
String fontPath = "/fonts/" + name + ".ttf";
try (InputStream is = UiUtils.class.getResourceAsStream(fontPath)) {
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
return font.deriveFont(12f);
} catch (Exception e) {
LOG.error("Failed load font by path: {}", fontPath, e);
return null;
}
}
public static boolean canStringBeDisplayed(String str, Font font) {
if (str == null || str.isEmpty()) {
return true;
}
int offset = 0;
while (offset < str.length()) {
int codePoint = str.codePointAt(offset);
if (!font.canDisplay(codePoint)) {
return false;
}
offset += Character.charCount(codePoint);
}
return true;
}
private FontUtils() {
}
}
| 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/utils/IOUtils.java | jadx-gui/src/main/java/jadx/gui/utils/IOUtils.java | package jadx.gui.utils;
import java.io.IOException;
import java.io.InputStream;
import org.jetbrains.annotations.Nullable;
public class IOUtils {
/**
* This method can be deleted once Jadx is Java11+
*/
@Nullable
public static byte[] readNBytes(InputStream inputStream, int len) throws IOException {
byte[] payload = new byte[len];
int readSize = 0;
while (true) {
int read = inputStream.read(payload, readSize, len - readSize);
if (read == -1) {
return null;
}
readSize += read;
if (readSize == len) {
return payload;
}
}
}
public static int read(InputStream inputStream, byte[] buf) throws IOException {
return read(inputStream, buf, 0, buf.length);
}
public static int read(InputStream inputStream, byte[] buf, int off, int len) throws IOException {
int remainingBytes = len;
while (remainingBytes > 0) {
int start = len - remainingBytes;
int bytesRead = inputStream.read(buf, off + start, remainingBytes);
if (bytesRead == -1) {
break;
}
remainingBytes -= bytesRead;
}
return len - remainingBytes;
}
}
| 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/utils/DefaultPopupMenuListener.java | jadx-gui/src/main/java/jadx/gui/utils/DefaultPopupMenuListener.java | package jadx.gui.utils;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public interface DefaultPopupMenuListener extends PopupMenuListener {
@Override
default void popupMenuWillBecomeVisible(PopupMenuEvent e) {
}
@Override
default void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
default void popupMenuCanceled(PopupMenuEvent 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/utils/LangLocale.java | jadx-gui/src/main/java/jadx/gui/utils/LangLocale.java | package jadx.gui.utils;
import java.util.Locale;
public class LangLocale {
private Locale locale;
// Don't remove. Used in json serialization
public LangLocale() {
}
public LangLocale(Locale locale) {
this.locale = locale;
}
public LangLocale(String l, String c) {
this.locale = new Locale(l, c);
}
public Locale get() {
return locale;
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
@Override
public String toString() {
return NLS.str("language.name", this);
}
@Override
public boolean equals(Object obj) {
return obj instanceof LangLocale && locale.equals(((LangLocale) obj).get());
}
@Override
public int hashCode() {
return locale.hashCode();
}
}
| 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/utils/Link.java | jadx-gui/src/main/java/jadx/gui/utils/Link.java | package jadx.gui.utils;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.commons.app.JadxSystemInfo;
import static java.awt.Desktop.Action;
public class Link extends JLabel {
private static final long serialVersionUID = 3655322136444908178L;
private static final Logger LOG = LoggerFactory.getLogger(Link.class);
private String url;
public Link() {
super();
init();
}
public Link(String text, String url) {
super(text);
init();
setUrl(url);
}
private void init() {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
browse();
}
});
}
public void setUrl(String url) {
this.url = url;
setToolTipText("Open " + url + " in your browser");
}
private void browse() {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Action.BROWSE)) {
try {
desktop.browse(new java.net.URI(url));
return;
} catch (Exception e) {
LOG.debug("Open url error", e);
}
}
}
try {
if (JadxSystemInfo.IS_WINDOWS) {
new ProcessBuilder()
.command(new String[] { "rundll32", "url.dll,FileProtocolHandler", url })
.start();
return;
}
if (JadxSystemInfo.IS_MAC) {
new ProcessBuilder()
.command(new String[] { "open", url })
.start();
return;
}
Map<String, String> env = System.getenv();
if (env.get("BROWSER") != null) {
new ProcessBuilder()
.command(new String[] { env.get("BROWSER"), url })
.start();
return;
}
} catch (Exception e) {
LOG.debug("Open url error", e);
}
showUrlDialog();
}
private void showUrlDialog() {
JTextArea urlArea = new JTextArea("Can't open browser. Please browse to:\n" + url);
JOptionPane.showMessageDialog(null, urlArea);
}
}
| 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/utils/RectangleTypeAdapter.java | jadx-gui/src/main/java/jadx/gui/utils/RectangleTypeAdapter.java | package jadx.gui.utils;
import java.awt.Rectangle;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class RectangleTypeAdapter {
private static final TypeAdapter<Rectangle> SINGLETON = new TypeAdapter<>() {
@Override
public void write(JsonWriter out, Rectangle value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.beginObject();
out.name("x").value(value.getX());
out.name("y").value(value.getY());
out.name("width").value(value.getWidth());
out.name("height").value(value.getHeight());
out.endObject();
}
}
@Override
public Rectangle read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
in.beginObject();
Rectangle rectangle = new Rectangle();
while (in.hasNext()) {
String name = in.nextName();
switch (name) {
case "x":
rectangle.x = in.nextInt();
break;
case "y":
rectangle.y = in.nextInt();
break;
case "width":
rectangle.width = in.nextInt();
break;
case "height":
rectangle.height = in.nextInt();
break;
default:
throw new IllegalArgumentException("Unknown field in Rectangle: " + name);
}
}
in.endObject();
return rectangle;
}
};
public static TypeAdapter<Rectangle> singleton() {
return SINGLETON;
}
private RectangleTypeAdapter() {
}
}
| 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/utils/JumpPosition.java | jadx-gui/src/main/java/jadx/gui/utils/JumpPosition.java | package jadx.gui.utils;
import jadx.core.utils.Utils;
import jadx.gui.treemodel.JNode;
public class JumpPosition {
private final JNode node;
private int pos;
public JumpPosition(JNode node) {
this(node, node.getPos());
}
public JumpPosition(JNode node, int pos) {
this.node = Utils.getOrElse(node.getRootClass(), node);
this.pos = pos;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public JNode getNode() {
return node;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof JumpPosition)) {
return false;
}
JumpPosition jump = (JumpPosition) obj;
return pos == jump.pos && node.equals(jump.node);
}
@Override
public int hashCode() {
return 31 * node.hashCode() + pos;
}
@Override
public String toString() {
return "Jump{" + node + ":" + pos + '}';
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/utils/NLS.java | jadx-gui/src/main/java/jadx/gui/utils/NLS.java | package jadx.gui.utils;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Vector;
import jadx.core.utils.exceptions.JadxRuntimeException;
public class NLS {
private static final Vector<LangLocale> LANG_LOCALES = new Vector<>();
private static final Map<LangLocale, ResourceBundle> LANG_LOCALES_MAP = new HashMap<>();
private static final ResourceBundle FALLBACK_MESSAGES_MAP;
private static final LangLocale LOCAL_LOCALE;
// Use these two fields to avoid invoking Map.get() method twice.
private static ResourceBundle localizedMessagesMap;
private static LangLocale currentLocale;
static {
LOCAL_LOCALE = new LangLocale(Locale.getDefault());
LANG_LOCALES.add(new LangLocale("en", "US")); // As default language
LANG_LOCALES.add(new LangLocale("zh", "CN"));
LANG_LOCALES.add(new LangLocale("zh", "TW"));
LANG_LOCALES.add(new LangLocale("es", "ES"));
LANG_LOCALES.add(new LangLocale("de", "DE"));
LANG_LOCALES.add(new LangLocale("ko", "KR"));
LANG_LOCALES.add(new LangLocale("pt", "BR"));
LANG_LOCALES.add(new LangLocale("ru", "RU"));
LANG_LOCALES.add(new LangLocale("id", "ID"));
LANG_LOCALES.forEach(NLS::load);
LangLocale defLang = LANG_LOCALES.get(0);
FALLBACK_MESSAGES_MAP = LANG_LOCALES_MAP.get(defLang);
localizedMessagesMap = LANG_LOCALES_MAP.get(defLang);
}
private NLS() {
}
private static void load(LangLocale lang) {
Locale locale = lang.get();
String resName = String.format("i18n/Messages_%s.properties", locale.toLanguageTag().replace('-', '_'));
URL bundleUrl = NLS.class.getClassLoader().getResource(resName);
if (bundleUrl == null) {
throw new JadxRuntimeException("Locale resource not found: " + resName);
}
ResourceBundle bundle;
try (Reader reader = new InputStreamReader(bundleUrl.openStream(), StandardCharsets.UTF_8)) {
bundle = new PropertyResourceBundle(reader);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to load " + resName, e);
}
LANG_LOCALES_MAP.put(lang, bundle);
}
public static String str(String key) {
try {
return localizedMessagesMap.getString(key);
} catch (Exception e) {
return FALLBACK_MESSAGES_MAP.getString(key);
}
}
public static String str(String key, Object... parameters) {
return String.format(str(key), parameters);
}
public static String str(String key, LangLocale locale) {
ResourceBundle bundle = LANG_LOCALES_MAP.get(locale);
if (bundle != null) {
try {
return bundle.getString(key);
} catch (MissingResourceException ignored) {
// use fallback string
}
}
return FALLBACK_MESSAGES_MAP.getString(key); // definitely exists
}
public static void setLocale(LangLocale locale) {
if (LANG_LOCALES_MAP.containsKey(locale)) {
currentLocale = locale;
} else {
currentLocale = LANG_LOCALES.get(0);
}
localizedMessagesMap = LANG_LOCALES_MAP.get(currentLocale);
}
public static Vector<LangLocale> getLangLocales() {
return LANG_LOCALES;
}
public static LangLocale currentLocale() {
return currentLocale;
}
public static LangLocale defaultLocale() {
if (LANG_LOCALES_MAP.containsKey(LOCAL_LOCALE)) {
return LOCAL_LOCALE;
}
// fallback to english if unsupported
return LANG_LOCALES.get(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/utils/PathTypeAdapter.java | jadx-gui/src/main/java/jadx/gui/utils/PathTypeAdapter.java | package jadx.gui.utils;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class PathTypeAdapter {
private static final TypeAdapter<Path> SINGLETON = new TypeAdapter<>() {
@Override
public void write(JsonWriter out, Path value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value.toAbsolutePath().toString());
}
}
@Override
public Path read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return Paths.get(in.nextString());
}
};
public static TypeAdapter<Path> singleton() {
return SINGLETON;
}
private PathTypeAdapter() {
}
}
| 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/utils/HexUtils.java | jadx-gui/src/main/java/jadx/gui/utils/HexUtils.java | package jadx.gui.utils;
public class HexUtils {
public static boolean isValidHexString(String hexString) {
String cleanS = hexString.replace(" ", "");
int len = cleanS.length();
try {
boolean isPair = len % 2 == 0;
if (isPair) {
Long.parseLong(cleanS, 16);
return true;
}
} catch (NumberFormatException ex) {
// ignore error
return false;
}
return false;
}
public static byte[] hexStringToByteArray(String hexString) {
if (hexString == null || hexString.isEmpty()) {
return new byte[0];
}
String cleanS = hexString.replace(" ", "");
int len = cleanS.length();
if (!isValidHexString(hexString)) {
throw new IllegalArgumentException("Hex string must have even length. Input length: " + len);
}
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
String byteString = cleanS.substring(i, i + 2);
try {
int intValue = Integer.parseInt(byteString, 16);
data[i / 2] = (byte) intValue;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Input string contains non-hex characters at index " + i + ": " + byteString, e);
}
}
return data;
}
}
| 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/utils/LafManager.java | jadx-gui/src/main/java/jadx/gui/utils/LafManager.java | package jadx.gui.utils;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.UIManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.formdev.flatlaf.FlatDarculaLaf;
import com.formdev.flatlaf.FlatDarkLaf;
import com.formdev.flatlaf.FlatIntelliJLaf;
import com.formdev.flatlaf.FlatLightLaf;
import com.formdev.flatlaf.intellijthemes.FlatAllIJThemes;
import com.formdev.flatlaf.themes.FlatMacDarkLaf;
import com.formdev.flatlaf.themes.FlatMacLightLaf;
import jadx.gui.settings.JadxSettings;
public class LafManager {
private static final Logger LOG = LoggerFactory.getLogger(LafManager.class);
public static final String SYSTEM_THEME_NAME = "default";
public static final String INITIAL_THEME_NAME = FlatLightLaf.NAME;
private static final Map<String, String> THEMES_MAP = initThemesMap();
public static void init(JadxSettings settings) {
if (setupLaf(getThemeClass(settings))) {
return;
}
setupLaf(SYSTEM_THEME_NAME);
settings.setLafTheme(SYSTEM_THEME_NAME);
settings.sync();
}
public static boolean updateLaf(JadxSettings settings) {
return setupLaf(getThemeClass(settings));
}
public static String[] getThemes() {
return THEMES_MAP.keySet().toArray(new String[0]);
}
private static String getThemeClass(JadxSettings settings) {
return THEMES_MAP.get(settings.getLafTheme());
}
private static boolean setupLaf(String themeClass) {
if (SYSTEM_THEME_NAME.equals(themeClass)) {
return applyLaf(UIManager.getSystemLookAndFeelClassName());
}
if (themeClass != null && !themeClass.isEmpty()) {
return applyLaf(themeClass);
}
return false;
}
private static Map<String, String> initThemesMap() {
Map<String, String> map = new LinkedHashMap<>();
map.put(SYSTEM_THEME_NAME, SYSTEM_THEME_NAME);
// default flatlaf themes
map.put(FlatLightLaf.NAME, FlatLightLaf.class.getName());
map.put(FlatDarkLaf.NAME, FlatDarkLaf.class.getName());
map.put(FlatMacLightLaf.NAME, FlatMacLightLaf.class.getName());
map.put(FlatMacDarkLaf.NAME, FlatMacDarkLaf.class.getName());
map.put(FlatIntelliJLaf.NAME, FlatIntelliJLaf.class.getName());
map.put(FlatDarculaLaf.NAME, FlatDarculaLaf.class.getName());
// themes from flatlaf-intellij-themes
for (FlatAllIJThemes.FlatIJLookAndFeelInfo themeInfo : FlatAllIJThemes.INFOS) {
map.put(themeInfo.getName(), themeInfo.getClassName());
}
return map;
}
private static boolean applyLaf(String theme) {
try {
UIManager.setLookAndFeel(theme);
return true;
} catch (Exception e) {
LOG.error("Failed to set laf to {}", theme, 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/utils/RelativePathTypeAdapter.java | jadx-gui/src/main/java/jadx/gui/utils/RelativePathTypeAdapter.java | package jadx.gui.utils;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class RelativePathTypeAdapter extends TypeAdapter<Path> {
private static final Logger LOG = LoggerFactory.getLogger(RelativePathTypeAdapter.class);
private final Path basePath;
public RelativePathTypeAdapter(Path basePath) {
this.basePath = Objects.requireNonNull(basePath);
}
@Override
public void write(JsonWriter out, Path value) throws IOException {
if (value == null) {
out.nullValue();
} else {
value = value.toAbsolutePath().normalize();
Path resultPath;
try {
resultPath = basePath.relativize(value);
} catch (IllegalArgumentException e) {
LOG.warn("Unable to build a relative path to {} - using absolute path", value);
resultPath = value;
}
out.value(resultPath.toString());
}
}
@Override
public Path read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
Path p = Paths.get(in.nextString());
if (p.isAbsolute()) {
return p;
}
return basePath.resolve(p);
}
}
| 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/utils/DesktopEntryUtils.java | jadx-gui/src/main/java/jadx/gui/utils/DesktopEntryUtils.java | package jadx.gui.utils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Objects;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.export.TemplateFile;
import jadx.core.utils.files.FileUtils;
public class DesktopEntryUtils {
private static final Logger LOG = LoggerFactory.getLogger(DesktopEntryUtils.class);
private static final Map<Integer, String> SIZE_TO_LOGO_MAP = Map.of(
16, "jadx-logo-16px.png",
32, "jadx-logo-32px.png",
48, "jadx-logo-48px.png",
252, "jadx-logo.png",
256, "jadx-logo.png");
private static final Path XDG_DESKTOP_MENU_COMMAND_PATH = findExecutablePath("xdg-desktop-menu");
private static final Path XDG_ICON_RESOURCE_COMMAND_PATH = findExecutablePath("xdg-icon-resource");
public static boolean createDesktopEntry() {
if (XDG_DESKTOP_MENU_COMMAND_PATH == null) {
LOG.error("xdg-desktop-menu was not found in $PATH");
return false;
}
if (XDG_ICON_RESOURCE_COMMAND_PATH == null) {
LOG.error("xdg-icon-resource was not found in $PATH");
return false;
}
Path desktopTempFile = FileUtils.createTempFileNonPrefixed("jadx-gui.desktop");
Path iconTempFolder = FileUtils.createTempDir("logos");
LOG.debug("Creating desktop with temp files: {}, {}", desktopTempFile, iconTempFolder);
try {
return createDesktopEntry(desktopTempFile, iconTempFolder);
} finally {
try {
FileUtils.deleteFileIfExists(desktopTempFile);
FileUtils.deleteDirIfExists(iconTempFolder);
} catch (IOException e) {
LOG.error("Failed to clean up temp files", e);
}
}
}
private static boolean createDesktopEntry(Path desktopTempFile, Path iconTempFolder) {
String launchScriptPath = getLaunchScriptPath();
if (launchScriptPath == null) {
return false;
}
for (Map.Entry<Integer, String> entry : SIZE_TO_LOGO_MAP.entrySet()) {
Path path = iconTempFolder.resolve(entry.getKey() + ".png");
if (!writeLogoFile(entry.getValue(), path)) {
return false;
}
if (!installIcon(entry.getKey(), path)) {
return false;
}
}
if (!writeDesktopFile(launchScriptPath, desktopTempFile)) {
return false;
}
return installDesktopEntry(desktopTempFile);
}
private static boolean installDesktopEntry(Path desktopTempFile) {
try {
ProcessBuilder desktopFileInstallCommand = new ProcessBuilder(Objects.requireNonNull(XDG_DESKTOP_MENU_COMMAND_PATH).toString(),
"install", desktopTempFile.toString());
Process process = desktopFileInstallCommand.start();
int statusCode = process.waitFor();
if (statusCode != 0) {
LOG.error("Got error code {} while installing desktop file", statusCode);
return false;
}
} catch (Exception e) {
LOG.error("Failed to install desktop file", e);
return false;
}
LOG.info("Successfully installed desktop file");
return true;
}
private static boolean installIcon(int size, Path iconPath) {
try {
ProcessBuilder iconInstallCommand =
new ProcessBuilder(Objects.requireNonNull(XDG_ICON_RESOURCE_COMMAND_PATH).toString(), "install", "--novendor", "--size",
String.valueOf(size), iconPath.toString(),
"jadx");
Process process = iconInstallCommand.start();
int statusCode = process.waitFor();
if (statusCode != 0) {
LOG.error("Got error code {} while installing icon of size {}", statusCode, size);
return false;
}
} catch (Exception e) {
LOG.error("Failed to install icon of size {}", size, e);
return false;
}
LOG.info("Successfully installed icon of size {}", size);
return true;
}
private static Path findExecutablePath(String executableName) {
for (String pathDirectory : System.getenv("PATH").split(File.pathSeparator)) {
Path path = Paths.get(pathDirectory, executableName);
if (path.toFile().isFile() && path.toFile().canExecute()) {
return path;
}
}
return null;
}
private static boolean writeDesktopFile(String launchScriptPath, Path desktopFilePath) {
try {
TemplateFile tmpl = TemplateFile.fromResources("/files/jadx-gui.desktop.tmpl");
tmpl.add("launchScriptPath", launchScriptPath);
FileUtils.writeFile(desktopFilePath, tmpl.build());
} catch (Exception e) {
LOG.error("Failed to save .desktop file at: {}", desktopFilePath, e);
return false;
}
LOG.debug("Wrote .desktop file to {}", desktopFilePath);
return true;
}
private static boolean writeLogoFile(String logoFile, Path logoPath) {
try (InputStream is = DesktopEntryUtils.class.getResourceAsStream("/logos/" + logoFile)) {
FileUtils.writeFile(logoPath, is);
} catch (Exception e) {
LOG.error("Failed to write logo file at: {}", logoPath, e);
return false;
}
LOG.debug("Wrote logo file to: {}", logoPath);
return true;
}
public static @Nullable String getLaunchScriptPath() {
String launchScriptPath = System.getProperty("jadx.launchScript.path");
if (launchScriptPath.isEmpty()) {
LOG.error(
"The jadx.launchScript.path property is not set. Please launch JADX with the bundled launch script or set it to the appropriate value yourself.");
return null;
}
LOG.debug("JADX launch script path: {}", launchScriptPath);
return launchScriptPath;
}
}
| 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/utils/JumpManager.java | jadx-gui/src/main/java/jadx/gui/utils/JumpManager.java | package jadx.gui.utils;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.Nullable;
public class JumpManager {
/**
* Maximum number of elements to store in a jump list
*/
private static final int MAX_JUMPS = 100;
/**
* This number of elements will be removed from the start if a list becomes bigger than MAX_JUMPS.
* List grow most of the time, so removing should be done in big batches to not run very often.
* Because of this, an effective jump history size will vary
* from (MAX_JUMPS - LIST_SHRINK_COUNT) to MAX_JUMPS over time.
*/
private static final int LIST_SHRINK_COUNT = 50;
private final List<JumpPosition> list = new ArrayList<>(MAX_JUMPS);
private int currentPos = 0;
public void addPosition(@Nullable JumpPosition pos) {
if (pos == null || ignoreJump(pos)) {
return;
}
currentPos++;
if (currentPos >= list.size()) {
list.add(pos);
if (list.size() >= MAX_JUMPS) {
list.subList(0, LIST_SHRINK_COUNT).clear();
}
currentPos = list.size() - 1;
} else {
// discard forward history after navigating back and jumping to a new place
list.set(currentPos, pos);
list.subList(currentPos + 1, list.size()).clear();
}
}
public int size() {
return list.size();
}
private boolean ignoreJump(JumpPosition pos) {
JumpPosition current = getCurrent();
if (current == null) {
return false;
}
return pos.equals(current);
}
public @Nullable JumpPosition getCurrent() {
if (currentPos >= 0 && currentPos < list.size()) {
return list.get(currentPos);
}
return null;
}
@Nullable
public JumpPosition getPrev() {
if (currentPos == 0) {
return null;
}
currentPos--;
return list.get(currentPos);
}
@Nullable
public JumpPosition getNext() {
int size = list.size();
if (size == 0) {
currentPos = 0;
return null;
}
int newPos = currentPos + 1;
if (newPos >= size) {
currentPos = size - 1;
return null;
}
JumpPosition position = list.get(newPos);
if (position == null) {
return null;
}
currentPos = newPos;
return position;
}
public void reset() {
list.clear();
currentPos = 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/utils/TextStandardActions.java | jadx-gui/src/main/java/jadx/gui/utils/TextStandardActions.java | package jadx.gui.utils;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
public class TextStandardActions {
private final JTextComponent textComponent;
private final JPopupMenu popup = new JPopupMenu();
private final UndoManager undoManager;
private Action undoAction;
private Action redoAction;
private Action cutAction;
private Action copyAction;
private Action pasteAction;
private Action deleteAction;
private Action selectAllAction;
public static void attach(JTextComponent textComponent) {
new TextStandardActions(textComponent);
}
public TextStandardActions(JTextComponent textComponent) {
this.textComponent = textComponent;
this.undoManager = new UndoManager();
initActions();
addPopupItems();
addKeyActions();
registerListeners();
}
private void initActions() {
undoAction = new AbstractAction(NLS.str("popup.undo")) {
@Override
public void actionPerformed(ActionEvent ae) {
if (undoManager.canUndo()) {
undoManager.undo();
}
}
};
redoAction = new AbstractAction(NLS.str("popup.redo")) {
@Override
public void actionPerformed(ActionEvent ae) {
if (undoManager.canRedo()) {
undoManager.redo();
}
}
};
cutAction = new AbstractAction(NLS.str("popup.cut")) {
@Override
public void actionPerformed(ActionEvent ae) {
textComponent.cut();
}
};
copyAction = new AbstractAction(NLS.str("popup.copy")) {
@Override
public void actionPerformed(ActionEvent ae) {
textComponent.copy();
}
};
pasteAction = new AbstractAction(NLS.str("popup.paste")) {
@Override
public void actionPerformed(ActionEvent ae) {
textComponent.paste();
}
};
deleteAction = new AbstractAction(NLS.str("popup.delete")) {
@Override
public void actionPerformed(ActionEvent ae) {
textComponent.replaceSelection("");
}
};
selectAllAction = new AbstractAction(NLS.str("popup.select_all")) {
@Override
public void actionPerformed(ActionEvent ae) {
textComponent.selectAll();
}
};
}
void addPopupItems() {
popup.add(undoAction);
popup.add(redoAction);
popup.addSeparator();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
popup.add(deleteAction);
popup.addSeparator();
popup.add(selectAllAction);
}
private void addKeyActions() {
KeyStroke undoKey = KeyStroke.getKeyStroke(KeyEvent.VK_Z, UiUtils.ctrlButton());
textComponent.getInputMap().put(undoKey, undoAction);
KeyStroke redoKey = KeyStroke.getKeyStroke(KeyEvent.VK_R, UiUtils.ctrlButton());
textComponent.getInputMap().put(redoKey, redoAction);
}
private void registerListeners() {
textComponent.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == 3 && e.getSource() == textComponent) {
process(e);
}
}
});
textComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit()));
}
private void process(MouseEvent e) {
textComponent.requestFocus();
boolean enabled = textComponent.isEnabled();
boolean editable = textComponent.isEditable();
boolean nonempty = !(textComponent.getText() == null || textComponent.getText().isEmpty());
boolean marked = textComponent.getSelectedText() != null;
boolean pasteAvailable = Toolkit.getDefaultToolkit().getSystemClipboard()
.getContents(null).isDataFlavorSupported(DataFlavor.stringFlavor);
undoAction.setEnabled(enabled && editable && undoManager.canUndo());
redoAction.setEnabled(enabled && editable && undoManager.canRedo());
cutAction.setEnabled(enabled && editable && marked);
copyAction.setEnabled(enabled && marked);
pasteAction.setEnabled(enabled && editable && pasteAvailable);
deleteAction.setEnabled(enabled && editable && marked);
selectAllAction.setEnabled(enabled && nonempty);
int nx = e.getX();
if (nx > 500) {
nx = nx - popup.getSize().width;
}
popup.show(e.getComponent(), nx, e.getY() - popup.getSize().height);
}
}
| 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/utils/CertificateManager.java | jadx-gui/src/main/java/jadx/gui/utils/CertificateManager.java | package jadx.gui.utils;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Collection;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CertificateManager {
private static final Logger LOG = LoggerFactory.getLogger(CertificateManager.class);
private static final String CERTIFICATE_TYPE_NAME = "X.509";
private final Certificate cert;
private X509Certificate x509cert;
public static String decode(InputStream in) {
StringBuilder strBuild = new StringBuilder();
Collection<? extends Certificate> certificates = readCertificates(in);
if (certificates != null) {
for (Certificate cert : certificates) {
CertificateManager certificateManager = new CertificateManager(cert);
strBuild.append(certificateManager.generateText());
}
}
return strBuild.toString();
}
static Collection<? extends Certificate> readCertificates(InputStream in) {
try {
CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE_NAME);
return cf.generateCertificates(in);
} catch (Exception e) {
LOG.error("Certificate read error", e);
}
return Collections.emptyList();
}
public CertificateManager(Certificate cert) {
this.cert = cert;
String type = cert.getType();
if (type.equals(CERTIFICATE_TYPE_NAME) && cert instanceof X509Certificate) {
x509cert = (X509Certificate) cert;
}
}
public String generateHeader() {
StringBuilder builder = new StringBuilder();
append(builder, NLS.str("certificate.cert_type"), x509cert.getType());
append(builder, NLS.str("certificate.serialSigVer"), ((Integer) x509cert.getVersion()).toString());
// serial number
append(builder, NLS.str("certificate.serialNumber"), "0x" + x509cert.getSerialNumber().toString(16));
// Get subject
Principal subjectDN = x509cert.getSubjectDN();
append(builder, NLS.str("certificate.cert_subject"), subjectDN.getName());
append(builder, NLS.str("certificate.serialValidFrom"), x509cert.getNotBefore().toString());
append(builder, NLS.str("certificate.serialValidUntil"), x509cert.getNotAfter().toString());
return builder.toString();
}
public String generateSignature() {
StringBuilder builder = new StringBuilder();
append(builder, NLS.str("certificate.serialSigType"), x509cert.getSigAlgName());
append(builder, NLS.str("certificate.serialSigOID"), x509cert.getSigAlgOID());
return builder.toString();
}
public String generateFingerprint() {
StringBuilder builder = new StringBuilder();
try {
append(builder, NLS.str("certificate.serialMD5"), getThumbPrint(x509cert, "MD5"));
append(builder, NLS.str("certificate.serialSHA1"), getThumbPrint(x509cert, "SHA-1"));
append(builder, NLS.str("certificate.serialSHA256"), getThumbPrint(x509cert, "SHA-256"));
} catch (Exception e) {
LOG.error("Failed to parse fingerprint", e);
}
return builder.toString();
}
public String generatePublicKey() {
PublicKey publicKey = x509cert.getPublicKey();
if (publicKey instanceof RSAPublicKey) {
return generateRSAPublicKey();
}
if (publicKey instanceof DSAPublicKey) {
return generateDSAPublicKey();
}
return "";
}
String generateRSAPublicKey() {
RSAPublicKey pub = (RSAPublicKey) cert.getPublicKey();
StringBuilder builder = new StringBuilder();
append(builder, NLS.str("certificate.serialPubKeyType"), pub.getAlgorithm());
append(builder, NLS.str("certificate.serialPubKeyExponent"), pub.getPublicExponent().toString(10));
append(builder, NLS.str("certificate.serialPubKeyModulusSize"), Integer.toString(
pub.getModulus().toString(2).length()));
append(builder, NLS.str("certificate.serialPubKeyModulus"), pub.getModulus().toString(10));
return builder.toString();
}
String generateDSAPublicKey() {
DSAPublicKey pub = (DSAPublicKey) cert.getPublicKey();
StringBuilder builder = new StringBuilder();
append(builder, NLS.str("certificate.serialPubKeyType"), pub.getAlgorithm());
append(builder, NLS.str("certificate.serialPubKeyY"), pub.getY().toString(10));
return builder.toString();
}
public String generateTextForX509() {
StringBuilder builder = new StringBuilder();
if (x509cert != null) {
builder.append(generateHeader());
builder.append('\n');
builder.append(generatePublicKey());
builder.append('\n');
builder.append(generateSignature());
builder.append('\n');
builder.append(generateFingerprint());
}
return builder.toString();
}
public String generateText() {
StringBuilder str = new StringBuilder();
String type = cert.getType();
if (type.equals(CERTIFICATE_TYPE_NAME)) {
str.append(generateTextForX509());
} else {
str.append(cert.toString());
}
return str.toString();
}
static void append(StringBuilder str, String name, String value) {
str.append(name).append(": ").append(value).append('\n');
}
public static String getThumbPrint(X509Certificate cert, String type)
throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance(type); // lgtm [java/weak-cryptographic-algorithm]
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
return hexify(digest);
}
public static String hexify(byte[] bytes) {
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
StringBuilder buf = new StringBuilder(bytes.length * 3);
for (byte aByte : bytes) {
buf.append(hexDigits[(aByte & 0xf0) >> 4]);
buf.append(hexDigits[aByte & 0x0f]);
buf.append(' ');
}
return buf.toString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/utils/IconsCache.java | jadx-gui/src/main/java/jadx/gui/utils/IconsCache.java | package jadx.gui.utils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.formdev.flatlaf.extras.FlatSVGIcon;
public class IconsCache {
private static final Map<String, FlatSVGIcon> SVG_ICONS = new ConcurrentHashMap<>();
public static FlatSVGIcon getSVGIcon(String name) {
return SVG_ICONS.computeIfAbsent(name, UiUtils::openSvgIcon);
}
}
| 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/utils/dbg/UIWatchDog.java | jadx-gui/src/main/java/jadx/gui/utils/dbg/UIWatchDog.java | package jadx.gui.utils.dbg;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.SwingUtilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.utils.UiUtils;
/**
* Watch for UI thread state, if it stuck log a warning with stacktrace
*/
public class UIWatchDog {
private static final Logger LOG = LoggerFactory.getLogger(UIWatchDog.class);
private static final int UI_MAX_DELAY_MS = 200;
private static final int CHECK_INTERVAL_MS = 50;
public static boolean onStart() {
UiUtils.uiRunAndWait(UIWatchDog::toggle);
return INSTANCE.isEnabled();
}
public static synchronized void toggle() {
if (SwingUtilities.isEventDispatchThread()) {
INSTANCE.toggleState(Thread.currentThread());
} else {
throw new JadxRuntimeException("This method should be called in UI thread");
}
}
private static final UIWatchDog INSTANCE = new UIWatchDog();
private final AtomicBoolean enabled = new AtomicBoolean(false);
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private Future<?> taskFuture;
private UIWatchDog() {
// singleton
}
private void toggleState(Thread uiThread) {
if (enabled.get()) {
// stop
enabled.set(false);
if (taskFuture != null) {
try {
taskFuture.get(CHECK_INTERVAL_MS * 5, TimeUnit.MILLISECONDS);
} catch (Throwable e) {
LOG.warn("Stopping UI watchdog error", e);
}
}
} else {
// start
enabled.set(true);
taskFuture = executor.submit(() -> start(uiThread));
}
}
private boolean isEnabled() {
return enabled.get();
}
@SuppressWarnings("BusyWait")
private void start(Thread uiThread) {
LOG.debug("UI watchdog started");
try {
Exception e = new JadxRuntimeException("at");
TimeMeasure tm = new TimeMeasure();
boolean stuck = false;
long reportTime = 0;
while (enabled.get()) {
if (uiThread.getState() == Thread.State.TIMED_WAITING) {
if (!stuck) {
tm.start();
stuck = true;
reportTime = UI_MAX_DELAY_MS;
} else {
tm.end();
long time = tm.getTime();
if (time > reportTime) {
e.setStackTrace(uiThread.getStackTrace());
LOG.warn("UI events thread stuck for {}ms", time, e);
reportTime += UI_MAX_DELAY_MS;
}
}
} else {
stuck = false;
}
Thread.sleep(CHECK_INTERVAL_MS);
}
} catch (Throwable e) {
LOG.error("UI watchdog fail", e);
}
LOG.debug("UI watchdog stopped");
}
private static final class TimeMeasure {
private long start;
private long end;
public void start() {
start = System.currentTimeMillis();
}
public void end() {
end = System.currentTimeMillis();
}
public long getTime() {
return end - start;
}
}
}
| 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/utils/tools/SyncNLSLines.java | jadx-gui/src/main/java/jadx/gui/utils/tools/SyncNLSLines.java | package jadx.gui.utils.tools;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Automatically synchronizes i18n files with a reference (EN) file.
* - Adds new lines from the reference file (commented out) to other language files.
* - Removes lines from other language files that are not present in the reference file.
* - Updates commented-out empty translations in other files with the reference text (commented).
*/
public class SyncNLSLines {
private static final Logger LOG = LoggerFactory.getLogger(SyncNLSLines.class);
private static final Path I18N_PATH = Paths.get("src/main/resources/i18n/");
private static final String REFERENCE_FILE_NAME = "Messages_en_US.properties";
/**
* Assumes this tool runs from the project root and jadx-gui is a direct subdirectory.
* If jadx-gui is the project root, this might need adjustment or to be removed
* if I18N_PATH is already relative to jadx-gui.
*/
private static final String GUI_MODULE_DIR_NAME = "jadx-gui";
private static final Path GUI_MODULE_PREFIX_PATH = Paths.get(GUI_MODULE_DIR_NAME);
public static void main(String[] args) {
try {
process();
} catch (Exception e) {
LOG.error("Failed to process i18n files", e);
}
}
private static void process() throws Exception {
Path refPath = getRefPath(REFERENCE_FILE_NAME);
if (!Files.exists(refPath)) {
LOG.error("Reference i18n file not found: {}", REFERENCE_FILE_NAME);
return;
}
LOG.info("Using reference file: {}", refPath.toAbsolutePath());
Path i18nDir = refPath.toAbsolutePath().getParent();
if (i18nDir == null) {
LOG.error("Could not determine i18n directory from reference path: {}", refPath);
return;
}
List<String> refFileLines = Files.readAllLines(refPath, StandardCharsets.UTF_8);
try (Stream<Path> pathStream = Files.list(i18nDir)) {
pathStream.filter(path -> {
String fileName = path.getFileName().toString();
return !fileName.equals(REFERENCE_FILE_NAME)
&& fileName.startsWith("Messages_")
&& fileName.endsWith(".properties");
})
.forEach(targetPath -> {
try {
LOG.info("Processing target file: {}", targetPath.toAbsolutePath());
applySync(refFileLines, targetPath);
} catch (Exception e) {
LOG.error("Failed to sync file: {}", targetPath, e);
}
});
}
LOG.info("I18N synchronization process finished.");
}
/**
* Parses a list of lines from a properties file into a map of key-value pairs.
* Preserves the full line as value. Comments and empty lines will have null keys.
*/
private static Map<String, String> parseProperties(List<String> lines) {
Map<String, String> properties = new LinkedHashMap<>();
for (String line : lines) {
String key = extractKey(line);
// If the key is null, it's a comment or blank line, we might not need these in the map.
// If we iterate over the original refFileLines later.
// For simplicity here, we only store actual properties.
if (key != null) {
properties.put(key, line);
}
}
return properties;
}
/**
* Extracts the key from a properties file line.
* Returns null if the line is a comment, empty, or doesn't seem to be a key-value pair.
*/
private static String extractKey(String line) {
String trimmedLine = line.trim();
if (trimmedLine.isEmpty() || trimmedLine.startsWith("#")) {
// Comment or empty line
return null;
}
int separatorIndex = trimmedLine.indexOf('=');
if (separatorIndex == -1) {
// Line without a separator could be a key with no value (less common in i18n)
// or just a malformed line. For now, let's consider it a key if it's not empty.
return trimmedLine;
}
return trimmedLine.substring(0, separatorIndex).trim();
}
private static void applySync(List<String> refFileLines, Path targetPath) throws IOException {
List<String> originalTargetLines = Files.readAllLines(targetPath, StandardCharsets.UTF_8);
Map<String, String> targetProperties = parseProperties(originalTargetLines);
List<String> newTargetLines = new ArrayList<>(refFileLines.size());
boolean updated = false;
for (String refLine : refFileLines) {
String refKey = extractKey(refLine);
if (refKey == null) {
// It's a comment or blank line from reference
newTargetLines.add(refLine);
} else {
// It's a property line from reference
if (targetProperties.containsKey(refKey)) {
String targetLine = targetProperties.get(refKey);
// Original logic: if target line is like "#key=" (commented, no value)
// then use the commented reference value.
String trimmed = targetLine.trim();
if (trimmed.startsWith("#")
&& trimmed.substring(1).trim().startsWith(refKey) // ensure it's the same key
&& trimmed.endsWith("=")) {
// Use reference line, commented
newTargetLines.add('#' + refLine.trim());
} else {
// Use existing target line
newTargetLines.add(targetLine);
}
} else {
// Key from reference is missing in target, add it commented out
newTargetLines.add('#' + refLine.trim());
}
}
}
// Check if files are different
if (originalTargetLines.size() != newTargetLines.size()) {
updated = true;
} else {
for (int i = 0; i < originalTargetLines.size(); i++) {
if (!originalTargetLines.get(i).equals(newTargetLines.get(i))) {
updated = true;
break;
}
}
}
if (updated) {
LOG.info("Updating {} ({} lines -> {} lines)", targetPath.getFileName(), originalTargetLines.size(), newTargetLines.size());
Files.write(targetPath, newTargetLines, StandardCharsets.UTF_8);
} else {
LOG.info("No changes needed for {}", targetPath.getFileName());
}
}
private static Path getRefPath(String referenceFileName) {
// Path relative to project root (where src/main/resources exists)
Path projectRootRelative = I18N_PATH.resolve(referenceFileName);
if (Files.exists(projectRootRelative)) {
return projectRootRelative.toAbsolutePath();
}
// Path relative to a module (e.g. jadx-gui/src/main/resources)
// This assumes the script is run from one level above GUI_MODULE_DIR_NAME
Path moduleRelative = GUI_MODULE_PREFIX_PATH.resolve(I18N_PATH).resolve(referenceFileName);
if (Files.exists(moduleRelative)) {
return moduleRelative.toAbsolutePath();
}
// Path if tool runs from within the GUI_MODULE_DIR_NAME itself
Path currentDirRelative = Paths.get(".").resolve(I18N_PATH).resolve(referenceFileName);
if (Files.exists(currentDirRelative)) {
return currentDirRelative.toAbsolutePath();
}
throw new RuntimeException("Can't find reference I18N: " + referenceFileName);
}
}
| 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/utils/cache/ValueCache.java | jadx-gui/src/main/java/jadx/gui/utils/cache/ValueCache.java | package jadx.gui.utils.cache;
import java.util.function.Function;
/**
* Simple store for values depending on 'key' object.
*
* @param <K> key object type
* @param <V> stored object type
*/
public class ValueCache<K, V> {
private K key;
private V value;
/**
* Return a stored object if key not changed, load a new object overwise.
*/
public synchronized V get(K requestKey, Function<K, V> loadFunc) {
if (key != null && key.equals(requestKey)) {
return value;
}
V newValue = loadFunc.apply(requestKey);
key = requestKey;
value = newValue;
return newValue;
}
}
| 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/utils/pkgs/JRenamePackage.java | jadx-gui/src/main/java/jadx/gui/utils/pkgs/JRenamePackage.java | package jadx.gui.utils.pkgs;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.Icon;
import org.apache.commons.lang3.StringUtils;
import jadx.api.JavaNode;
import jadx.api.JavaPackage;
import jadx.api.data.ICodeRename;
import jadx.api.data.impl.JadxCodeRename;
import jadx.api.data.impl.JadxNodeRef;
import jadx.core.deobf.NameMapper;
import jadx.gui.treemodel.JRenameNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.Icons;
import static jadx.core.deobf.NameMapper.VALID_JAVA_IDENTIFIER;
public class JRenamePackage implements JRenameNode {
private final JavaPackage refPkg;
private final String rawFullName;
private final String fullName;
private final String name;
public JRenamePackage(JavaPackage refPkg, String rawFullName, String fullName, String name) {
this.refPkg = refPkg;
this.rawFullName = rawFullName;
this.fullName = fullName;
this.name = name;
}
@Override
public JavaNode getJavaNode() {
return refPkg;
}
@Override
public String getTitle() {
return fullName;
}
@Override
public String getName() {
return name;
}
@Override
public Icon getIcon() {
return Icons.PACKAGE;
}
@Override
public boolean canRename() {
return true;
}
@Override
public ICodeRename buildCodeRename(String newName, Set<ICodeRename> renames) {
return new JadxCodeRename(JadxNodeRef.forPkg(rawFullName), newName);
}
@Override
public boolean isValidName(String newName) {
return isValidPackageName(newName);
}
private static final Pattern PACKAGE_RENAME_PATTERN = Pattern.compile(
"(\\.)?PKG(\\.PKG)*".replace("PKG", VALID_JAVA_IDENTIFIER.pattern()));
static boolean isValidPackageName(String newName) {
if (newName == null || newName.isEmpty() || NameMapper.isReserved(newName)) {
return false;
}
Matcher matcher = PACKAGE_RENAME_PATTERN.matcher(newName);
if (!matcher.matches()) {
return false;
}
for (String part : StringUtils.split(newName, '.')) {
if (NameMapper.isReserved(part)) {
return false;
}
}
return true;
}
@Override
public void removeAlias() {
refPkg.removeAlias();
}
@Override
public void addUpdateNodes(List<JavaNode> toUpdate) {
refPkg.addUseIn(toUpdate);
}
@Override
public void reload(MainWindow mainWindow) {
mainWindow.rebuildPackagesTree();
mainWindow.reloadTreePreservingState();
}
@Override
public String toString() {
return refPkg.toString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/utils/pkgs/PackageHelper.java | jadx-gui/src/main/java/jadx/gui/utils/pkgs/PackageHelper.java | package jadx.gui.utils.pkgs;
import java.util.ArrayList;
import java.util.Collections;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JavaPackage;
import jadx.core.dex.info.PackageInfo;
import jadx.core.utils.ListUtils;
import jadx.core.utils.Utils;
import jadx.gui.JadxWrapper;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JPackage;
import jadx.gui.utils.JNodeCache;
public class PackageHelper {
private static final Logger LOG = LoggerFactory.getLogger(PackageHelper.class);
private static final Comparator<JClass> CLASS_COMPARATOR = Comparator.comparing(JClass::getName, String.CASE_INSENSITIVE_ORDER);
private static final Comparator<JPackage> PKG_COMPARATOR = Comparator.comparing(JPackage::getName, String.CASE_INSENSITIVE_ORDER);
private final JadxWrapper wrapper;
private final JNodeCache nodeCache;
private List<String> excludedPackages;
private final Map<PackageInfo, JPackage> pkgInfoMap = new HashMap<>();
public PackageHelper(JadxWrapper wrapper, JNodeCache jNodeCache) {
this.wrapper = wrapper;
this.nodeCache = jNodeCache;
}
public List<JPackage> getRoots(boolean flatPackages) {
excludedPackages = wrapper.getExcludedPackages();
pkgInfoMap.clear();
if (flatPackages) {
return prepareFlatPackages();
}
long start = System.currentTimeMillis();
List<JPackage> roots = prepareHierarchyPackages();
if (LOG.isDebugEnabled()) {
LOG.debug("Prepare hierarchy packages in {} ms", System.currentTimeMillis() - start);
}
return roots;
}
public List<JRenamePackage> getRenameNodes(JPackage pkg) {
List<JRenamePackage> list = new ArrayList<>();
PackageInfo pkgInfo = pkg.getPkg().getPkgNode().getAliasPkgInfo();
Set<String> added = new HashSet<>();
do {
JPackage jPkg = pkgInfoMap.get(pkgInfo);
if (jPkg != null && !jPkg.isSynthetic()) {
JavaPackage javaPkg = jPkg.getPkg();
if (!javaPkg.isDefault()) {
JRenamePackage renamePkg = new JRenamePackage(javaPkg,
javaPkg.getRawFullName(), javaPkg.getFullName(), javaPkg.getName());
if (added.add(javaPkg.getFullName())) {
list.add(renamePkg);
}
}
}
pkgInfo = pkgInfo.getParentPkg();
} while (pkgInfo != null);
return list;
}
private List<JPackage> prepareFlatPackages() {
List<JPackage> list = new ArrayList<>();
for (JavaPackage javaPkg : wrapper.getPackages()) {
if (javaPkg.isLeaf() || !javaPkg.getClasses().isEmpty()) {
JPackage pkg = buildJPackage(javaPkg, false);
pkg.setName(javaPkg.getFullName());
list.add(pkg);
pkgInfoMap.put(javaPkg.getPkgNode().getAliasPkgInfo(), pkg);
}
}
list.sort(PKG_COMPARATOR);
return list;
}
private List<JPackage> prepareHierarchyPackages() {
JPackage root = JPackage.makeTmpRoot();
List<JavaPackage> packages = wrapper.getPackages();
List<JPackage> jPackages = new ArrayList<>(packages.size());
// create nodes for exists packages
for (JavaPackage javaPkg : packages) {
JPackage jPkg = buildJPackage(javaPkg, false);
jPackages.add(jPkg);
PackageInfo aliasPkgInfo = javaPkg.getPkgNode().getAliasPkgInfo();
jPkg.setName(aliasPkgInfo.getName());
pkgInfoMap.put(aliasPkgInfo, jPkg);
if (aliasPkgInfo.isRoot()) {
root.getSubPackages().add(jPkg);
}
}
// link subpackages, create missing packages created by renames
for (JPackage jPkg : jPackages) {
if (jPkg.getPkg().isLeaf()) {
buildLeafPath(jPkg, root, pkgInfoMap);
}
}
List<JPackage> toMerge = new ArrayList<>();
traverseMiddlePackages(root, toMerge);
Utils.treeDfsVisit(root, JPackage::getSubPackages, v -> v.getSubPackages().sort(PKG_COMPARATOR));
return root.getSubPackages();
}
private void buildLeafPath(JPackage jPkg, JPackage root, Map<PackageInfo, JPackage> pkgMap) {
JPackage currentJPkg = jPkg;
PackageInfo current = jPkg.getPkg().getPkgNode().getAliasPkgInfo();
while (true) {
current = current.getParentPkg();
if (current == null) {
break;
}
JPackage parentJPkg = pkgMap.get(current);
if (parentJPkg == null) {
parentJPkg = buildJPackage(currentJPkg.getPkg(), true);
parentJPkg.setName(current.getName());
pkgMap.put(current, parentJPkg);
if (current.isRoot()) {
root.getSubPackages().add(parentJPkg);
}
}
List<JPackage> subPackages = parentJPkg.getSubPackages();
String pkgName = currentJPkg.getName();
if (ListUtils.noneMatch(subPackages, p -> p.getName().equals(pkgName))) {
subPackages.add(currentJPkg);
}
currentJPkg = parentJPkg;
}
}
private static void traverseMiddlePackages(JPackage pkg, List<JPackage> toMerge) {
List<JPackage> subPackages = pkg.getSubPackages();
int count = subPackages.size();
for (int i = 0; i < count; i++) {
JPackage subPackage = subPackages.get(i);
JPackage replacePkg = mergeMiddlePackages(subPackage, toMerge);
if (replacePkg != subPackage) {
subPackages.set(i, replacePkg);
}
traverseMiddlePackages(replacePkg, toMerge);
}
}
private static JPackage mergeMiddlePackages(JPackage jPkg, List<JPackage> merged) {
List<JPackage> subPackages = jPkg.getSubPackages();
if (subPackages.size() == 1 && jPkg.getClasses().isEmpty()) {
merged.add(jPkg);
JPackage endPkg = mergeMiddlePackages(subPackages.get(0), merged);
merged.clear();
return endPkg;
}
if (!merged.isEmpty()) {
merged.add(jPkg);
jPkg.setName(Utils.listToString(merged, ".", JPackage::getName));
}
return jPkg;
}
private JPackage buildJPackage(JavaPackage javaPkg, boolean synthetic) {
boolean pkgEnabled = isPkgEnabled(javaPkg.getRawFullName(), excludedPackages);
List<JClass> classes;
if (synthetic) {
classes = Collections.emptyList();
} else {
classes = Utils.collectionMap(javaPkg.getClassesNoDup(), nodeCache::makeFrom);
classes.sort(CLASS_COMPARATOR);
}
return nodeCache.newJPackage(javaPkg, synthetic, pkgEnabled, classes);
}
private static boolean isPkgEnabled(String fullPkgName, List<String> excludedPackages) {
return excludedPackages.isEmpty() || excludedPackages.stream().noneMatch(p -> isPkgMatch(fullPkgName, p));
}
private static boolean isPkgMatch(String fullPkgName, String filterPkg) {
if (fullPkgName.equals(filterPkg)) {
return true;
}
// optimized check, same as `fullPkgName.startsWith(filterPkg + '.')`
int filterPkgLen = filterPkg.length();
return fullPkgName.length() > filterPkgLen
&& fullPkgName.charAt(filterPkgLen) == '.'
&& fullPkgName.startsWith(filterPkg);
}
}
| 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/utils/res/ResTableHelper.java | jadx-gui/src/main/java/jadx/gui/utils/res/ResTableHelper.java | package jadx.gui.utils.res;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
import jadx.api.ICodeInfo;
import jadx.api.ResourceFileContent;
import jadx.api.ResourceType;
import jadx.core.xmlgen.ResContainer;
import jadx.gui.treemodel.JResource;
public class ResTableHelper {
/**
* Build UI tree for resource table container.
*
* @return root nodes
*/
public static List<JResource> buildTree(ResContainer resTable) {
ResTableHelper resTableHelper = new ResTableHelper(resTable.getFileName());
resTableHelper.process(resTable);
return resTableHelper.roots;
}
private final List<JResource> roots = new ArrayList<>();
private final Map<String, JResource> dirs = new HashMap<>();
private final String resNamePrefix;
private ResTableHelper(String resTableFileName) {
this.resNamePrefix = resTableFileName + ":/";
}
private void process(ResContainer resTable) {
for (ResContainer subFile : resTable.getSubFiles()) {
loadSubNodes(subFile);
}
}
private void loadSubNodes(ResContainer rc) {
String resName = rc.getName();
int split = resName.lastIndexOf('/');
String dir;
String name;
if (split == -1) {
dir = null;
name = resName;
} else {
dir = resName.substring(0, split);
name = resName.substring(split + 1);
}
ICodeInfo code = rc.getText();
ResourceFileContent fileContent = new ResourceFileContent(name, ResourceType.XML, code);
JResource resFile = new JResource(fileContent, resNamePrefix + resName, name, JResource.JResType.FILE);
addResFile(dir, resFile);
for (ResContainer subFile : rc.getSubFiles()) {
loadSubNodes(subFile);
}
}
private void addResFile(@Nullable String dir, JResource resFile) {
if (dir == null) {
roots.add(resFile);
return;
}
JResource dirRes = dirs.get(dir);
if (dirRes != null) {
dirRes.addSubNode(resFile);
return;
}
JResource parentDir = null;
int splitPos = -1;
while (true) {
int prevStart = splitPos + 1;
splitPos = dir.indexOf('/', prevStart);
boolean last = splitPos == -1;
String path = last ? dir : dir.substring(0, splitPos);
JResource curDir = dirs.get(path);
if (curDir == null) {
String dirName = last ? dir.substring(prevStart) : dir.substring(prevStart, splitPos);
curDir = new JResource(null, resNamePrefix + path, dirName, JResource.JResType.DIR);
dirs.put(path, curDir);
if (parentDir == null) {
roots.add(curDir);
} else {
parentDir.addSubNode(curDir);
}
}
if (last) {
curDir.addSubNode(resFile);
return;
}
parentDir = curDir;
}
}
}
| 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/utils/fileswatcher/FilesWatcher.java | jadx-gui/src/main/java/jadx/gui/utils/fileswatcher/FilesWatcher.java | package jadx.gui.utils.fileswatcher;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.utils.Utils;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
public class FilesWatcher {
private static final Logger LOG = LoggerFactory.getLogger(FilesWatcher.class);
private final WatchService watcher = FileSystems.getDefault().newWatchService();
private final Map<WatchKey, Path> keys = new HashMap<>();
private final Map<Path, Set<Path>> files = new HashMap<>();
private final AtomicBoolean cancel = new AtomicBoolean(false);
private final BiConsumer<Path, WatchEvent.Kind<Path>> listener;
public FilesWatcher(List<Path> paths, BiConsumer<Path, WatchEvent.Kind<Path>> listener) throws IOException {
this.listener = listener;
for (Path path : paths) {
if (Files.isDirectory(path, NOFOLLOW_LINKS)) {
registerDirs(path);
} else {
Path parentDir = path.toAbsolutePath().getParent();
register(parentDir);
files.merge(parentDir, Collections.singleton(path), Utils::mergeSets);
}
}
}
public void cancel() {
cancel.set(true);
}
@SuppressWarnings("unchecked")
public void watch() {
cancel.set(false);
LOG.debug("File watcher started for {} dirs", keys.size());
while (!cancel.get()) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException e) {
LOG.debug("File watcher interrupted");
return;
}
Path dir = keys.get(key);
if (dir == null) {
LOG.warn("Unknown directory key: {}", key);
continue;
}
for (WatchEvent<?> event : key.pollEvents()) {
if (cancel.get() || Thread.interrupted()) {
return;
}
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
Path fileName = ((WatchEvent<Path>) event).context();
Path path = dir.resolve(fileName);
Set<Path> files = this.files.get(dir);
if (files == null || files.contains(path)) {
listener.accept(path, (WatchEvent.Kind<Path>) kind);
}
if (kind == ENTRY_CREATE) {
try {
if (Files.isDirectory(path, NOFOLLOW_LINKS)) {
registerDirs(path);
}
} catch (Exception e) {
LOG.warn("Failed to update directory watch: {}", path, e);
}
}
}
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
if (keys.isEmpty()) {
LOG.debug("File watcher stopped: all watch keys removed");
return;
}
}
}
}
private void registerDirs(Path start) throws IOException {
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
keys.put(key, dir);
}
}
| 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/utils/fileswatcher/LiveReloadWorker.java | jadx-gui/src/main/java/jadx/gui/utils/fileswatcher/LiveReloadWorker.java | package jadx.gui.utils.fileswatcher;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.reactivex.rxjava3.processors.PublishProcessor;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.UiUtils;
public class LiveReloadWorker {
private static final Logger LOG = LoggerFactory.getLogger(LiveReloadWorker.class);
private final MainWindow mainWindow;
private final PublishProcessor<Path> processor;
private volatile boolean started = false;
private ExecutorService executor;
private FilesWatcher watcher;
@SuppressWarnings("ResultOfMethodCallIgnored")
public LiveReloadWorker(MainWindow mainWindow) {
this.mainWindow = mainWindow;
this.processor = PublishProcessor.create();
this.processor
.debounce(1, TimeUnit.SECONDS)
.subscribe(path -> {
LOG.debug("Reload triggered");
UiUtils.uiRun(mainWindow::reopen);
});
}
public boolean isStarted() {
return started;
}
public synchronized void updateState(boolean enabled) {
if (this.started == enabled) {
return;
}
if (enabled) {
LOG.debug("Starting live reload worker");
start();
} else {
LOG.debug("Stopping live reload worker");
stop();
}
}
private void onUpdate(Path path, WatchEvent.Kind<Path> pathKind) {
LOG.debug("Path updated: {}", path);
processor.onNext(path);
}
private synchronized void start() {
try {
watcher = new FilesWatcher(mainWindow.getProject().getFilePaths(), this::onUpdate);
executor = Executors.newSingleThreadExecutor();
started = true;
executor.submit(watcher::watch);
} catch (Exception e) {
LOG.warn("Failed to start live reload worker", e);
resetState();
}
}
private synchronized void stop() {
try {
watcher.cancel();
executor.shutdownNow();
boolean canceled = executor.awaitTermination(5, TimeUnit.SECONDS);
if (!canceled) {
LOG.warn("Failed to cancel live reload worker");
}
} catch (Exception e) {
LOG.warn("Failed to stop live reload worker", e);
} finally {
resetState();
}
}
private void resetState() {
started = false;
executor = null;
watcher = 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/utils/shortcut/Shortcut.java | jadx-gui/src/main/java/jadx/gui/utils/shortcut/Shortcut.java | package jadx.gui.utils.shortcut;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.swing.KeyStroke;
import jadx.commons.app.JadxSystemInfo;
public class Shortcut {
private static final Set<Integer> FORBIDDEN_KEY_CODES = new HashSet<>(List.of(
KeyEvent.VK_UNDEFINED, KeyEvent.VK_SHIFT, KeyEvent.VK_ALT, KeyEvent.VK_META, KeyEvent.VK_ALT_GRAPH));
private static final Set<Integer> ALLOWED_MODIFIERS = new HashSet<>(List.of(
KeyEvent.CTRL_DOWN_MASK, KeyEvent.META_DOWN_MASK, KeyEvent.ALT_DOWN_MASK, KeyEvent.ALT_GRAPH_DOWN_MASK,
KeyEvent.SHIFT_DOWN_MASK));
private Integer keyCode = null;
private Integer modifiers = null;
private Integer mouseButton = null;
private Shortcut() {
}
public static Shortcut keyboard(int keyCode) {
return keyboard(keyCode, 0);
}
public static Shortcut keyboard(int keyCode, int modifiers) {
Shortcut shortcut = new Shortcut();
shortcut.keyCode = keyCode;
shortcut.modifiers = modifiers;
return shortcut;
}
public static Shortcut mouse(int mouseButton) {
Shortcut shortcut = new Shortcut();
shortcut.mouseButton = mouseButton;
return shortcut;
}
public static Shortcut none() {
Shortcut shortcut = new Shortcut();
// Must have at least one non-null attribute in order to be serialized
// otherwise will roll back to default Shortcut
shortcut.modifiers = 0;
return shortcut;
}
public Integer getKeyCode() {
return keyCode;
}
public Integer getModifiers() {
return modifiers;
}
public Integer getMouseButton() {
return mouseButton;
}
public boolean isKeyboard() {
return keyCode != null;
}
public boolean isMouse() {
return mouseButton != null;
}
public boolean isNone() {
return !isMouse() && !isKeyboard();
}
public boolean isValidKeyboard() {
return isKeyboard() && !FORBIDDEN_KEY_CODES.contains(keyCode) && isValidModifiers();
}
public boolean isValidModifiers() {
int modifiersTest = modifiers;
for (Integer modifier : ALLOWED_MODIFIERS) {
modifiersTest &= ~modifier;
}
return modifiersTest == 0;
}
public KeyStroke toKeyStroke() {
return isKeyboard()
? KeyStroke.getKeyStroke(keyCode, modifiers,
modifiers != 0 && JadxSystemInfo.IS_MAC)
: null;
}
@Override
public String toString() {
if (isKeyboard()) {
return keyToString();
} else if (isMouse()) {
return mouseToString();
}
return "NONE";
}
public String getTypeString() {
if (isKeyboard()) {
return "Keyboard";
} else if (isMouse()) {
return "Mouse";
}
return null;
}
private String mouseToString() {
return "MouseButton" + mouseButton;
}
private String keyToString() {
StringBuilder sb = new StringBuilder();
if (modifiers != null && modifiers > 0) {
sb.append(KeyEvent.getModifiersExText(modifiers));
sb.append('+');
}
if (keyCode != null && keyCode != 0) {
sb.append(KeyEvent.getKeyText(keyCode));
} else {
sb.append("UNDEFINED");
}
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Shortcut shortcut = (Shortcut) o;
return Objects.equals(keyCode, shortcut.keyCode)
&& Objects.equals(modifiers, shortcut.modifiers)
&& Objects.equals(mouseButton, shortcut.mouseButton);
}
@Override
public int hashCode() {
return Objects.hash(keyCode, modifiers, mouseButton);
}
}
| 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/utils/shortcut/ShortcutsController.java | jadx-gui/src/main/java/jadx/gui/utils/shortcut/ShortcutsController.java | package jadx.gui.utils.shortcut;
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.data.ShortcutsWrapper;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.action.ActionCategory;
import jadx.gui.ui.action.ActionModel;
import jadx.gui.ui.action.IShortcutAction;
import jadx.gui.utils.UiUtils;
public class ShortcutsController {
private static final Logger LOG = LoggerFactory.getLogger(ShortcutsController.class);
private final JadxSettings settings;
private final Map<ActionModel, Set<IShortcutAction>> boundActions = new EnumMap<>(ActionModel.class);
private final Map<Integer, List<IShortcutAction>> mouseActions = new HashMap<>();
private ShortcutsWrapper shortcuts;
public ShortcutsController(JadxSettings settings) {
this.settings = settings;
}
public void loadSettings() {
shortcuts = settings.getShortcuts();
indexMouseActions();
boundActions.forEach((actionModel, actions) -> {
if (actions != null) {
Shortcut shortcut = get(actionModel);
for (IShortcutAction action : actions) {
action.setShortcut(shortcut);
}
}
});
}
@Nullable
public Shortcut get(ActionModel actionModel) {
return shortcuts.get(actionModel);
}
public KeyStroke getKeyStroke(ActionModel actionModel) {
Shortcut shortcut = get(actionModel);
if (shortcut != null && shortcut.isKeyboard()) {
return shortcut.toKeyStroke();
}
return null;
}
/**
* Binds to an action and updates its shortcut every time loadSettings is called
*/
public void bind(IShortcutAction action) {
if (action.getShortcutComponent() == null) {
LOG.warn("No shortcut component in action: {}", action, new JadxRuntimeException());
return;
}
boundActions.computeIfAbsent(action.getActionModel(), k -> new HashSet<>()).add(action);
}
/*
* Immediately sets the shortcut for an action
*/
public void bindImmediate(IShortcutAction action) {
bind(action);
Shortcut shortcut = get(action.getActionModel());
action.setShortcut(shortcut);
}
public static Map<ActionModel, Shortcut> getDefault() {
Map<ActionModel, Shortcut> shortcuts = new HashMap<>();
for (ActionModel actionModel : ActionModel.values()) {
shortcuts.put(actionModel, actionModel.getDefaultShortcut());
}
return shortcuts;
}
public void registerMouseEventListener(MainWindow mw) {
Toolkit.getDefaultToolkit().addAWTEventListener(event -> {
if (mw.isSettingsOpen()) {
return;
}
if (!(event instanceof MouseEvent)) {
return;
}
MouseEvent mouseEvent = (MouseEvent) event;
if (mouseEvent.getID() != MouseEvent.MOUSE_PRESSED) {
return;
}
List<IShortcutAction> actions = mouseActions.get(mouseEvent.getButton());
if (actions != null) {
for (IShortcutAction action : actions) {
if (action != null) {
mouseEvent.consume();
UiUtils.uiRun(action::performAction);
}
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
private void indexMouseActions() {
mouseActions.clear();
for (ActionModel actionModel : ActionModel.values()) {
Shortcut shortcut = shortcuts.get(actionModel);
if (shortcut != null && shortcut.isMouse()) {
Set<IShortcutAction> actions = boundActions.get(actionModel);
if (actions != null && !actions.isEmpty()) {
mouseActions.computeIfAbsent(shortcut.getMouseButton(), i -> new ArrayList<>())
.addAll(actions);
}
}
}
}
public void unbindActionsForComponent(JComponent component) {
for (Set<IShortcutAction> actions : boundActions.values()) {
if (actions != null) {
actions.removeIf(action -> action == null
|| action.getShortcutComponent() == null
|| action.getShortcutComponent() == component);
}
}
}
/**
* Keep only actions bound to the main window.
* Other actions will be added on demand.
*/
public void reset() {
for (ActionModel actionModel : ActionModel.values()) {
if (actionModel.getCategory() != ActionCategory.MENU_TOOLBAR) {
boundActions.remove(actionModel);
}
}
}
}
| 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/utils/rx/RxUtils.java | jadx-gui/src/main/java/jadx/gui/utils/rx/RxUtils.java | package jadx.gui.utils.rx;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.function.Supplier;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentListener;
import org.jetbrains.annotations.NotNull;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.FlowableEmitter;
import io.reactivex.rxjava3.core.FlowableOnSubscribe;
import jadx.gui.utils.ui.DocumentUpdateListener;
public class RxUtils {
public static Flowable<String> textFieldChanges(final JTextField textField) {
FlowableOnSubscribe<String> source = emitter -> {
DocumentListener listener = new DocumentUpdateListener(ev -> emitter.onNext(textField.getText()));
textField.getDocument().addDocumentListener(listener);
emitter.setDisposable(new CustomDisposable(() -> textField.getDocument().removeDocumentListener(listener)));
};
return Flowable.create(source, BackpressureStrategy.LATEST).distinctUntilChanged();
}
public static Flowable<String> textFieldEnterPress(final JTextField textField) {
FlowableOnSubscribe<String> source = emitter -> {
KeyListener keyListener = enterKeyListener(emitter, textField::getText);
textField.addKeyListener(keyListener);
emitter.setDisposable(new CustomDisposable(() -> textField.removeKeyListener(keyListener)));
};
return Flowable.create(source, BackpressureStrategy.LATEST).distinctUntilChanged();
}
public static Flowable<String> spinnerChanges(final JSpinner spinner) {
FlowableOnSubscribe<String> source = emitter -> {
ChangeListener changeListener = e -> emitter.onNext(String.valueOf(spinner.getValue()));
spinner.addChangeListener(changeListener);
emitter.setDisposable(new CustomDisposable(() -> spinner.removeChangeListener(changeListener)));
};
return Flowable.create(source, BackpressureStrategy.LATEST).distinctUntilChanged();
}
public static Flowable<String> spinnerEnterPress(final JSpinner spinner) {
FlowableOnSubscribe<String> source = emitter -> {
KeyListener keyListener = enterKeyListener(emitter, () -> String.valueOf(spinner.getValue()));
spinner.addKeyListener(keyListener);
emitter.setDisposable(new CustomDisposable(() -> spinner.removeKeyListener(keyListener)));
};
return Flowable.create(source, BackpressureStrategy.LATEST).distinctUntilChanged();
}
private static @NotNull KeyListener enterKeyListener(FlowableEmitter<String> emitter, Supplier<String> supplier) {
return new KeyAdapter() {
@Override
public void keyPressed(KeyEvent ev) {
if (ev.getKeyCode() == KeyEvent.VK_ENTER) {
emitter.onNext(supplier.get());
}
}
};
}
}
| 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/utils/rx/CustomDisposable.java | jadx-gui/src/main/java/jadx/gui/utils/rx/CustomDisposable.java | package jadx.gui.utils.rx;
import java.util.concurrent.atomic.AtomicBoolean;
import io.reactivex.rxjava3.disposables.Disposable;
public class CustomDisposable implements Disposable {
private final AtomicBoolean disposed = new AtomicBoolean(false);
private final Runnable disposeTask;
public CustomDisposable(Runnable disposeTask) {
this.disposeTask = disposeTask;
}
@Override
public void dispose() {
try {
disposeTask.run();
} finally {
disposed.set(true);
}
}
@Override
public boolean isDisposed() {
return disposed.get();
}
}
| 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/utils/rx/DebounceUpdate.java | jadx-gui/src/main/java/jadx/gui/utils/rx/DebounceUpdate.java | package jadx.gui.utils.rx;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.FlowableEmitter;
import io.reactivex.rxjava3.core.FlowableOnSubscribe;
import io.reactivex.rxjava3.disposables.Disposable;
public class DebounceUpdate {
private FlowableEmitter<Boolean> emitter;
private final Disposable disposable;
public DebounceUpdate(int timeMs, Runnable action) {
FlowableOnSubscribe<Boolean> source = emitter -> this.emitter = emitter;
disposable = Flowable.create(source, BackpressureStrategy.LATEST)
.debounce(timeMs, TimeUnit.MILLISECONDS)
.subscribe(v -> action.run());
}
public void requestUpdate() {
emitter.onNext(Boolean.TRUE);
}
public void dispose() {
disposable.dispose();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/utils/files/JadxFiles.java | jadx-gui/src/main/java/jadx/gui/utils/files/JadxFiles.java | package jadx.gui.utils.files;
import java.nio.file.Path;
import jadx.commons.app.JadxCommonFiles;
public class JadxFiles {
private static final Path CONFIG_DIR = JadxCommonFiles.getConfigDir();
public static final Path GUI_CONF = CONFIG_DIR.resolve("gui.json");
public static final Path CACHES_LIST = CONFIG_DIR.resolve("caches.json");
public static final Path CACHE_DIR = JadxCommonFiles.getCacheDir();
public static final Path PROJECTS_CACHE_DIR = CACHE_DIR.resolve("projects");
}
| 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/utils/plugins/PluginWithOptions.java | jadx-gui/src/main/java/jadx/gui/utils/plugins/PluginWithOptions.java | package jadx.gui.utils.plugins;
import org.jetbrains.annotations.NotNull;
import jadx.api.plugins.JadxPlugin;
import jadx.api.plugins.options.JadxPluginOptions;
public class PluginWithOptions implements Comparable<PluginWithOptions> {
public static final PluginWithOptions NULL = new PluginWithOptions(null, null);
private final JadxPlugin plugin;
private final JadxPluginOptions options;
public PluginWithOptions(JadxPlugin plugin, JadxPluginOptions options) {
this.plugin = plugin;
this.options = options;
}
public JadxPlugin getPlugin() {
return plugin;
}
public JadxPluginOptions getOptions() {
return options;
}
@Override
public int compareTo(@NotNull PluginWithOptions other) {
return plugin.getClass().getName().compareTo(other.getClass().getName());
}
@Override
public String toString() {
return "PluginWithOptions{plugin=" + plugin + ", options=" + options + '}';
}
}
| 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/utils/plugins/SettingsGroupPluginWrap.java | jadx-gui/src/main/java/jadx/gui/utils/plugins/SettingsGroupPluginWrap.java | package jadx.gui.utils.plugins;
import java.util.Collections;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.plugins.gui.ISettingsGroup;
public class SettingsGroupPluginWrap implements ISettingsGroup {
private static final Logger LOG = LoggerFactory.getLogger(SettingsGroupPluginWrap.class);
private final String pluginId;
private final ISettingsGroup pluginSettingGroup;
public SettingsGroupPluginWrap(String pluginId, ISettingsGroup pluginSettingGroup) {
this.pluginId = pluginId;
this.pluginSettingGroup = pluginSettingGroup;
}
@Override
public String getTitle() {
try {
return pluginSettingGroup.getTitle();
} catch (Throwable t) {
LOG.warn("Failed to get settings group title for plugin: {}", pluginId, t);
return "<error>";
}
}
@Override
public JComponent buildComponent() {
try {
return pluginSettingGroup.buildComponent();
} catch (Throwable t) {
LOG.warn("Failed to build settings group component for plugin: {}", pluginId, t);
return new JLabel("<error>");
}
}
@Override
public List<ISettingsGroup> getSubGroups() {
try {
return pluginSettingGroup.getSubGroups();
} catch (Throwable t) {
LOG.warn("Failed to get settings group sub-groups for plugin: {}", pluginId, t);
return Collections.emptyList();
}
}
@Override
public void close(boolean save) {
try {
pluginSettingGroup.close(save);
} catch (Throwable t) {
LOG.warn("Failed to close settings group for plugin: {}", pluginId, t);
}
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/utils/plugins/CollectPlugins.java | jadx-gui/src/main/java/jadx/gui/utils/plugins/CollectPlugins.java | package jadx.gui.utils.plugins;
import java.util.ArrayList;
import java.util.Optional;
import java.util.SortedSet;
import jadx.api.JadxArgs;
import jadx.api.JadxDecompiler;
import jadx.cli.plugins.JadxFilesGetter;
import jadx.core.plugins.AppContext;
import jadx.core.plugins.JadxPluginManager;
import jadx.core.plugins.PluginContext;
import jadx.gui.ui.MainWindow;
import jadx.plugins.tools.JadxExternalPluginsLoader;
/**
* Collect all plugins.
* Init not yet loaded plugins in new temporary context.
* Support a case if decompiler in wrapper is not initialized yet.
*/
public class CollectPlugins {
private final MainWindow mainWindow;
public CollectPlugins(MainWindow mainWindow) {
this.mainWindow = mainWindow;
}
public CloseablePlugins build() {
Optional<JadxDecompiler> currentDecompiler = mainWindow.getWrapper().getCurrentDecompiler();
if (currentDecompiler.isPresent()) {
JadxDecompiler decompiler = currentDecompiler.get();
SortedSet<PluginContext> plugins = decompiler.getPluginManager().getResolvedPluginContexts();
return new CloseablePlugins(new ArrayList<>(plugins), null);
}
// collect and init plugins in new temp context
JadxArgs jadxArgs = mainWindow.getSettings().toJadxArgs();
jadxArgs.setFilesGetter(JadxFilesGetter.INSTANCE);
try (JadxDecompiler decompiler = new JadxDecompiler(jadxArgs)) {
JadxPluginManager pluginManager = decompiler.getPluginManager();
pluginManager.registerAddPluginListener(pluginContext -> {
AppContext appContext = new AppContext();
appContext.setGuiContext(null); // load temp plugins without UI context
appContext.setFilesGetter(jadxArgs.getFilesGetter());
pluginContext.setAppContext(appContext);
});
pluginManager.load(new JadxExternalPluginsLoader());
SortedSet<PluginContext> allPlugins = pluginManager.getAllPluginContexts();
pluginManager.init(allPlugins);
Runnable closeable = () -> pluginManager.unload(allPlugins);
return new CloseablePlugins(new ArrayList<>(allPlugins), closeable);
}
}
}
| 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/utils/plugins/CloseablePlugins.java | jadx-gui/src/main/java/jadx/gui/utils/plugins/CloseablePlugins.java | package jadx.gui.utils.plugins;
import java.util.List;
import org.jetbrains.annotations.Nullable;
import jadx.core.plugins.PluginContext;
public class CloseablePlugins {
private final List<PluginContext> list;
private final @Nullable Runnable closeable;
public CloseablePlugins(List<PluginContext> list, @Nullable Runnable closeable) {
this.list = list;
this.closeable = closeable;
}
public void close() {
if (closeable != null) {
closeable.run();
}
}
public @Nullable Runnable getCloseable() {
return closeable;
}
public List<PluginContext> getList() {
return list;
}
}
| 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/utils/layout/WrapLayout.java | jadx-gui/src/main/java/jadx/gui/utils/layout/WrapLayout.java | package jadx.gui.utils.layout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Insets;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import org.intellij.lang.annotations.MagicConstant;
/**
* FlowLayout subclass that fully supports wrapping of components.
*/
public class WrapLayout extends FlowLayout {
private static final long serialVersionUID = 6109752116520941346L;
private Dimension preferredLayoutSize;
/**
* Constructs a new <code>WrapLayout</code> with a left
* alignment and a default 5-unit horizontal and vertical gap.
*/
public WrapLayout() {
super();
}
/**
* Constructs a new <code>FlowLayout</code> with the specified
* alignment and a default 5-unit horizontal and vertical gap.
* The value of the alignment argument must be one of
* <code>WrapLayout</code>, <code>WrapLayout</code>,
* or <code>WrapLayout</code>.
*
* @param align the alignment value
*/
public WrapLayout(@MagicConstant(valuesFromClass = FlowLayout.class) int align) {
super(align);
}
/**
* Creates a new flow layout manager with the indicated alignment
* and the indicated horizontal and vertical gaps.
* <p>
* The value of the alignment argument must be one of
* <code>WrapLayout</code>, <code>WrapLayout</code>,
* or <code>WrapLayout</code>.
*
* @param align the alignment value
* @param hgap the horizontal gap between components
* @param vgap the vertical gap between components
*/
public WrapLayout(int align, int hgap, int vgap) {
super(align, hgap, vgap);
}
/**
* Returns the preferred dimensions for this layout given the
* <i>visible</i> components in the specified target container.
*
* @param target the component which needs to be laid out
* @return the preferred dimensions to lay out the
* subcomponents of the specified container
*/
@Override
public Dimension preferredLayoutSize(Container target) {
return layoutSize(target, true);
}
/**
* Returns the minimum dimensions needed to layout the <i>visible</i>
* components contained in the specified target container.
*
* @param target the component which needs to be laid out
* @return the minimum dimensions to lay out the
* subcomponents of the specified container
*/
@Override
public Dimension minimumLayoutSize(Container target) {
Dimension minimum = layoutSize(target, false);
minimum.width -= (getHgap() + 1);
return minimum;
}
/**
* Returns the minimum or preferred dimension needed to layout the target
* container.
*
* @param target target to get layout size for
* @param preferred should preferred size be calculated
* @return the dimension to layout the target container
*/
private Dimension layoutSize(Container target, boolean preferred) {
synchronized (target.getTreeLock()) {
// Each row must fit with the width allocated to the container.
// When the container width = 0, the preferred width of the container
// has not yet been calculated so lets ask for the maximum.
int targetWidth = target.getSize().width;
Container container = target;
while (container.getSize().width == 0 && container.getParent() != null) {
container = container.getParent();
}
targetWidth = container.getSize().width;
if (targetWidth == 0) {
targetWidth = Integer.MAX_VALUE;
}
int hgap = getHgap();
int vgap = getVgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++) {
Component m = target.getComponent(i);
if (m.isVisible()) {
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
int width = d.width;
// Can't add the component to current row. Start a new row.
if (rowWidth + width >= maxWidth) {
addRow(dim, rowWidth, rowHeight);
rowWidth = 0;
rowHeight = 0;
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0) {
rowWidth += hgap;
}
rowWidth += width;
rowHeight = Math.max(rowHeight, d.height);
}
}
addRow(dim, rowWidth, rowHeight);
dim.width += horizontalInsetsAndGap;
dim.height += insets.top + insets.bottom + vgap * 2;
// When using a scroll pane or the DecoratedLookAndFeel we need to
// make sure the preferred size is less than the size of the
// target container so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null && target.isValid()) {
dim.width -= (hgap + 1);
}
return dim;
}
}
/*
* A new row has been completed. Use the dimensions of this row
* to update the preferred size for the container.
* @param dim update the width and height when appropriate
* @param rowWidth the width of the row to add
* @param rowHeight the height of the row to add
*/
private void addRow(Dimension dim, int rowWidth, int rowHeight) {
dim.width = Math.max(dim.width, rowWidth);
if (dim.height > 0) {
dim.height += getVgap();
}
dim.height += rowHeight;
}
}
| 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/utils/ui/ActionHandler.java | jadx-gui/src/main/java/jadx/gui/utils/ui/ActionHandler.java | package jadx.gui.utils.ui;
import java.awt.event.ActionEvent;
import java.util.function.Consumer;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JToggleButton;
import javax.swing.KeyStroke;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.shortcut.Shortcut;
public class ActionHandler extends AbstractAction {
private final Consumer<ActionEvent> consumer;
public ActionHandler(Runnable action) {
this.consumer = ev -> action.run();
}
public ActionHandler(Consumer<ActionEvent> consumer) {
this.consumer = consumer;
}
public ActionHandler(String name, Runnable action) {
this(action);
setName(name);
}
public ActionHandler() {
this.consumer = ev -> {
};
}
public void setName(String name) {
putValue(NAME, name);
}
public ActionHandler withNameAndDesc(String name) {
setNameAndDesc(name);
return this;
}
public void setNameAndDesc(String name) {
setName(name);
setShortDescription(name);
}
public void setShortDescription(String desc) {
putValue(SHORT_DESCRIPTION, desc);
}
public void setIcon(Icon icon) {
putValue(SMALL_ICON, icon);
}
public void setSelected(boolean selected) {
putValue(SELECTED_KEY, selected);
}
public void setKeyBinding(KeyStroke keyStroke) {
putValue(ACCELERATOR_KEY, keyStroke);
}
public void attachKeyBindingFor(JComponent component, KeyStroke keyStroke) {
UiUtils.addKeyBinding(component, keyStroke, "run", this);
setKeyBinding(keyStroke);
}
public void addKeyBindToDescription() {
KeyStroke keyStroke = (KeyStroke) getValue(ACCELERATOR_KEY);
if (keyStroke != null) {
String keyText = Shortcut.keyboard(keyStroke.getKeyCode(), keyStroke.getModifiers()).toString();
String desc = (String) getValue(SHORT_DESCRIPTION);
setShortDescription(desc + " (" + keyText + ")");
}
}
@Override
public void actionPerformed(ActionEvent e) {
consumer.accept(e);
}
public JButton makeButton() {
addKeyBindToDescription();
return new JButton(this);
}
public JToggleButton makeToggleButton() {
JToggleButton toggleButton = new JToggleButton(this);
toggleButton.setText("");
return toggleButton;
}
public JCheckBoxMenuItem makeCheckBoxMenuItem() {
return new JCheckBoxMenuItem(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/utils/ui/ZoomActions.java | jadx-gui/src/main/java/jadx/gui/utils/ui/ZoomActions.java | package jadx.gui.utils.ui;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.KeyEvent;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.font.FontAdapter;
import jadx.gui.settings.font.FontSettings;
import jadx.gui.ui.codearea.SmaliArea;
import jadx.gui.utils.UiUtils;
public class ZoomActions {
private final JComponent component;
private final JadxSettings settings;
private final Runnable update;
public static void register(JComponent component, JadxSettings settings, Runnable update) {
ZoomActions actions = new ZoomActions(component, settings, update);
actions.register();
}
private ZoomActions(JComponent component, JadxSettings settings, Runnable update) {
this.component = component;
this.settings = settings;
this.update = update;
}
private void register() {
String zoomIn = "TextZoomIn";
String zoomOut = "TextZoomOut";
int ctrlButton = UiUtils.ctrlButton();
InputMap inputMap = component.getInputMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, ctrlButton), zoomIn);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, ctrlButton), zoomIn);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, ctrlButton), zoomIn);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, ctrlButton), zoomOut);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, ctrlButton), zoomOut);
ActionMap actionMap = component.getActionMap();
actionMap.put(zoomIn, new ActionHandler(e -> textZoom(1)));
actionMap.put(zoomOut, new ActionHandler(e -> textZoom(-1)));
component.addMouseWheelListener(e -> {
if (e.getModifiersEx() == UiUtils.ctrlButton()) {
textZoom(e.getWheelRotation() < 0 ? 1 : -1);
e.consume();
} else {
// pass event to parent component, needed for scroll in JScrollPane
Container parent = component.getParent();
if (parent != null) {
parent.dispatchEvent(e);
}
}
});
}
private void textZoom(int change) {
FontSettings fontSettings = settings.getFontSettings();
FontAdapter fontAdapter;
if (component instanceof SmaliArea) {
fontAdapter = fontSettings.getSmaliFontAdapter();
} else {
fontAdapter = fontSettings.getCodeFontAdapter();
}
fontAdapter.setFont(changeFontSize(fontAdapter.getFont(), change));
settings.sync();
update.run();
}
private Font changeFontSize(Font font, int change) {
float newSize = font.getSize() + change;
if (newSize < 2) {
// ignore change
return font;
}
return font.deriveFont(newSize);
}
}
| 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/utils/ui/DocumentUpdateListener.java | jadx-gui/src/main/java/jadx/gui/utils/ui/DocumentUpdateListener.java | package jadx.gui.utils.ui;
import java.util.function.Consumer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DocumentUpdateListener implements DocumentListener {
private final Consumer<DocumentEvent> listener;
public DocumentUpdateListener(Consumer<DocumentEvent> listener) {
this.listener = listener;
}
@Override
public void insertUpdate(DocumentEvent event) {
this.listener.accept(event);
}
@Override
public void removeUpdate(DocumentEvent event) {
this.listener.accept(event);
}
@Override
public void changedUpdate(DocumentEvent event) {
// ignore attributes change
}
}
| 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/utils/ui/SimpleMenuItem.java | jadx-gui/src/main/java/jadx/gui/utils/ui/SimpleMenuItem.java | package jadx.gui.utils.ui;
import javax.swing.JMenuItem;
public class SimpleMenuItem extends JMenuItem {
public SimpleMenuItem(String text, Runnable action) {
super(text);
addActionListener(ev -> action.run());
}
}
| 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/utils/ui/MousePressedHandler.java | jadx-gui/src/main/java/jadx/gui/utils/ui/MousePressedHandler.java | package jadx.gui.utils.ui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.function.Consumer;
public class MousePressedHandler extends MouseAdapter {
private final Consumer<MouseEvent> listener;
public MousePressedHandler(Consumer<MouseEvent> listener) {
this.listener = listener;
}
@Override
public void mousePressed(MouseEvent ev) {
listener.accept(ev);
}
}
| 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/utils/ui/NodeLabel.java | jadx-gui/src/main/java/jadx/gui/utils/ui/NodeLabel.java | package jadx.gui.utils.ui;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import jadx.gui.treemodel.JNode;
public class NodeLabel extends JLabel {
public static NodeLabel longName(JNode node) {
NodeLabel label = new NodeLabel(node.makeLongStringHtml(), node.disableHtml());
label.setIcon(node.getIcon());
label.setHorizontalAlignment(SwingConstants.LEFT);
return label;
}
public static NodeLabel noHtml(String label) {
return new NodeLabel(label, true);
}
public static void disableHtml(JLabel label, boolean disable) {
label.putClientProperty("html.disable", disable);
}
private boolean htmlDisabled = false;
public NodeLabel() {
disableHtml(true);
}
public NodeLabel(String label) {
disableHtml(true);
setText(label);
}
public NodeLabel(String label, boolean disableHtml) {
disableHtml(disableHtml);
setText(label);
}
public void disableHtml(boolean disable) {
if (htmlDisabled != disable) {
htmlDisabled = disable;
disableHtml(this, disable);
}
}
}
| 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/utils/ui/FileOpenerHelper.java | jadx-gui/src/main/java/jadx/gui/utils/ui/FileOpenerHelper.java | package jadx.gui.utils.ui;
import java.awt.Desktop;
import java.awt.Frame;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ResourceFile;
import jadx.api.ResourcesLoader;
import jadx.core.plugins.files.TempFilesGetter;
import jadx.gui.treemodel.JResource;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
public class FileOpenerHelper {
private static final Logger LOG = LoggerFactory.getLogger(FileOpenerHelper.class);
public static void exportBinary(JResource resource, Path savePath) {
try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(savePath.toFile()))) {
byte[] bytes = ResourcesLoader.decodeStream(resource.getResFile(), (size, is) -> is.readAllBytes());
if (bytes == null) {
bytes = new byte[0];
}
os.write(bytes);
} catch (Exception e) {
throw new RuntimeException("Error saving file " + resource.getName(), e);
}
}
public static void openFile(Frame frame, JResource res) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
Path tempDir = TempFilesGetter.INSTANCE.getTempDir();
ResourceFile resFile = res.getResFile();
Path path = Paths.get(resFile.getDeobfName());
Path fileNamePath = path.getFileName();
Path filePath = tempDir.resolve(fileNamePath);
exportBinary(res, filePath);
if (!Files.exists(filePath)) {
UiUtils.errorMessage(frame, NLS.str("error_dialog.not_found_file", filePath));
return;
}
if (Files.isDirectory(filePath)) {
UiUtils.errorMessage(frame, NLS.str("error_dialog.path_is_directory", filePath));
return;
}
if (!Files.isReadable(filePath)) {
UiUtils.errorMessage(frame, NLS.str("error_dialog.cannot_read", filePath));
return;
}
try {
desktop.open(filePath.toFile());
} catch (IOException ex) {
UiUtils.errorMessage(frame, NLS.str("error_dialog.open_failed", ex.getMessage()));
LOG.error("Unable to open file: {0}", ex);
} catch (IllegalArgumentException ex) {
UiUtils.errorMessage(frame, NLS.str("error_dialog.invalid_path_format", ex.getMessage()));
LOG.error("Invalid file path: {0}", ex);
}
} else {
UiUtils.errorMessage(frame, NLS.str("error_dialog.desktop_unsupported"));
}
}
}
| 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/plugins/mappings/JInputMapping.java | jadx-gui/src/main/java/jadx/gui/plugins/mappings/JInputMapping.java | package jadx.gui.plugins.mappings;
import java.nio.file.Path;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JPopupMenu;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.api.impl.SimpleCodeInfo;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.core.utils.files.FileUtils;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JEditableNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.codearea.CodeContentPanel;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.tab.TabbedPane;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.SimpleMenuItem;
public class JInputMapping extends JEditableNode {
private static final Logger LOG = LoggerFactory.getLogger(JInputMapping.class);
private static final ImageIcon MAPPING_ICON = UiUtils.openSvgIcon("nodes/abbreviatePackageNames");
private final Path mappingPath;
private final String name;
public JInputMapping(Path mappingPath) {
this.mappingPath = mappingPath;
this.name = mappingPath.getFileName().toString();
}
@Override
public boolean hasContent() {
return true;
}
@Override
public ContentPanel getContentPanel(TabbedPane tabbedPane) {
return new CodeContentPanel(tabbedPane, this);
}
@Override
public @NotNull ICodeInfo getCodeInfo() {
try {
return new SimpleCodeInfo(FileUtils.readFile(mappingPath));
} catch (Exception e) {
throw new JadxRuntimeException("Failed to read mapping file: " + mappingPath.toAbsolutePath(), e);
}
}
@Override
public void save(String newContent) {
try {
FileUtils.writeFile(mappingPath, newContent);
LOG.debug("Mapping saved: {}", mappingPath.toAbsolutePath());
} catch (Exception e) {
throw new JadxRuntimeException("Failed to write mapping file: " + mappingPath.toAbsolutePath(), e);
}
}
@Override
public JPopupMenu onTreePopupMenu(MainWindow mainWindow) {
JPopupMenu menu = new JPopupMenu();
menu.add(new SimpleMenuItem(NLS.str("popup.remove"),
() -> mainWindow.getRenameMappings().closeMappingsAndRemoveFromProject()));
return menu;
}
@Override
public String getSyntaxName() {
return SyntaxConstants.SYNTAX_STYLE_NONE;
}
@Override
public JClass getJParent() {
return null;
}
@Override
public Icon getIcon() {
return MAPPING_ICON;
}
@Override
public String getName() {
return name;
}
@Override
public String makeString() {
return name;
}
@Override
public String getTooltip() {
return mappingPath.normalize().toAbsolutePath().toString();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/plugins/mappings/RenameMappingsGui.java | jadx-gui/src/main/java/jadx/gui/plugins/mappings/RenameMappingsGui.java | package jadx.gui.plugins.mappings;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
import java.util.stream.Stream;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.fabricmc.mappingio.MappingReader;
import net.fabricmc.mappingio.format.MappingFormat;
import jadx.api.args.UserRenamesMappingsMode;
import jadx.api.plugins.utils.CommonFileUtils;
import jadx.core.dex.nodes.RootNode;
import jadx.core.utils.Utils;
import jadx.gui.jobs.TaskStatus;
import jadx.gui.settings.JadxProject;
import jadx.gui.settings.JadxSettings;
import jadx.gui.treemodel.JNode;
import jadx.gui.treemodel.JRoot;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.filedialog.FileDialogWrapper;
import jadx.gui.ui.filedialog.FileOpenMode;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.tab.TabbedPane;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.ActionHandler;
import jadx.plugins.mappings.RenameMappingsOptions;
import jadx.plugins.mappings.save.MappingExporter;
public class RenameMappingsGui {
private static final Logger LOG = LoggerFactory.getLogger(RenameMappingsGui.class);
private final MainWindow mainWindow;
private boolean renamesChanged = false;
private JInputMapping mappingNode;
private transient JMenu openMappingsMenu;
private transient Action saveMappingsAction;
private transient JMenu saveMappingsAsMenu;
private transient Action closeMappingsAction;
public RenameMappingsGui(MainWindow mainWindow) {
this.mainWindow = mainWindow;
mainWindow.addLoadListener(this::onLoad);
mainWindow.addTreeUpdateListener(this::treeUpdate);
}
public void addMenuActions(JMenu menu) {
openMappingsMenu = new JMenu(NLS.str("file.open_mappings"));
openMappingsMenu.add(new ActionHandler(ev -> openMappings(MappingFormat.PROGUARD_FILE, true))
.withNameAndDesc("Proguard (inverted)"));
openMappingsMenu.add(new ActionHandler(ev -> openMappings(MappingFormat.PROGUARD_FILE, false)).withNameAndDesc("Proguard"));
saveMappingsAction = new ActionHandler(this::saveMappings).withNameAndDesc(NLS.str("file.save_mappings"));
saveMappingsAsMenu = new JMenu(NLS.str("file.save_mappings_as"));
for (MappingFormat mappingFormat : MappingFormat.values()) {
if (mappingFormat != MappingFormat.PROGUARD_FILE) {
openMappingsMenu.add(new ActionHandler(ev -> openMappings(mappingFormat, false))
.withNameAndDesc(mappingFormat.name));
}
saveMappingsAsMenu.add(new ActionHandler(ev -> saveMappingsAs(mappingFormat))
.withNameAndDesc(mappingFormat.name));
}
closeMappingsAction = new ActionHandler(ev -> closeMappingsAndRemoveFromProject())
.withNameAndDesc(NLS.str("file.close_mappings"));
menu.addSeparator();
menu.add(openMappingsMenu);
menu.add(saveMappingsAction);
menu.add(saveMappingsAsMenu);
menu.add(closeMappingsAction);
}
private boolean onLoad(boolean loaded) {
renamesChanged = false;
mappingNode = null;
if (loaded) {
RootNode rootNode = mainWindow.getWrapper().getRootNode();
rootNode.registerCodeDataUpdateListener(codeData -> onRename());
} else {
// project or window close
JadxProject project = mainWindow.getProject();
JadxSettings settings = mainWindow.getSettings();
if (project.getMappingsPath() != null
&& settings.getUserRenamesMappingsMode() == UserRenamesMappingsMode.READ_AND_AUTOSAVE_BEFORE_CLOSING) {
saveMappings();
}
}
return false;
}
private void onRename() {
JadxProject project = mainWindow.getProject();
JadxSettings settings = mainWindow.getSettings();
if (project.getMappingsPath() != null
&& settings.getUserRenamesMappingsMode() == UserRenamesMappingsMode.READ_AND_AUTOSAVE_EVERY_CHANGE) {
saveMappings();
} else {
renamesChanged = true;
UiUtils.uiRun(mainWindow::update);
}
}
public void onUpdate(boolean loaded) {
JadxProject project = mainWindow.getProject();
openMappingsMenu.setEnabled(loaded);
saveMappingsAction.setEnabled(loaded && renamesChanged && project.getMappingsPath() != null);
saveMappingsAsMenu.setEnabled(loaded);
closeMappingsAction.setEnabled(project.getMappingsPath() != null);
}
private void treeUpdate(JRoot treeRoot) {
if (mappingNode != null) {
// already added
return;
}
Path mappingsPath = mainWindow.getProject().getMappingsPath();
if (mappingsPath == null) {
return;
}
JNode node = treeRoot.followStaticPath("JInputs");
JNode currentNode = node.removeNode(n -> n.getClass().equals(JInputMapping.class));
if (currentNode != null) {
// close opened tab
TabbedPane tabbedPane = mainWindow.getTabbedPane();
ContentPanel openedTab = tabbedPane.getTabByNode(currentNode);
if (openedTab != null) {
tabbedPane.closeCodePanel(openedTab);
}
}
mappingNode = new JInputMapping(mappingsPath);
node.add(mappingNode);
}
private void openMappings(MappingFormat mappingFormat, boolean inverted) {
FileDialogWrapper fileDialog = new FileDialogWrapper(mainWindow, FileOpenMode.CUSTOM_OPEN);
fileDialog.setTitle(NLS.str("file.open_mappings"));
if (mappingFormat.hasSingleFile()) {
fileDialog.setFileExtList(Collections.singletonList(mappingFormat.fileExt));
fileDialog.setSelectionMode(JFileChooser.FILES_ONLY);
} else {
fileDialog.setSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
List<Path> selectedPaths = fileDialog.show();
if (selectedPaths.size() != 1) {
return;
}
Path filePath = selectedPaths.get(0);
LOG.info("Loading mappings from: {}", filePath.toAbsolutePath());
JadxProject project = mainWindow.getProject();
project.setMappingsPath(filePath);
project.updatePluginOptions(options -> {
options.put(RenameMappingsOptions.FORMAT_OPT, mappingFormat.name());
options.put(RenameMappingsOptions.INVERT_OPT, inverted ? "yes" : "no");
});
mainWindow.reopen();
}
public void closeMappingsAndRemoveFromProject() {
mainWindow.getProject().setMappingsPath(null);
mainWindow.reopen();
}
private void saveMappings() {
renamesChanged = false;
saveInBackground(getCurrentMappingFormat(),
mainWindow.getProject().getMappingsPath(),
s -> mainWindow.update());
}
private void saveMappingsAs(MappingFormat mappingFormat) {
FileDialogWrapper fileDialog = new FileDialogWrapper(mainWindow, FileOpenMode.CUSTOM_SAVE);
fileDialog.setTitle(NLS.str("file.save_mappings_as"));
if (mappingFormat.hasSingleFile()) {
Path currentDir = Utils.getOrElse(fileDialog.getCurrentDir(), CommonFileUtils.CWD_PATH);
fileDialog.setSelectedFile(currentDir.resolve("mappings." + mappingFormat.fileExt));
fileDialog.setFileExtList(Collections.singletonList(mappingFormat.fileExt));
fileDialog.setSelectionMode(JFileChooser.FILES_ONLY);
} else {
fileDialog.setSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
List<Path> selectedPaths = fileDialog.show();
if (selectedPaths.size() != 1) {
return;
}
Path selectedPath = selectedPaths.get(0);
Path savePath;
// Append file extension if missing
if (mappingFormat.hasSingleFile()
&& !selectedPath.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(mappingFormat.fileExt)) {
savePath = selectedPath.resolveSibling(selectedPath.getFileName() + "." + mappingFormat.fileExt);
} else {
savePath = selectedPath;
}
// If the target file already exists (and it's not an empty directory), show an overwrite
// confirmation
if (Files.exists(savePath)) {
boolean emptyDir = false;
try (Stream<Path> entries = Files.list(savePath)) {
emptyDir = entries.findFirst().isEmpty();
} catch (IOException ignored) {
}
if (!emptyDir) {
int res = JOptionPane.showConfirmDialog(
mainWindow,
NLS.str("confirm.save_as_message", savePath.getFileName()),
NLS.str("confirm.save_as_title"),
JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.NO_OPTION) {
return;
}
}
}
LOG.info("Saving mappings to: {}", savePath.toAbsolutePath());
JadxProject project = mainWindow.getProject();
project.setMappingsPath(savePath);
project.updatePluginOptions(options -> {
options.put(RenameMappingsOptions.FORMAT_OPT, mappingFormat.name());
options.put(RenameMappingsOptions.INVERT_OPT, "no");
});
saveInBackground(mappingFormat, savePath, s -> {
mappingNode = null;
mainWindow.reloadTree();
});
}
private void saveInBackground(MappingFormat mappingFormat, Path savePath, Consumer<TaskStatus> onFinishUiRunnable) {
mainWindow.getBackgroundExecutor().execute(NLS.str("progress.save_mappings"),
() -> new MappingExporter(mainWindow.getWrapper().getRootNode())
.exportMappings(savePath, mainWindow.getProject().getCodeData(), mappingFormat),
onFinishUiRunnable);
}
private MappingFormat getCurrentMappingFormat() {
JadxProject project = mainWindow.getProject();
String fmtStr = project.getPluginOption(RenameMappingsOptions.FORMAT_OPT);
if (fmtStr != null) {
return MappingFormat.valueOf(fmtStr);
}
Path mappingsPath = project.getMappingsPath();
try {
return MappingReader.detectFormat(mappingsPath);
} catch (IOException e) {
throw new RuntimeException("Failed to detect mapping format for: " + mappingsPath);
}
}
}
| 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/plugins/script/ScriptCompleteProvider.java | jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptCompleteProvider.java | package jadx.gui.plugins.script;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.swing.Icon;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.CompletionProviderBase;
import org.fife.ui.autocomplete.ParameterizedCompletion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kotlin.script.experimental.api.ScriptDiagnostic;
import kotlin.script.experimental.api.SourceCode;
import kotlin.script.experimental.api.SourceCodeCompletionVariant;
import jadx.core.utils.ListUtils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.ui.codearea.AbstractCodeArea;
import jadx.gui.utils.Icons;
import jadx.plugins.script.ide.ScriptCompletionResult;
import jadx.plugins.script.ide.ScriptServices;
import static jadx.plugins.script.ide.ScriptServicesKt.AUTO_COMPLETE_INSERT_STR;
public class ScriptCompleteProvider extends CompletionProviderBase {
private static final Logger LOG = LoggerFactory.getLogger(ScriptCompleteProvider.class);
private static final Map<String, Icon> ICONS_MAP = buildIconsMap();
private static Map<String, Icon> buildIconsMap() {
Map<String, Icon> map = new HashMap<>();
map.put("class", Icons.CLASS);
map.put("method", Icons.METHOD);
map.put("field", Icons.FIELD);
map.put("property", Icons.PROPERTY);
map.put("parameter", Icons.PARAMETER);
map.put("package", Icons.PACKAGE);
return map;
}
private final AbstractCodeArea codeArea;
private ScriptServices scriptServices;
public ScriptCompleteProvider(AbstractCodeArea codeArea) {
this.codeArea = codeArea;
}
private List<Completion> getCompletions() {
try {
String code = codeArea.getText();
int caretPos = codeArea.getCaretPosition();
// TODO: resolve error after reusing ScriptCompiler
scriptServices = new ScriptServices();
String scriptName = codeArea.getNode().getName();
ScriptCompletionResult result = scriptServices.complete(scriptName, code, caretPos);
int replacePos = getReplacePos(caretPos, result);
if (!result.getReports().isEmpty()) {
LOG.debug("Script completion reports: {}", result.getReports());
}
return convertCompletions(result.getCompletions(), code, replacePos);
} catch (Exception e) {
LOG.error("Code completion failed", e);
return Collections.emptyList();
}
}
private List<Completion> convertCompletions(List<SourceCodeCompletionVariant> completions, String code, int replacePos) {
if (completions.isEmpty()) {
return Collections.emptyList();
}
if (LOG.isDebugEnabled()) {
String cmplStr = completions.stream().map(SourceCodeCompletionVariant::toString).collect(Collectors.joining("\n"));
LOG.debug("Completions:\n{}", cmplStr);
}
int count = completions.size();
List<Completion> list = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
SourceCodeCompletionVariant c = completions.get(i);
if (Objects.equals(c.getIcon(), "keyword")) {
// too many, not very useful
continue;
}
ScriptCompletionData cmpl = new ScriptCompletionData(this, count - i);
cmpl.setData(c.getText(), code, replacePos);
if (Objects.equals(c.getIcon(), "method") && !Objects.equals(c.getText(), c.getDisplayText())) {
// add method args details for methods
cmpl.setSummary(c.getDisplayText() + " " + c.getTail());
} else {
cmpl.setSummary(c.getTail());
}
cmpl.setToolTip(c.getDisplayText());
Icon icon = ICONS_MAP.get(c.getIcon());
cmpl.setIcon(icon != null ? icon : Icons.FILE);
list.add(cmpl);
}
return list;
}
private int getReplacePos(int caretPos, ScriptCompletionResult result) throws BadLocationException {
int lineRaw = codeArea.getLineOfOffset(caretPos);
int lineStart = codeArea.getLineStartOffset(lineRaw);
int line = lineRaw + 1;
int col = caretPos - lineStart + 1;
List<ScriptDiagnostic> reports = result.getReports();
ScriptDiagnostic cmplReport = ListUtils.filterOnlyOne(reports, r -> {
if (r.getSeverity() == ScriptDiagnostic.Severity.ERROR && r.getLocation() != null) {
SourceCode.Position start = r.getLocation().getStart();
return start.getLine() == line && r.getMessage().endsWith(AUTO_COMPLETE_INSERT_STR);
}
return false;
});
if (cmplReport == null) {
LOG.warn("Failed to find completion report in: {}", reports);
return caretPos;
}
reports.remove(cmplReport);
int reportCol = Objects.requireNonNull(cmplReport.getLocation()).getStart().getCol();
return caretPos - (col - reportCol);
}
@Override
public String getAlreadyEnteredText(JTextComponent comp) {
try {
int pos = codeArea.getCaretPosition();
return codeArea.getText(0, pos);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to get text before caret", e);
}
}
@Override
public List<Completion> getCompletionsAt(JTextComponent comp, Point p) {
return getCompletions();
}
@Override
protected List<Completion> getCompletionsImpl(JTextComponent comp) {
return getCompletions();
}
@Override
public List<ParameterizedCompletion> getParameterizedCompletions(JTextComponent tc) {
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/plugins/script/ScriptCompletionData.java | jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptCompletionData.java | package jadx.gui.plugins.script;
import javax.swing.Icon;
import javax.swing.text.JTextComponent;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.CompletionProvider;
public class ScriptCompletionData implements Completion {
private final CompletionProvider provider;
private final int relevance;
private String input;
private String code;
private int replacePos;
private Icon icon;
private String summary;
private String toolTip;
public ScriptCompletionData(CompletionProvider provider, int relevance) {
this.provider = provider;
this.relevance = relevance;
}
public void setData(String input, String code, int replacePos) {
this.input = input;
this.code = code;
this.replacePos = replacePos;
}
@Override
public String getInputText() {
return input;
}
@Override
public CompletionProvider getProvider() {
return provider;
}
@Override
public String getAlreadyEntered(JTextComponent comp) {
return provider.getAlreadyEnteredText(comp);
}
@Override
public int getRelevance() {
return relevance;
}
@Override
public String getReplacementText() {
return code.substring(0, replacePos) + input;
}
@Override
public Icon getIcon() {
return icon;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
@Override
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
@Override
public String getToolTipText() {
return toolTip;
}
public void setToolTip(String toolTip) {
this.toolTip = toolTip;
}
@Override
public int compareTo(Completion other) {
return Integer.compare(relevance, other.getRelevance());
}
@Override
public String toString() {
return input;
}
}
| 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/plugins/script/ScriptCodeArea.java | jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptCodeArea.java | package jadx.gui.plugins.script;
import org.fife.ui.autocomplete.AutoCompletion;
import org.jetbrains.annotations.NotNull;
import jadx.api.ICodeInfo;
import jadx.gui.jobs.IBackgroundTask;
import jadx.gui.jobs.LoadTask;
import jadx.gui.settings.JadxSettings;
import jadx.gui.treemodel.JInputScript;
import jadx.gui.ui.action.JadxAutoCompletion;
import jadx.gui.ui.codearea.AbstractCodeArea;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.utils.shortcut.ShortcutsController;
public class ScriptCodeArea extends AbstractCodeArea {
private final JInputScript scriptNode;
private final AutoCompletion autoCompletion;
private final ShortcutsController shortcutsController;
public ScriptCodeArea(ContentPanel contentPanel, JInputScript node) {
super(contentPanel, node);
scriptNode = node;
setSyntaxEditingStyle(node.getSyntaxName());
setCodeFoldingEnabled(true);
setCloseCurlyBraces(true);
shortcutsController = contentPanel.getMainWindow().getShortcutsController();
JadxSettings settings = contentPanel.getMainWindow().getSettings();
autoCompletion = addAutoComplete(settings);
}
private AutoCompletion addAutoComplete(JadxSettings settings) {
ScriptCompleteProvider provider = new ScriptCompleteProvider(this);
provider.setAutoActivationRules(false, ".");
JadxAutoCompletion ac = new JadxAutoCompletion(provider);
ac.setListCellRenderer(new ScriptCompletionRenderer(settings));
ac.setAutoActivationEnabled(true);
ac.setAutoCompleteSingleChoices(true);
ac.install(this);
shortcutsController.bindImmediate(ac);
return ac;
}
@Override
public @NotNull ICodeInfo getCodeInfo() {
return node.getCodeInfo();
}
@Override
public IBackgroundTask getLoadTask() {
return new LoadTask<>(
() -> node.getCodeInfo().getCodeStr(),
code -> {
setText(code);
setCaretPosition(0);
setLoaded();
});
}
@Override
public void refresh() {
setText(node.getCodeInfo().getCodeStr());
}
public void updateCode(String newCode) {
int caretPos = getCaretPosition();
setText(newCode);
setCaretPosition(caretPos);
scriptNode.setChanged(true);
}
public void save() {
scriptNode.save(getText());
scriptNode.setChanged(false);
}
public JInputScript getScriptNode() {
return scriptNode;
}
@Override
public void dispose() {
shortcutsController.unbindActionsForComponent(this);
autoCompletion.uninstall();
super.dispose();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptErrorService.java | jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptErrorService.java | package jadx.gui.plugins.script;
import java.util.List;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.parser.AbstractParser;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParseResult;
import org.fife.ui.rsyntaxtextarea.parser.DefaultParserNotice;
import org.fife.ui.rsyntaxtextarea.parser.ParseResult;
import org.fife.ui.rsyntaxtextarea.parser.ParserNotice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kotlin.script.experimental.api.ScriptDiagnostic;
import kotlin.script.experimental.api.SourceCode;
public class ScriptErrorService extends AbstractParser {
private static final Logger LOG = LoggerFactory.getLogger(ScriptErrorService.class);
private final DefaultParseResult result;
private final ScriptCodeArea scriptArea;
public ScriptErrorService(ScriptCodeArea scriptArea) {
this.scriptArea = scriptArea;
this.result = new DefaultParseResult(this);
}
@Override
public ParseResult parse(RSyntaxDocument doc, String style) {
return result;
}
public void clearErrors() {
result.clearNotices();
scriptArea.removeParser(this);
}
public void apply() {
scriptArea.removeParser(this);
scriptArea.addParser(this);
scriptArea.addNotify();
scriptArea.requestFocus();
jumpCaretToFirstError();
}
private void jumpCaretToFirstError() {
List<ParserNotice> parserNotices = result.getNotices();
if (parserNotices.isEmpty()) {
return;
}
ParserNotice notice = parserNotices.get(0);
int offset = notice.getOffset();
if (offset == -1) {
try {
offset = scriptArea.getLineStartOffset(notice.getLine());
} catch (Exception e) {
LOG.error("Failed to jump to first error", e);
return;
}
}
scriptArea.scrollToPos(offset);
}
public void addCompilerIssues(List<ScriptDiagnostic> issues) {
for (ScriptDiagnostic issue : issues) {
if (issue.getSeverity() == ScriptDiagnostic.Severity.DEBUG) {
continue;
}
DefaultParserNotice notice;
SourceCode.Location loc = issue.getLocation();
if (loc == null) {
notice = new DefaultParserNotice(this, issue.getMessage(), 0);
} else {
try {
int line = loc.getStart().getLine();
int offset = scriptArea.getLineStartOffset(line - 1) + loc.getStart().getCol();
int len = loc.getEnd() == null ? -1 : loc.getEnd().getCol() - loc.getStart().getCol();
notice = new DefaultParserNotice(this, issue.getMessage(), line, offset - 1, len);
notice.setLevel(convertLevel(issue.getSeverity()));
} catch (Exception e) {
LOG.error("Failed to convert script issue", e);
continue;
}
}
addNotice(notice);
}
}
private static ParserNotice.Level convertLevel(ScriptDiagnostic.Severity severity) {
switch (severity) {
case FATAL:
case ERROR:
return ParserNotice.Level.ERROR;
case WARNING:
return ParserNotice.Level.WARNING;
case INFO:
case DEBUG:
return ParserNotice.Level.INFO;
}
return ParserNotice.Level.ERROR;
}
public void addLintErrors(List<JadxLintError> errors) {
for (JadxLintError error : errors) {
try {
int line = error.getLine();
int offset = scriptArea.getLineStartOffset(line - 1) + error.getCol() - 1;
String word = scriptArea.getWordByPosition(offset);
int len = word != null ? word.length() : -1;
DefaultParserNotice notice = new DefaultParserNotice(this, error.getDetail(), line, offset, len);
notice.setLevel(ParserNotice.Level.WARNING);
addNotice(notice);
} catch (Exception e) {
LOG.error("Failed to convert lint error", e);
}
}
}
private void addNotice(DefaultParserNotice notice) {
LOG.debug("Add notice: {}:{}:{} - {}",
notice.getLine(), notice.getOffset(), notice.getLength(), notice.getMessage());
result.addNotice(notice);
}
}
| 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/plugins/script/ScriptContentPanel.java | jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptContentPanel.java | package jadx.gui.plugins.script;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.util.Collections;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import org.fife.ui.rsyntaxtextarea.ErrorStrip;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import kotlin.script.experimental.api.ScriptDiagnostic;
import kotlin.script.experimental.api.ScriptDiagnostic.Severity;
import jadx.gui.logs.LogOptions;
import jadx.gui.settings.JadxSettings;
import jadx.gui.settings.LineNumbersMode;
import jadx.gui.treemodel.JInputScript;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.action.ActionModel;
import jadx.gui.ui.action.JadxGuiAction;
import jadx.gui.ui.codearea.AbstractCodeArea;
import jadx.gui.ui.codearea.AbstractCodeContentPanel;
import jadx.gui.ui.codearea.SearchBar;
import jadx.gui.ui.tab.TabbedPane;
import jadx.gui.utils.Icons;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.NodeLabel;
import jadx.plugins.script.ide.ScriptAnalyzeResult;
import jadx.plugins.script.ide.ScriptServices;
import static jadx.plugins.script.runtime.ScriptRuntime.JADX_SCRIPT_LOG_PREFIX;
public class ScriptContentPanel extends AbstractCodeContentPanel {
private static final long serialVersionUID = 6575696321112417513L;
private final ScriptCodeArea scriptArea;
private final SearchBar searchBar;
private final RTextScrollPane codeScrollPane;
private final JPanel actionPanel;
private final JLabel resultLabel;
private final ScriptErrorService errorService;
private final Logger scriptLog;
public ScriptContentPanel(TabbedPane panel, JInputScript scriptNode) {
super(panel, scriptNode);
scriptArea = new ScriptCodeArea(this, scriptNode);
resultLabel = new NodeLabel("");
errorService = new ScriptErrorService(scriptArea);
actionPanel = buildScriptActionsPanel();
searchBar = new SearchBar(scriptArea);
codeScrollPane = new RTextScrollPane(scriptArea);
scriptLog = LoggerFactory.getLogger(JADX_SCRIPT_LOG_PREFIX + scriptNode.getName());
initUI();
applySettings();
scriptArea.load();
}
private void initUI() {
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
topPanel.add(actionPanel, BorderLayout.NORTH);
topPanel.add(searchBar, BorderLayout.SOUTH);
JPanel codePanel = new JPanel(new BorderLayout());
codePanel.setBorder(new EmptyBorder(0, 0, 0, 0));
codePanel.add(codeScrollPane);
codePanel.add(new ErrorStrip(scriptArea), BorderLayout.LINE_END);
setLayout(new BorderLayout());
setBorder(new EmptyBorder(0, 0, 0, 0));
add(topPanel, BorderLayout.NORTH);
add(codeScrollPane, BorderLayout.CENTER);
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_F, UiUtils.ctrlButton());
UiUtils.addKeyBinding(scriptArea, key, "SearchAction", searchBar::toggle);
}
private JPanel buildScriptActionsPanel() {
JadxGuiAction runAction = new JadxGuiAction(ActionModel.SCRIPT_RUN, this::runScript);
JadxGuiAction saveAction = new JadxGuiAction(ActionModel.SCRIPT_SAVE, scriptArea::save);
runAction.setShortcutComponent(scriptArea);
saveAction.setShortcutComponent(scriptArea);
tabbedPane.getMainWindow().getShortcutsController().bindImmediate(runAction);
tabbedPane.getMainWindow().getShortcutsController().bindImmediate(saveAction);
JButton save = saveAction.makeButton();
scriptArea.getScriptNode().addChangeListener(save::setEnabled);
JButton check = new JButton(NLS.str("script.check"), Icons.CHECK);
check.addActionListener(ev -> checkScript());
JButton format = new JButton(NLS.str("script.format"), Icons.FORMAT);
format.addActionListener(ev -> reformatCode());
JButton scriptLog = new JButton(NLS.str("script.log"), Icons.FORMAT);
scriptLog.addActionListener(ev -> showScriptLog());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.setBorder(new EmptyBorder(0, 0, 0, 0));
panel.add(runAction.makeButton());
panel.add(Box.createRigidArea(new Dimension(10, 0)));
panel.add(save);
panel.add(Box.createRigidArea(new Dimension(10, 0)));
panel.add(check);
panel.add(Box.createRigidArea(new Dimension(10, 0)));
panel.add(format);
panel.add(Box.createRigidArea(new Dimension(30, 0)));
panel.add(resultLabel);
panel.add(Box.createHorizontalGlue());
panel.add(scriptLog);
return panel;
}
private void runScript() {
scriptArea.save();
if (!checkScript()) {
return;
}
resetResultLabel();
TabbedPane tabbedPane = getTabbedPane();
MainWindow mainWindow = tabbedPane.getMainWindow();
mainWindow.getBackgroundExecutor().execute(NLS.str("script.run"), () -> {
try {
mainWindow.getWrapper().reloadPasses();
} catch (Exception e) {
scriptLog.error("Passes reload failed", e);
}
}, taskStatus -> {
mainWindow.passesReloaded();
});
}
private boolean checkScript() {
try {
resetResultLabel();
String code = scriptArea.getText();
String fileName = scriptArea.getNode().getName();
ScriptServices scriptServices = new ScriptServices();
ScriptAnalyzeResult result = scriptServices.analyze(fileName, code);
boolean success = result.getSuccess();
List<ScriptDiagnostic> issues = result.getIssues();
for (ScriptDiagnostic issue : issues) {
Severity severity = issue.getSeverity();
if (severity == Severity.ERROR || severity == Severity.FATAL) {
scriptLog.error("{}", issue.render(false, true, true, true));
success = false;
} else if (severity == Severity.WARNING) {
scriptLog.warn("Compile issue: {}", issue);
}
}
List<JadxLintError> lintErrs = Collections.emptyList();
if (success) {
lintErrs = getLintIssues(code);
}
errorService.clearErrors();
errorService.addCompilerIssues(issues);
errorService.addLintErrors(lintErrs);
if (!success) {
resultLabel.setText("Compile issues: " + issues.size());
showScriptLog();
} else if (!lintErrs.isEmpty()) {
resultLabel.setText("Lint issues: " + lintErrs.size());
} else {
resultLabel.setText("OK");
}
errorService.apply();
return success;
} catch (Throwable e) {
scriptLog.error("Failed to check code", e);
return true;
}
}
private List<JadxLintError> getLintIssues(String code) {
try {
List<JadxLintError> lintErrs = KtLintUtils.INSTANCE.lint(code);
for (JadxLintError error : lintErrs) {
scriptLog.warn("Lint issue: {} ({}:{})(ruleId={})",
error.getDetail(), error.getLine(), error.getCol(), error.getRuleId());
}
return lintErrs;
} catch (Throwable e) { // can throw initialization error
scriptLog.warn("KtLint failed", e);
return Collections.emptyList();
}
}
private void reformatCode() {
resetResultLabel();
try {
String code = scriptArea.getText();
String formattedCode = KtLintUtils.INSTANCE.format(code);
if (!code.equals(formattedCode)) {
scriptArea.updateCode(formattedCode);
resultLabel.setText("Code updated");
errorService.clearErrors();
}
} catch (Throwable e) { // can throw initialization error
scriptLog.error("Failed to reformat code", e);
}
}
private void resetResultLabel() {
resultLabel.setText("");
}
private void applySettings() {
JadxSettings settings = getSettings();
codeScrollPane.setLineNumbersEnabled(settings.getLineNumbersMode() != LineNumbersMode.DISABLE);
codeScrollPane.getGutter().setLineNumberFont(settings.getCodeFont());
scriptArea.loadSettings();
}
private void showScriptLog() {
getMainWindow().showLogViewer(LogOptions.forScript(getNode().getName()));
}
@Override
public AbstractCodeArea getCodeArea() {
return scriptArea;
}
@Override
public Component getChildrenComponent() {
return getCodeArea();
}
@Override
public void loadSettings() {
applySettings();
updateUI();
}
public void dispose() {
scriptArea.dispose();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptCompletionRenderer.java | jadx-gui/src/main/java/jadx/gui/plugins/script/ScriptCompletionRenderer.java | package jadx.gui.plugins.script;
import javax.swing.JList;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.CompletionCellRenderer;
import jadx.gui.settings.JadxSettings;
import static jadx.gui.utils.UiUtils.escapeHtml;
import static jadx.gui.utils.UiUtils.fadeHtml;
import static jadx.gui.utils.UiUtils.wrapHtml;
public class ScriptCompletionRenderer extends CompletionCellRenderer {
public ScriptCompletionRenderer(JadxSettings settings) {
setDisplayFont(settings.getCodeFont());
}
@Override
protected void prepareForOtherCompletion(JList list, Completion c, int index, boolean selected, boolean hasFocus) {
ScriptCompletionData cmpl = (ScriptCompletionData) c;
setText(wrapHtml(escapeHtml(cmpl.getInputText()) + " "
+ fadeHtml(escapeHtml(cmpl.getSummary()))));
}
}
| 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/plugins/quark/QuarkDialog.java | jadx-gui/src/main/java/jadx/gui/plugins/quark/QuarkDialog.java | package jadx.gui.plugins.quark;
import java.awt.BorderLayout;
import java.awt.Container;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.gui.settings.JadxSettings;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.UiUtils;
import jadx.gui.utils.ui.NodeLabel;
public class QuarkDialog extends JDialog {
private static final long serialVersionUID = 4855753773520368215L;
private static final Logger LOG = LoggerFactory.getLogger(QuarkDialog.class);
private final transient JadxSettings settings;
private final transient MainWindow mainWindow;
private final List<Path> files;
private JComboBox<Path> fileSelectCombo;
public QuarkDialog(MainWindow mainWindow) {
this.mainWindow = mainWindow;
this.settings = mainWindow.getSettings();
this.files = filterOpenFiles(mainWindow);
if (files.isEmpty()) {
UiUtils.errorMessage(mainWindow, "Quark is unable to analyze loaded files");
LOG.error("Quark: The files cannot be analyzed: {}", mainWindow.getProject().getFilePaths());
return;
}
initUI();
}
private List<Path> filterOpenFiles(MainWindow mainWindow) {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.{apk,dex}");
return mainWindow.getProject().getFilePaths()
.stream()
.filter(matcher::matches)
.collect(Collectors.toList());
}
private void initUI() {
JLabel description = new JLabel("Analyzing apk using Quark-Engine");
JLabel selectApkText = new JLabel("Select Apk/Dex");
description.setAlignmentX(0.5f);
fileSelectCombo = new JComboBox<>(files.toArray(new Path[0]));
fileSelectCombo.setRenderer((list, value, index, isSelected, cellHasFocus) -> new NodeLabel(value.getFileName().toString()));
JPanel textPane = new JPanel();
textPane.add(description);
JPanel selectApkPanel = new JPanel();
selectApkPanel.add(selectApkText);
selectApkPanel.add(fileSelectCombo);
JPanel buttonPane = new JPanel();
JButton start = new JButton("Start");
JButton close = new JButton("Close");
close.addActionListener(event -> close());
start.addActionListener(event -> startQuarkTasks());
buttonPane.add(start);
buttonPane.add(close);
getRootPane().setDefaultButton(close);
JPanel centerPane = new JPanel();
centerPane.add(selectApkPanel);
Container contentPane = getContentPane();
contentPane.add(textPane, BorderLayout.PAGE_START);
contentPane.add(centerPane);
contentPane.add(buttonPane, BorderLayout.PAGE_END);
setTitle("Quark Engine");
pack();
if (!mainWindow.getSettings().loadWindowPos(this)) {
setSize(300, 140);
}
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
UiUtils.addEscapeShortCutToDispose(this);
}
private void startQuarkTasks() {
Path apkFile = (Path) fileSelectCombo.getSelectedItem();
new QuarkManager(mainWindow, apkFile).start();
close();
}
private void close() {
dispose();
}
@Override
public void dispose() {
settings.saveWindowPos(this);
super.dispose();
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/plugins/quark/QuarkReportNode.java | jadx-gui/src/main/java/jadx/gui/plugins/quark/QuarkReportNode.java | package jadx.gui.plugins.quark;
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.ICodeInfo;
import jadx.api.impl.SimpleCodeInfo;
import jadx.core.utils.GsonUtils;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
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 QuarkReportNode extends JNode {
private static final long serialVersionUID = -766800957202637021L;
private static final Logger LOG = LoggerFactory.getLogger(QuarkReportNode.class);
private static final ImageIcon ICON = UiUtils.openSvgIcon("ui/quark");
private final Path reportFile;
private ICodeInfo errorContent;
public QuarkReportNode(Path reportFile) {
this.reportFile = reportFile;
}
@Override
public JClass getJParent() {
return null;
}
@Override
public Icon getIcon() {
return ICON;
}
@Override
public String makeString() {
return "Quark analysis report";
}
@Override
public boolean hasContent() {
return true;
}
@Override
public ContentPanel getContentPanel(TabbedPane tabbedPane) {
try {
QuarkReportData data;
try (BufferedReader reader = Files.newBufferedReader(reportFile)) {
data = GsonUtils.buildGson().fromJson(reader, QuarkReportData.class);
}
data.validate();
return new QuarkReportPanel(tabbedPane, this, data);
} catch (Exception e) {
LOG.error("Quark report parse error", e);
StringEscapeUtils.Builder builder = StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_HTML4);
builder.append("<h2>");
builder.escape("Quark analysis failed!");
builder.append("</h2>");
builder.append("<h3>");
builder.append("Error: ").escape(e.getMessage());
builder.append("</h3>");
builder.append("<pre>");
builder.escape(ExceptionUtils.getStackTrace(e));
builder.append("</pre>");
errorContent = new SimpleCodeInfo(builder.toString());
return new HtmlPanel(tabbedPane, this);
}
}
@Override
public ICodeInfo getCodeInfo() {
return errorContent;
}
}
| 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/plugins/quark/QuarkManager.java | jadx-gui/src/main/java/jadx/gui/plugins/quark/QuarkManager.java | package jadx.gui.plugins.quark;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import jadx.commons.app.JadxSystemInfo;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.jobs.BackgroundExecutor;
import jadx.gui.logs.LogOptions;
import jadx.gui.treemodel.JRoot;
import jadx.gui.ui.MainWindow;
import jadx.gui.utils.UiUtils;
public class QuarkManager {
private static final Logger LOG = LoggerFactory.getLogger(QuarkManager.class);
private static final Path QUARK_DIR_PATH = Paths.get(System.getProperty("user.home"), ".quark-engine");
private static final Path VENV_PATH = QUARK_DIR_PATH.resolve("quark_venv");
private static final int LARGE_APK_SIZE = 30;
private final MainWindow mainWindow;
private final Path apkPath;
private boolean useVEnv;
private boolean installComplete;
private Path reportFile;
public QuarkManager(MainWindow mainWindow, Path apkPath) {
this.mainWindow = mainWindow;
this.apkPath = apkPath;
}
public void start() {
if (!checkFileSize(LARGE_APK_SIZE)) {
int result = JOptionPane.showConfirmDialog(mainWindow,
"The selected file size is too large (over 30M) that may take a long time to analyze, do you want to continue",
"Quark: Warning", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
return;
}
}
BackgroundExecutor executor = mainWindow.getBackgroundExecutor();
executor.execute("Quark install", this::checkInstall,
installStatus -> executor.execute("Quark analysis", this::startAnalysis, analysisStatus -> loadReport()));
}
private void checkInstall() {
try {
if (checkCommand("quark")) {
useVEnv = false;
installComplete = true;
return;
}
useVEnv = true;
if (checkVEnvCommand("quark")) {
installComplete = true;
installQuark(); // upgrade quark
return;
}
int result = JOptionPane.showConfirmDialog(mainWindow,
"Quark is not installed, do you want to install it from PyPI?", "Warning",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
installComplete = false;
return;
}
createVirtualEnv();
installQuark();
installComplete = true;
} catch (Exception e) {
UiUtils.errorMessage(mainWindow, e.getMessage());
LOG.error("Failed to install quark", e);
installComplete = false;
}
}
private void startAnalysis() {
if (!installComplete) {
return;
}
try {
updateQuarkRules();
reportFile = Files.createTempFile("QuarkReport-", ".json").toAbsolutePath();
List<String> cmd = new ArrayList<>();
cmd.add(getCommand("quark"));
cmd.add("-a");
cmd.add(apkPath.toString());
cmd.add("-o");
cmd.add(reportFile.toString());
runCommand(cmd);
} catch (Exception e) {
UiUtils.errorMessage(mainWindow, "Failed to execute Quark");
LOG.error("Failed to execute Quark", e);
}
}
private void loadReport() {
try {
QuarkReportNode quarkNode = new QuarkReportNode(reportFile);
JRoot root = mainWindow.getTreeRoot();
root.replaceCustomNode(quarkNode);
root.update();
mainWindow.reloadTree();
mainWindow.getTabsController().selectTab(quarkNode);
} catch (Exception e) {
UiUtils.errorMessage(mainWindow, "Failed to load Quark report.");
LOG.error("Failed to load Quark report.", e);
}
}
private void createVirtualEnv() {
if (Files.exists(getVenvPath("activate"))) {
return;
}
File directory = QUARK_DIR_PATH.toFile();
if (!directory.isDirectory()) {
if (!directory.mkdirs()) {
throw new JadxRuntimeException("Failed create directory: " + directory);
}
}
List<String> cmd = new ArrayList<>();
if (JadxSystemInfo.IS_WINDOWS) {
cmd.add("python");
cmd.add("-m");
cmd.add("venv");
} else {
cmd.add("virtualenv");
}
cmd.add(VENV_PATH.toString());
try {
runCommand(cmd);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to create virtual environment", e);
}
}
private void installQuark() {
List<String> cmd = new ArrayList<>();
cmd.add(getCommand("pip3"));
cmd.add("install");
cmd.add("setuptools");
cmd.add("quark-engine");
cmd.add("--upgrade");
try {
runCommand(cmd);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to install quark-engine", e);
}
}
private void updateQuarkRules() {
List<String> cmd = new ArrayList<>();
cmd.add(getCommand("freshquark"));
try {
runCommand(cmd);
} catch (Exception e) {
throw new JadxRuntimeException("Failed to update quark rules", e);
}
}
public boolean checkFileSize(int sizeThreshold) {
try {
int fileSize = (int) Files.size(apkPath) / 1024 / 1024;
if (fileSize > sizeThreshold) {
return false;
}
} catch (Exception e) {
LOG.error("Failed to calculate file: {}", e.getMessage(), e);
return false;
}
return true;
}
private String getCommand(String cmd) {
if (useVEnv) {
return getVenvPath(cmd).toAbsolutePath().toString();
}
return cmd;
}
private boolean checkVEnvCommand(String cmd) {
Path venvPath = getVenvPath(cmd);
return checkCommand(venvPath.toAbsolutePath().toString());
}
private Path getVenvPath(String cmd) {
if (JadxSystemInfo.IS_WINDOWS) {
return VENV_PATH.resolve("Scripts").resolve(cmd + ".exe");
}
return VENV_PATH.resolve("bin").resolve(cmd);
}
private void runCommand(List<String> cmd) throws Exception {
mainWindow.showLogViewer(LogOptions.forLevel(Level.INFO));
LOG.info("Running command: {}", String.join(" ", cmd));
ProcessBuilder builder = new ProcessBuilder(cmd);
builder.redirectErrorStream(true);
Process process = builder.start();
try (BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
buf.lines().forEach(msg -> LOG.info("# {}", msg));
} finally {
process.waitFor();
}
if (process.exitValue() != 0) {
throw new RuntimeException("Execution failed (exit code " + process.exitValue() + ") - command "
+ String.join(" ", cmd) + "\nPlease see command log output what was going wrong.");
}
}
private boolean checkCommand(String... cmd) {
try {
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
} catch (Exception e) {
return false;
}
return true;
}
}
| java | Apache-2.0 | 7bbb58863b8a80c0b862425d2701d23be40aeae8 | 2026-01-04T14:45:57.033910Z | false |
skylot/jadx | https://github.com/skylot/jadx/blob/7bbb58863b8a80c0b862425d2701d23be40aeae8/jadx-gui/src/main/java/jadx/gui/plugins/quark/QuarkReportPanel.java | jadx-gui/src/main/java/jadx/gui/plugins/quark/QuarkReportPanel.java | package jadx.gui.plugins.quark;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.Strings;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import jadx.api.JavaClass;
import jadx.api.JavaMethod;
import jadx.core.utils.Utils;
import jadx.gui.JadxWrapper;
import jadx.gui.treemodel.JMethod;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.tab.TabbedPane;
import jadx.gui.utils.JNodeCache;
import jadx.gui.utils.ui.NodeLabel;
public class QuarkReportPanel extends ContentPanel {
private static final long serialVersionUID = -242266836695889206L;
private static final Logger LOG = LoggerFactory.getLogger(QuarkReportPanel.class);
private final QuarkReportData data;
private final JNodeCache nodeCache;
private JEditorPane header;
private JTree tree;
private DefaultMutableTreeNode treeRoot;
private Font font;
private Font boldFont;
private CachingTreeCellRenderer cellRenderer;
protected QuarkReportPanel(TabbedPane panel, QuarkReportNode node, QuarkReportData data) {
super(panel, node);
this.data = data;
this.nodeCache = panel.getMainWindow().getCacheObject().getNodeCache();
prepareData();
initUI();
loadSettings();
}
private void prepareData() {
data.crimes.sort(Comparator.comparingInt(c -> -c.parseConfidence()));
}
private void initUI() {
setLayout(new BorderLayout());
header = new JEditorPane();
header.setContentType("text/html");
header.setEditable(false);
header.setText(buildHeader());
cellRenderer = new CachingTreeCellRenderer();
treeRoot = new TextTreeNode("Potential Malicious Activities:").bold();
tree = buildTree();
for (QuarkReportData.Crime crime : data.crimes) {
treeRoot.add(new CrimeTreeNode(crime));
}
tree.expandRow(0);
tree.expandRow(1);
JScrollPane tableScroll = new JScrollPane(tree);
tableScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(header, BorderLayout.PAGE_START);
mainPanel.add(tableScroll, BorderLayout.CENTER);
add(mainPanel);
}
private JTree buildTree() {
JTree tree = new JTree(treeRoot);
tree.setLayout(new BorderLayout());
tree.setBorder(BorderFactory.createEmptyBorder());
tree.setShowsRootHandles(false);
tree.setScrollsOnExpand(false);
tree.setSelectionModel(null);
tree.setCellRenderer(cellRenderer);
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
if (SwingUtilities.isLeftMouseButton(event)) {
Object node = getNodeUnderMouse(tree, event);
if (node instanceof MethodTreeNode) {
JMethod method = ((MethodTreeNode) node).getJMethod();
tabbedPane.getTabsController().codeJump(method);
}
}
}
});
tree.addTreeExpansionListener(new TreeExpansionListener() {
@Override
public void treeExpanded(TreeExpansionEvent event) {
TreePath path = event.getPath();
Object leaf = path.getLastPathComponent();
if (leaf instanceof CrimeTreeNode) {
CrimeTreeNode node = (CrimeTreeNode) leaf;
Enumeration<TreeNode> children = node.children();
while (children.hasMoreElements()) {
TreeNode child = children.nextElement();
tree.expandPath(path.pathByAddingChild(child));
}
}
}
@Override
public void treeCollapsed(TreeExpansionEvent event) {
}
});
return tree;
}
private String buildHeader() {
StringEscapeUtils.Builder builder = StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_HTML4);
builder.append("<h1>Quark Analysis Report</h1>");
builder.append("<h3>");
builder.append("File: ").append(data.apk_filename);
builder.append("<br>");
builder.append("Treat level: ").append(data.threat_level);
builder.append("<br>");
builder.append("Total score: ").append(Integer.toString(data.total_score));
builder.append("</h3>");
return builder.toString();
}
@Override
public void loadSettings() {
Font settingsFont = getMainWindow().getSettings().getCodeFont();
this.font = settingsFont.deriveFont(settingsFont.getSize2D() + 1.f);
this.boldFont = font.deriveFont(Font.BOLD);
header.setFont(font);
tree.setFont(font);
cellRenderer.clearCache();
}
private static Object getNodeUnderMouse(JTree tree, MouseEvent mouseEvent) {
TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
return path != null ? path.getLastPathComponent() : null;
}
private static class CachingTreeCellRenderer implements TreeCellRenderer {
private final Map<BaseTreeNode, Component> cache = new IdentityHashMap<>();
@Override
public Component getTreeCellRendererComponent(JTree tr, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean focus) {
return cache.computeIfAbsent((BaseTreeNode) value, BaseTreeNode::render);
}
public void clearCache() {
cache.clear();
}
}
private abstract static class BaseTreeNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 7197501219150495889L;
public BaseTreeNode(Object userObject) {
super(userObject);
}
public abstract Component render();
}
private class TextTreeNode extends BaseTreeNode {
private static final long serialVersionUID = 6763410122501083453L;
private boolean bold;
public TextTreeNode(String text) {
super(text);
}
public TextTreeNode bold() {
bold = true;
return this;
}
@Override
public Component render() {
JLabel label = new NodeLabel(((String) getUserObject()));
label.setFont(bold ? boldFont : font);
label.setIcon(null);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
return label;
}
}
private class CrimeTreeNode extends TextTreeNode {
private static final long serialVersionUID = -1464310215237483911L;
private final QuarkReportData.Crime crime;
public CrimeTreeNode(QuarkReportData.Crime crime) {
super(crime.crime);
this.crime = crime;
bold();
addDetails();
}
private void addDetails() {
add(new TextTreeNode("Confidence: " + crime.confidence));
if (Utils.notEmpty(crime.permissions)) {
add(new TextTreeNode("Permissions: " + Strings.join(", ", crime.permissions)));
}
if (Utils.notEmpty(crime.native_api)) {
TextTreeNode node = new TextTreeNode("Native API");
for (QuarkReportData.Method method : crime.native_api) {
node.add(new TextTreeNode(method.toString()));
}
add(node);
}
List<JsonElement> combination = crime.combination;
if (Utils.notEmpty(combination) && combination.get(0) instanceof JsonArray) {
TextTreeNode node = new TextTreeNode("Combination");
int size = combination.size();
for (int i = 0; i < size; i++) {
TextTreeNode set = new TextTreeNode("Set " + i);
JsonArray array = (JsonArray) combination.get(i);
for (JsonElement ele : array) {
String mth = ele.getAsString();
set.add(resolveMethod(mth));
}
node.add(set);
}
add(node);
}
if (Utils.notEmpty(crime.register)) {
TextTreeNode node = new TextTreeNode("Invocations");
for (Map<String, QuarkReportData.InvokePlace> invokeMap : crime.register) {
invokeMap.forEach((key, value) -> node.add(resolveMethod(key)));
}
add(node);
}
}
@Override
public String toString() {
return crime.crime;
}
}
public MutableTreeNode resolveMethod(String descr) {
try {
String[] parts = removeQuotes(descr).split(" ", 3);
String cls = Utils.cleanObjectName(parts[0].replace('$', '.'));
String mth = parts[1] + parts[2].replace(" ", "");
MainWindow mainWindow = getMainWindow();
JadxWrapper wrapper = mainWindow.getWrapper();
JavaClass javaClass = wrapper.searchJavaClassByRawName(cls);
if (javaClass == null) {
return new TextTreeNode(cls + "." + mth);
}
JavaMethod javaMethod = javaClass.searchMethodByShortId(mth);
if (javaMethod == null) {
return new TextTreeNode(javaClass.getFullName() + "." + mth);
}
return new MethodTreeNode(javaMethod);
} catch (Exception e) {
LOG.error("Failed to parse method descriptor string: {}", descr, e);
return new TextTreeNode(descr);
}
}
private static String removeQuotes(String descr) {
if (descr.charAt(0) == '\'') {
return descr.substring(1, descr.length() - 1);
}
return descr;
}
private class MethodTreeNode extends BaseTreeNode {
private static final long serialVersionUID = 4350343915220068508L;
private final JavaMethod mth;
private final JMethod jnode;
public MethodTreeNode(JavaMethod mth) {
super(mth);
this.mth = mth;
this.jnode = (JMethod) nodeCache.makeFrom(mth);
}
public JMethod getJMethod() {
return jnode;
}
@Override
public Component render() {
JLabel label = new NodeLabel(mth.toString());
label.setFont(font);
label.setIcon(jnode.getIcon());
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
return label;
}
}
}
| 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/plugins/quark/QuarkReportData.java | jadx-gui/src/main/java/jadx/gui/plugins/quark/QuarkReportData.java | package jadx.gui.plugins.quark;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import jadx.core.utils.Utils;
@SuppressWarnings("MemberName")
public class QuarkReportData {
public static class Crime {
public String crime;
public String confidence;
public List<String> permissions;
List<Method> native_api;
List<JsonElement> combination;
List<Map<String, InvokePlace>> register;
public int parseConfidence() {
return Integer.parseInt(confidence.replace("%", ""));
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Crime{");
sb.append("crime='").append(crime).append('\'');
sb.append(", confidence='").append(confidence).append('\'');
sb.append(", permissions=").append(permissions);
sb.append(", native_api=").append(native_api);
sb.append(", combination=").append(combination);
sb.append(", register=").append(register);
sb.append('}');
return sb.toString();
}
}
public static class Method {
@SerializedName("class")
String cls;
String method;
String descriptor;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(Utils.cleanObjectName(cls)).append(".").append(method);
if (descriptor != null) {
sb.append(descriptor);
}
return sb.toString();
}
}
public static class InvokePlace {
List<String> first;
List<String> second;
}
String apk_filename;
String threat_level;
int total_score;
List<Crime> crimes;
public void validate() {
if (crimes == null) {
throw new RuntimeException("Invalid data: \"crimes\" list missing");
}
for (Crime crime : crimes) {
if (crime.confidence == null) {
throw new RuntimeException("Confidence value missing: " + crime);
}
try {
crime.parseConfidence();
} catch (Exception e) {
throw new RuntimeException("Invalid crime entry: " + crime);
}
}
}
}
| 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/plugins/context/TreePopupMenuEntry.java | jadx-gui/src/main/java/jadx/gui/plugins/context/TreePopupMenuEntry.java | package jadx.gui.plugins.context;
import java.util.function.Consumer;
import java.util.function.Predicate;
import javax.swing.JMenuItem;
import org.jetbrains.annotations.Nullable;
import jadx.api.gui.tree.ITreeNode;
public class TreePopupMenuEntry {
private final String name;
private final Predicate<ITreeNode> addPredicate;
private final Consumer<ITreeNode> action;
public TreePopupMenuEntry(String name, Predicate<ITreeNode> addPredicate, Consumer<ITreeNode> action) {
this.name = name;
this.addPredicate = addPredicate;
this.action = action;
}
public @Nullable JMenuItem buildEntry(ITreeNode node) {
if (!addPredicate.test(node)) {
return null;
}
JMenuItem menuItem = new JMenuItem(name);
menuItem.addActionListener(ev -> action.accept(node));
return menuItem;
}
}
| 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/plugins/context/GuiPluginContext.java | jadx-gui/src/main/java/jadx/gui/plugins/context/GuiPluginContext.java | package jadx.gui.plugins.context;
import java.awt.Container;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JadxDecompiler;
import jadx.api.JavaClass;
import jadx.api.JavaNode;
import jadx.api.gui.tree.ITreeNode;
import jadx.api.metadata.ICodeNodeRef;
import jadx.api.plugins.events.IJadxEvents;
import jadx.api.plugins.events.types.NodeRenamedByUser;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.api.plugins.gui.JadxGuiContext;
import jadx.api.plugins.gui.JadxGuiSettings;
import jadx.core.plugins.PluginContext;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.codearea.AbstractCodeArea;
import jadx.gui.ui.codearea.AbstractCodeContentPanel;
import jadx.gui.ui.codearea.CodeArea;
import jadx.gui.ui.dialog.UsageDialog;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.utils.IconsCache;
import jadx.gui.utils.UiUtils;
public class GuiPluginContext implements JadxGuiContext {
private static final Logger LOG = LoggerFactory.getLogger(GuiPluginContext.class);
private final CommonGuiPluginsContext commonContext;
private final PluginContext pluginContext;
private @Nullable ISettingsGroup customSettingsGroup;
public GuiPluginContext(CommonGuiPluginsContext commonContext, PluginContext pluginContext) {
this.commonContext = commonContext;
this.pluginContext = pluginContext;
}
public CommonGuiPluginsContext getCommonContext() {
return commonContext;
}
public PluginContext getPluginContext() {
return pluginContext;
}
@Override
public JFrame getMainFrame() {
return commonContext.getMainWindow();
}
@Override
public void uiRun(Runnable runnable) {
UiUtils.uiRun(runnable);
}
@Override
public void addMenuAction(String name, Runnable action) {
commonContext.addMenuAction(name, action);
}
@Override
public void addPopupMenuAction(String name, @Nullable Function<ICodeNodeRef, Boolean> enabled,
@Nullable String keyBinding, Consumer<ICodeNodeRef> action) {
commonContext.getCodePopupActionList().add(new CodePopupAction(name, enabled, keyBinding, action));
}
@Override
public void addTreePopupMenuEntry(String name, Predicate<ITreeNode> addPredicate, Consumer<ITreeNode> action) {
commonContext.getTreePopupMenuEntries().add(new TreePopupMenuEntry(name, addPredicate, action));
}
@Override
public boolean registerGlobalKeyBinding(String id, String keyBinding, Runnable action) {
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyBinding);
if (keyStroke == null) {
throw new IllegalArgumentException("Failed to parse key binding: " + keyBinding);
}
JPanel mainPanel = (JPanel) commonContext.getMainWindow().getContentPane();
Object prevBinding = mainPanel.getInputMap().get(keyStroke);
if (prevBinding != null) {
return false;
}
UiUtils.addKeyBinding(mainPanel, keyStroke, id, action);
return true;
}
@Override
public void copyToClipboard(String str) {
UiUtils.copyToClipboard(str);
}
@Override
public JadxGuiSettings settings() {
return new GuiSettingsContext(this);
}
void setCustomSettings(ISettingsGroup customSettingsGroup) {
this.customSettingsGroup = customSettingsGroup;
}
public @Nullable ISettingsGroup getCustomSettingsGroup() {
return customSettingsGroup;
}
@Nullable
private CodeArea getCodeArea() {
Container contentPane = commonContext.getMainWindow().getTabbedPane().getSelectedContentPanel();
if (contentPane instanceof AbstractCodeContentPanel) {
AbstractCodeArea codeArea = ((AbstractCodeContentPanel) contentPane).getCodeArea();
if (codeArea instanceof CodeArea) {
return (CodeArea) codeArea;
}
}
return null;
}
@Override
public ImageIcon getSVGIcon(String name) {
try {
return IconsCache.getSVGIcon(name);
} catch (Exception e) {
LOG.error("Failed to load icon: {}", name, e);
return IconsCache.getSVGIcon("ui/error");
}
}
@Override
public ICodeNodeRef getNodeUnderCaret() {
CodeArea codeArea = getCodeArea();
if (codeArea != null) {
JNode nodeUnderCaret = codeArea.getNodeUnderCaret();
if (nodeUnderCaret != null) {
return nodeUnderCaret.getCodeNodeRef();
}
}
return null;
}
@Override
public ICodeNodeRef getNodeUnderMouse() {
CodeArea codeArea = getCodeArea();
if (codeArea != null) {
JNode nodeUnderMouse = codeArea.getNodeUnderMouse();
if (nodeUnderMouse != null) {
return nodeUnderMouse.getCodeNodeRef();
}
}
return null;
}
@Override
public ICodeNodeRef getEnclosingNodeUnderCaret() {
CodeArea codeArea = getCodeArea();
if (codeArea != null) {
JNode nodeUnderMouse = codeArea.getEnclosingNodeUnderCaret();
if (nodeUnderMouse != null) {
return nodeUnderMouse.getCodeNodeRef();
}
}
return null;
}
@Override
public ICodeNodeRef getEnclosingNodeUnderMouse() {
CodeArea codeArea = getCodeArea();
if (codeArea != null) {
JNode nodeUnderMouse = codeArea.getEnclosingNodeUnderMouse();
if (nodeUnderMouse != null) {
return nodeUnderMouse.getCodeNodeRef();
}
}
return null;
}
@Override
public boolean open(ICodeNodeRef ref) {
commonContext.getMainWindow().getTabsController().codeJump(getJNodeFromRef(ref));
return true;
}
@Override
public void openUsageDialog(ICodeNodeRef ref) {
UsageDialog.open(commonContext.getMainWindow(), getJNodeFromRef(ref));
}
private JNode getJNodeFromRef(ICodeNodeRef ref) {
return commonContext.getMainWindow().getCacheObject().getNodeCache().makeFrom(ref);
}
@Override
public void reloadActiveTab() {
UiUtils.uiRun(() -> {
CodeArea codeArea = getCodeArea();
if (codeArea != null) {
codeArea.refreshClass();
}
});
}
@Override
public void reloadAllTabs() {
UiUtils.uiRun(() -> {
for (ContentPanel contentPane : commonContext.getMainWindow().getTabbedPane().getTabs()) {
if (contentPane instanceof AbstractCodeContentPanel) {
AbstractCodeArea codeArea = ((AbstractCodeContentPanel) contentPane).getCodeArea();
if (codeArea instanceof CodeArea) {
((CodeArea) codeArea).refreshClass();
}
}
}
});
}
@Override
public void applyNodeRename(ICodeNodeRef nodeRef) {
JadxDecompiler decompiler = commonContext.getMainWindow().getWrapper().getDecompiler();
JavaNode javaNode = decompiler.getJavaNodeByRef(nodeRef);
if (javaNode == null) {
throw new JadxRuntimeException("Failed to resolve node ref: " + nodeRef);
}
String newName;
if (javaNode instanceof JavaClass) {
// package can have alias
newName = javaNode.getFullName();
} else {
newName = javaNode.getName();
}
IJadxEvents events = commonContext.getMainWindow().events();
events.send(new NodeRenamedByUser(nodeRef, "", newName));
}
}
| 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/plugins/context/CommonGuiPluginsContext.java | jadx-gui/src/main/java/jadx/gui/plugins/context/CommonGuiPluginsContext.java | package jadx.gui.plugins.context;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.core.plugins.PluginContext;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.codearea.CodeArea;
import jadx.gui.ui.codearea.JNodePopupBuilder;
import jadx.gui.utils.ui.ActionHandler;
public class CommonGuiPluginsContext {
private static final Logger LOG = LoggerFactory.getLogger(CommonGuiPluginsContext.class);
private final MainWindow mainWindow;
private final Map<PluginContext, GuiPluginContext> pluginsMap = new HashMap<>();
private final List<CodePopupAction> codePopupActionList = new ArrayList<>();
private final List<TreePopupMenuEntry> treePopupMenuEntries = new ArrayList<>();
public CommonGuiPluginsContext(MainWindow mainWindow) {
this.mainWindow = mainWindow;
}
public GuiPluginContext buildForPlugin(PluginContext pluginContext) {
GuiPluginContext guiPluginContext = new GuiPluginContext(this, pluginContext);
pluginsMap.put(pluginContext, guiPluginContext);
return guiPluginContext;
}
public @Nullable GuiPluginContext getPluginGuiContext(PluginContext pluginContext) {
return pluginsMap.get(pluginContext);
}
public void reset() {
codePopupActionList.clear();
treePopupMenuEntries.clear();
mainWindow.resetPluginsMenu();
}
public MainWindow getMainWindow() {
return mainWindow;
}
public List<CodePopupAction> getCodePopupActionList() {
return codePopupActionList;
}
public List<TreePopupMenuEntry> getTreePopupMenuEntries() {
return treePopupMenuEntries;
}
public void addMenuAction(String name, Runnable action) {
ActionHandler item = new ActionHandler(ev -> {
try {
mainWindow.getBackgroundExecutor().execute(name, action);
} catch (Exception e) {
LOG.error("Error running action for menu item: {}", name, e);
}
});
item.setNameAndDesc(name);
mainWindow.addToPluginsMenu(item);
}
public void appendPopupMenus(CodeArea codeArea, JNodePopupBuilder popup) {
if (codePopupActionList.isEmpty()) {
return;
}
popup.addSeparator();
for (CodePopupAction codePopupAction : codePopupActionList) {
popup.add(codePopupAction.buildAction(codeArea));
}
}
}
| 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/plugins/context/CodePopupAction.java | jadx-gui/src/main/java/jadx/gui/plugins/context/CodePopupAction.java | package jadx.gui.plugins.context;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.swing.KeyStroke;
import org.jetbrains.annotations.Nullable;
import jadx.api.metadata.ICodeNodeRef;
import jadx.gui.treemodel.JNode;
import jadx.gui.ui.action.JNodeAction;
import jadx.gui.ui.codearea.CodeArea;
public class CodePopupAction {
private final String name;
private final Function<ICodeNodeRef, Boolean> enabledCheck;
private final String keyBinding;
private final Consumer<ICodeNodeRef> action;
public CodePopupAction(String name, Function<ICodeNodeRef, Boolean> enabled, String keyBinding, Consumer<ICodeNodeRef> action) {
this.name = name;
this.enabledCheck = enabled;
this.keyBinding = keyBinding;
this.action = action;
}
public JNodeAction buildAction(CodeArea codeArea) {
return new NodeAction(this, codeArea);
}
private static class NodeAction extends JNodeAction {
private final CodePopupAction data;
public NodeAction(CodePopupAction data, CodeArea codeArea) {
super(data.name, codeArea);
setName(data.name);
setShortcutComponent(codeArea);
if (data.keyBinding != null) {
KeyStroke key = KeyStroke.getKeyStroke(data.keyBinding);
if (key == null) {
throw new IllegalArgumentException("Failed to parse key stroke: " + data.keyBinding);
}
setKeyBinding(key);
}
this.data = data;
}
@Override
public boolean isActionEnabled(@Nullable JNode node) {
if (node == null) {
return false;
}
ICodeNodeRef codeNode = node.getCodeNodeRef();
if (codeNode == null) {
return false;
}
return data.enabledCheck.apply(codeNode);
}
@Override
public void runAction(JNode node) {
Runnable r = () -> data.action.accept(node.getCodeNodeRef());
getCodeArea().getMainWindow().getBackgroundExecutor().execute(data.name, r);
}
}
}
| 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/plugins/context/GuiSettingsContext.java | jadx-gui/src/main/java/jadx/gui/plugins/context/GuiSettingsContext.java | package jadx.gui.plugins.context;
import java.util.List;
import jadx.api.plugins.gui.ISettingsGroup;
import jadx.api.plugins.gui.JadxGuiSettings;
import jadx.api.plugins.options.OptionDescription;
import jadx.gui.settings.ui.SubSettingsGroup;
import jadx.gui.settings.ui.plugins.PluginSettings;
import jadx.gui.ui.MainWindow;
public class GuiSettingsContext implements JadxGuiSettings {
private final GuiPluginContext guiPluginContext;
public GuiSettingsContext(GuiPluginContext guiPluginContext) {
this.guiPluginContext = guiPluginContext;
}
@Override
public void setCustomSettingsGroup(ISettingsGroup group) {
guiPluginContext.setCustomSettings(group);
}
@Override
public ISettingsGroup buildSettingsGroupForOptions(String title, List<OptionDescription> options) {
MainWindow mainWindow = guiPluginContext.getCommonContext().getMainWindow();
PluginSettings pluginsSettings = new PluginSettings(mainWindow, mainWindow.getSettings());
SubSettingsGroup settingsGroup = new SubSettingsGroup(title);
pluginsSettings.addOptions(settingsGroup, options);
return settingsGroup;
}
}
| 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/events/JadxGuiEvents.java | jadx-gui/src/main/java/jadx/gui/events/JadxGuiEvents.java | package jadx.gui.events;
import jadx.api.plugins.events.JadxEventType;
import jadx.gui.events.types.TreeUpdate;
import static jadx.api.plugins.events.JadxEventType.create;
public class JadxGuiEvents {
public static final JadxEventType<TreeUpdate> TREE_UPDATE = create("TREE_UPDATE");
}
| 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/events/services/RenameService.java | jadx-gui/src/main/java/jadx/gui/events/services/RenameService.java | package jadx.gui.events.services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jadx.api.JadxDecompiler;
import jadx.api.JavaNode;
import jadx.api.data.ICodeRename;
import jadx.api.data.impl.JadxCodeData;
import jadx.api.plugins.events.JadxEvents;
import jadx.api.plugins.events.types.NodeRenamedByUser;
import jadx.core.utils.Utils;
import jadx.core.utils.exceptions.JadxRuntimeException;
import jadx.gui.jobs.TaskStatus;
import jadx.gui.settings.JadxProject;
import jadx.gui.treemodel.JClass;
import jadx.gui.treemodel.JNode;
import jadx.gui.treemodel.JRenameNode;
import jadx.gui.ui.MainWindow;
import jadx.gui.ui.codearea.ClassCodeContentPanel;
import jadx.gui.ui.codearea.CodeArea;
import jadx.gui.ui.panel.ContentPanel;
import jadx.gui.ui.tab.TabbedPane;
import jadx.gui.utils.CacheObject;
import jadx.gui.utils.JNodeCache;
import jadx.gui.utils.NLS;
import jadx.gui.utils.UiUtils;
/**
* Rename service listen for user rename events.
* For each event:
* - add/update rename entry in project code data
* - update code and/or invalidate cache for related classes
* - apply all needed UI updates (tabs, classes tree)
*/
public class RenameService {
private static final Logger LOG = LoggerFactory.getLogger(RenameService.class);
public static void init(MainWindow mainWindow) {
RenameService renameService = new RenameService(mainWindow);
mainWindow.events().global().addListener(JadxEvents.NODE_RENAMED_BY_USER, renameService::process);
}
private final MainWindow mainWindow;
private RenameService(MainWindow mainWindow) {
this.mainWindow = mainWindow;
}
private void process(NodeRenamedByUser event) {
try {
LOG.debug("Applying rename event: {}", event);
JRenameNode node = getRenameNode(event);
updateCodeRenames(set -> processRename(node, event, set));
refreshState(node);
} catch (Exception e) {
LOG.error("Rename failed", e);
UiUtils.errorMessage(mainWindow, "Rename failed:\n" + Utils.getStackTrace(e));
}
}
private @NotNull JRenameNode getRenameNode(NodeRenamedByUser event) {
Object renameNode = event.getRenameNode();
if (renameNode instanceof JRenameNode) {
return (JRenameNode) renameNode;
}
JadxDecompiler decompiler = mainWindow.getWrapper().getDecompiler();
JavaNode javaNode = decompiler.getJavaNodeByRef(event.getNode());
if (javaNode != null) {
JNode node = mainWindow.getCacheObject().getNodeCache().makeFrom(javaNode);
if (node instanceof JRenameNode) {
return (JRenameNode) node;
}
}
throw new JadxRuntimeException("Failed to resolve node: " + event.getNode());
}
private void processRename(JRenameNode node, NodeRenamedByUser event, Set<ICodeRename> renames) {
ICodeRename rename = node.buildCodeRename(event.getNewName(), renames);
renames.remove(rename);
if (event.isResetName() || event.getNewName().isEmpty()) {
node.removeAlias();
} else {
renames.add(rename);
}
}
private void updateCodeRenames(Consumer<Set<ICodeRename>> updater) {
JadxProject project = mainWindow.getProject();
JadxCodeData codeData = project.getCodeData();
if (codeData == null) {
codeData = new JadxCodeData();
}
Set<ICodeRename> set = new HashSet<>(codeData.getRenames());
updater.accept(set);
List<ICodeRename> list = new ArrayList<>(set);
Collections.sort(list);
codeData.setRenames(list);
project.setCodeData(codeData);
}
private void refreshState(JRenameNode node) {
List<JavaNode> toUpdate = new ArrayList<>();
node.addUpdateNodes(toUpdate);
JNodeCache nodeCache = mainWindow.getCacheObject().getNodeCache();
Set<JClass> updatedTopClasses = toUpdate
.stream()
.map(JavaNode::getTopParentClass)
.map(nodeCache::makeFrom)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
LOG.debug("Classes to update: {}", updatedTopClasses);
if (updatedTopClasses.isEmpty()) {
return;
}
mainWindow.getBackgroundExecutor().execute("Refreshing",
() -> {
mainWindow.getWrapper().reloadCodeData();
UiUtils.uiRunAndWait(() -> refreshTabs(mainWindow.getTabbedPane(), updatedTopClasses));
refreshClasses(updatedTopClasses);
},
(status) -> {
if (status == TaskStatus.CANCEL_BY_MEMORY) {
mainWindow.showHeapUsageBar();
UiUtils.errorMessage(mainWindow, NLS.str("message.memoryLow"));
}
node.reload(mainWindow);
});
}
private void refreshClasses(Set<JClass> updatedTopClasses) {
CacheObject cache = mainWindow.getCacheObject();
if (updatedTopClasses.size() < 10) {
// small batch => reload
LOG.debug("Classes to reload: {}", updatedTopClasses.size());
for (JClass cls : updatedTopClasses) {
try {
cls.reload(cache);
} catch (Exception e) {
LOG.error("Failed to reload class: {}", cls.getFullName(), e);
}
}
} else {
// big batch => unload
LOG.debug("Classes to unload: {}", updatedTopClasses.size());
for (JClass cls : updatedTopClasses) {
try {
cls.unload(cache);
} catch (Exception e) {
LOG.error("Failed to unload class: {}", cls.getFullName(), e);
}
}
}
}
private void refreshTabs(TabbedPane tabbedPane, Set<JClass> updatedClasses) {
for (ContentPanel tab : tabbedPane.getTabs()) {
JClass rootClass = tab.getNode().getRootClass();
if (updatedClasses.remove(rootClass)) {
ClassCodeContentPanel contentPanel = (ClassCodeContentPanel) tab;
CodeArea codeArea = (CodeArea) contentPanel.getJavaCodePanel().getCodeArea();
codeArea.refreshClass();
}
}
}
}
| 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/events/types/TreeUpdate.java | jadx-gui/src/main/java/jadx/gui/events/types/TreeUpdate.java | package jadx.gui.events.types;
import jadx.api.plugins.events.IJadxEvent;
import jadx.api.plugins.events.JadxEventType;
import jadx.gui.events.JadxGuiEvents;
import jadx.gui.treemodel.JRoot;
public class TreeUpdate implements IJadxEvent {
private final JRoot jRoot;
public TreeUpdate(JRoot jRoot) {
this.jRoot = jRoot;
}
public JRoot getJRoot() {
return jRoot;
}
@Override
public JadxEventType<TreeUpdate> getType() {
return JadxGuiEvents.TREE_UPDATE;
}
}
| 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.