Repository: java-decompiler/jd-gui
Branch: master
Commit: b3c1ced04e57
Files: 257
Total size: 945.3 KB
Directory structure:
gitextract_0mx2o5ea/
├── .gitattributes
├── .gitignore
├── LICENSE
├── NOTICE
├── README.md
├── api/
│ ├── build.gradle
│ └── src/
│ └── main/
│ └── java/
│ └── org/
│ └── jd/
│ └── gui/
│ ├── api/
│ │ ├── API.java
│ │ ├── feature/
│ │ │ ├── ContainerEntryGettable.java
│ │ │ ├── ContentCopyable.java
│ │ │ ├── ContentIndexable.java
│ │ │ ├── ContentSavable.java
│ │ │ ├── ContentSearchable.java
│ │ │ ├── ContentSelectable.java
│ │ │ ├── FocusedTypeGettable.java
│ │ │ ├── IndexesChangeListener.java
│ │ │ ├── LineNumberNavigable.java
│ │ │ ├── PageChangeListener.java
│ │ │ ├── PageChangeable.java
│ │ │ ├── PageClosable.java
│ │ │ ├── PageCreator.java
│ │ │ ├── PreferencesChangeListener.java
│ │ │ ├── SourcesSavable.java
│ │ │ ├── TreeNodeExpandable.java
│ │ │ ├── UriGettable.java
│ │ │ └── UriOpenable.java
│ │ └── model/
│ │ ├── Container.java
│ │ ├── Indexes.java
│ │ ├── TreeNodeData.java
│ │ └── Type.java
│ └── spi/
│ ├── ContainerFactory.java
│ ├── ContextualActionsFactory.java
│ ├── FileLoader.java
│ ├── Indexer.java
│ ├── PanelFactory.java
│ ├── PasteHandler.java
│ ├── PreferencesPanel.java
│ ├── SourceLoader.java
│ ├── SourceSaver.java
│ ├── TreeNodeFactory.java
│ ├── TypeFactory.java
│ └── UriLoader.java
├── app/
│ ├── build.gradle
│ └── src/
│ └── main/
│ ├── java/
│ │ └── org/
│ │ └── jd/
│ │ └── gui/
│ │ ├── App.java
│ │ ├── Constants.java
│ │ ├── OsxApp.java
│ │ ├── controller/
│ │ │ ├── AboutController.java
│ │ │ ├── GoToController.java
│ │ │ ├── MainController.java
│ │ │ ├── OpenTypeController.java
│ │ │ ├── OpenTypeHierarchyController.java
│ │ │ ├── PreferencesController.java
│ │ │ ├── SaveAllSourcesController.java
│ │ │ ├── SearchInConstantPoolsController.java
│ │ │ └── SelectLocationController.java
│ │ ├── model/
│ │ │ ├── configuration/
│ │ │ │ └── Configuration.java
│ │ │ ├── container/
│ │ │ │ └── DelegatingFilterContainer.java
│ │ │ └── history/
│ │ │ └── History.java
│ │ ├── service/
│ │ │ ├── actions/
│ │ │ │ └── ContextualActionsFactoryService.java
│ │ │ ├── configuration/
│ │ │ │ ├── ConfigurationPersister.java
│ │ │ │ ├── ConfigurationPersisterService.java
│ │ │ │ └── ConfigurationXmlPersisterProvider.java
│ │ │ ├── container/
│ │ │ │ └── ContainerFactoryService.java
│ │ │ ├── extension/
│ │ │ │ └── ExtensionService.java
│ │ │ ├── fileloader/
│ │ │ │ └── FileLoaderService.java
│ │ │ ├── indexer/
│ │ │ │ └── IndexerService.java
│ │ │ ├── mainpanel/
│ │ │ │ ├── ContainerPanelFactoryProvider.java
│ │ │ │ └── PanelFactoryService.java
│ │ │ ├── pastehandler/
│ │ │ │ └── PasteHandlerService.java
│ │ │ ├── platform/
│ │ │ │ └── PlatformService.java
│ │ │ ├── preferencespanel/
│ │ │ │ ├── PreferencesPanelService.java
│ │ │ │ ├── UISingleInstancePreferencesProvider.java
│ │ │ │ └── UITabsPreferencesProvider.java
│ │ │ ├── sourceloader/
│ │ │ │ └── SourceLoaderService.java
│ │ │ ├── sourcesaver/
│ │ │ │ └── SourceSaverService.java
│ │ │ ├── treenode/
│ │ │ │ └── TreeNodeFactoryService.java
│ │ │ ├── type/
│ │ │ │ └── TypeFactoryService.java
│ │ │ └── uriloader/
│ │ │ └── UriLoaderService.java
│ │ ├── util/
│ │ │ ├── exception/
│ │ │ │ └── ExceptionUtil.java
│ │ │ ├── function/
│ │ │ │ └── TriConsumer.java
│ │ │ ├── net/
│ │ │ │ ├── InterProcessCommunicationUtil.java
│ │ │ │ └── UriUtil.java
│ │ │ └── swing/
│ │ │ └── SwingUtil.java
│ │ └── view/
│ │ ├── AboutView.java
│ │ ├── GoToView.java
│ │ ├── MainView.java
│ │ ├── OpenTypeHierarchyView.java
│ │ ├── OpenTypeView.java
│ │ ├── PreferencesView.java
│ │ ├── SaveAllSourcesView.java
│ │ ├── SearchInConstantPoolsView.java
│ │ ├── SelectLocationView.java
│ │ ├── bean/
│ │ │ └── OpenTypeListCellBean.java
│ │ ├── component/
│ │ │ ├── IconButton.java
│ │ │ ├── List.java
│ │ │ ├── Tree.java
│ │ │ └── panel/
│ │ │ ├── MainTabbedPanel.java
│ │ │ ├── TabbedPanel.java
│ │ │ └── TreeTabbedPanel.java
│ │ └── renderer/
│ │ ├── OpenTypeListCellRenderer.java
│ │ └── TreeNodeRenderer.java
│ └── resources/
│ └── META-INF/
│ └── services/
│ ├── org.jd.gui.spi.PanelFactory
│ └── org.jd.gui.spi.PreferencesPanel
├── build.gradle
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── services/
│ ├── build.gradle
│ └── src/
│ ├── main/
│ │ ├── antlr/
│ │ │ └── Java.g4
│ │ ├── java/
│ │ │ └── org/
│ │ │ ├── fife/
│ │ │ │ └── ui/
│ │ │ │ └── rtextarea/
│ │ │ │ └── Marker.java
│ │ │ └── jd/
│ │ │ └── gui/
│ │ │ ├── model/
│ │ │ │ └── container/
│ │ │ │ ├── ContainerEntryComparator.java
│ │ │ │ ├── EarContainer.java
│ │ │ │ ├── GenericContainer.java
│ │ │ │ ├── JarContainer.java
│ │ │ │ ├── JavaModuleContainer.java
│ │ │ │ ├── KarContainer.java
│ │ │ │ └── WarContainer.java
│ │ │ ├── service/
│ │ │ │ ├── actions/
│ │ │ │ │ ├── CopyQualifiedNameContextualActionsFactory.java
│ │ │ │ │ └── InvalidFormatException.java
│ │ │ │ ├── container/
│ │ │ │ │ ├── EarContainerFactoryProvider.java
│ │ │ │ │ ├── GenericContainerFactoryProvider.java
│ │ │ │ │ ├── JarContainerFactoryProvider.java
│ │ │ │ │ ├── JavaModuleContainerFactoryProvider.java
│ │ │ │ │ ├── KarContainerFactoryProvider.java
│ │ │ │ │ └── WarContainerFactoryProvider.java
│ │ │ │ ├── fileloader/
│ │ │ │ │ ├── AarFileLoaderProvider.java
│ │ │ │ │ ├── AbstractFileLoaderProvider.java
│ │ │ │ │ ├── AbstractTypeFileLoaderProvider.java
│ │ │ │ │ ├── ClassFileLoaderProvider.java
│ │ │ │ │ ├── EarFileLoaderProvider.java
│ │ │ │ │ ├── JarFileLoaderProvider.java
│ │ │ │ │ ├── JavaFileLoaderProvider.java
│ │ │ │ │ ├── JavaModuleFileLoaderProvider.java
│ │ │ │ │ ├── KarFileLoaderProvider.java
│ │ │ │ │ ├── LogFileLoaderProvider.java
│ │ │ │ │ ├── WarFileLoaderProvider.java
│ │ │ │ │ └── ZipFileLoaderProvider.java
│ │ │ │ ├── indexer/
│ │ │ │ │ ├── AbstractIndexerProvider.java
│ │ │ │ │ ├── ClassFileIndexerProvider.java
│ │ │ │ │ ├── DirectoryIndexerProvider.java
│ │ │ │ │ ├── EjbJarXmlFileIndexerProvider.java
│ │ │ │ │ ├── JavaFileIndexerProvider.java
│ │ │ │ │ ├── JavaModuleFileIndexerProvider.java
│ │ │ │ │ ├── JavaModuleInfoFileIndexerProvider.java
│ │ │ │ │ ├── MetainfServiceFileIndexerProvider.java
│ │ │ │ │ ├── TextFileIndexerProvider.java
│ │ │ │ │ ├── WebXmlFileIndexerProvider.java
│ │ │ │ │ ├── XmlBasedFileIndexerProvider.java
│ │ │ │ │ ├── XmlFileIndexerProvider.java
│ │ │ │ │ └── ZipFileIndexerProvider.java
│ │ │ │ ├── pastehandler/
│ │ │ │ │ └── LogPasteHandler.java
│ │ │ │ ├── preferencespanel/
│ │ │ │ │ ├── ClassFileDecompilerPreferencesProvider.java
│ │ │ │ │ ├── ClassFileSaverPreferencesProvider.java
│ │ │ │ │ ├── DirectoryIndexerPreferencesProvider.java
│ │ │ │ │ ├── MavenOrgSourceLoaderPreferencesProvider.java
│ │ │ │ │ └── ViewerPreferencesProvider.java
│ │ │ │ ├── sourceloader/
│ │ │ │ │ └── MavenOrgSourceLoaderProvider.java
│ │ │ │ ├── sourcesaver/
│ │ │ │ │ ├── AbstractSourceSaverProvider.java
│ │ │ │ │ ├── ClassFileSourceSaverProvider.java
│ │ │ │ │ ├── DirectorySourceSaverProvider.java
│ │ │ │ │ ├── FileSourceSaverProvider.java
│ │ │ │ │ ├── PackageSourceSaverProvider.java
│ │ │ │ │ └── ZipFileSourceSaverProvider.java
│ │ │ │ ├── treenode/
│ │ │ │ │ ├── AbstractTreeNodeFactoryProvider.java
│ │ │ │ │ ├── AbstractTypeFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── ClassFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── ClassesDirectoryTreeNodeFactoryProvider.java
│ │ │ │ │ ├── CssFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── DirectoryTreeNodeFactoryProvider.java
│ │ │ │ │ ├── DtdFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── EarFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── EjbJarXmlFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── FileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── HtmlFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── ImageFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── JarFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── JavaFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── JavaModuleFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── JavaModulePackageTreeNodeFactoryProvider.java
│ │ │ │ │ ├── JavascriptFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── JsonFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── JspFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── KarFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── ManifestFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── MetainfDirectoryTreeNodeFactoryProvider.java
│ │ │ │ │ ├── MetainfServiceFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── ModuleInfoFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── PackageTreeNodeFactoryProvider.java
│ │ │ │ │ ├── PropertiesFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── SpiFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── SqlFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── TextFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── WarFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── WarPackageTreeNodeFactoryProvider.java
│ │ │ │ │ ├── WebXmlFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── WebinfLibDirectoryTreeNodeFactoryProvider.java
│ │ │ │ │ ├── XmlBasedFileTreeNodeFactoryProvider.java
│ │ │ │ │ ├── XmlFileTreeNodeFactoryProvider.java
│ │ │ │ │ └── ZipFileTreeNodeFactoryProvider.java
│ │ │ │ ├── type/
│ │ │ │ │ ├── AbstractTypeFactoryProvider.java
│ │ │ │ │ ├── ClassFileTypeFactoryProvider.java
│ │ │ │ │ └── JavaFileTypeFactoryProvider.java
│ │ │ │ └── uriloader/
│ │ │ │ └── FileUriLoaderProvider.java
│ │ │ ├── util/
│ │ │ │ ├── container/
│ │ │ │ │ └── JarContainerEntryUtil.java
│ │ │ │ ├── decompiler/
│ │ │ │ │ ├── ClassPathLoader.java
│ │ │ │ │ ├── ContainerLoader.java
│ │ │ │ │ ├── LineNumberStringBuilderPrinter.java
│ │ │ │ │ ├── NopPrinter.java
│ │ │ │ │ └── StringBuilderPrinter.java
│ │ │ │ ├── exception/
│ │ │ │ │ └── ExceptionUtil.java
│ │ │ │ ├── index/
│ │ │ │ │ └── IndexesUtil.java
│ │ │ │ ├── io/
│ │ │ │ │ ├── NewlineOutputStream.java
│ │ │ │ │ └── TextReader.java
│ │ │ │ ├── matcher/
│ │ │ │ │ └── DescriptorMatcher.java
│ │ │ │ ├── parser/
│ │ │ │ │ └── antlr/
│ │ │ │ │ ├── ANTLRJavaParser.java
│ │ │ │ │ └── AbstractJavaListener.java
│ │ │ │ └── xml/
│ │ │ │ └── AbstractXmlPathFinder.java
│ │ │ └── view/
│ │ │ ├── component/
│ │ │ │ ├── AbstractTextPage.java
│ │ │ │ ├── ClassFilePage.java
│ │ │ │ ├── CustomLineNumbersPage.java
│ │ │ │ ├── DynamicPage.java
│ │ │ │ ├── EjbJarXmlFilePage.java
│ │ │ │ ├── HyperlinkPage.java
│ │ │ │ ├── JavaFilePage.java
│ │ │ │ ├── LogPage.java
│ │ │ │ ├── ManifestFilePage.java
│ │ │ │ ├── ModuleInfoFilePage.java
│ │ │ │ ├── OneTypeReferencePerLinePage.java
│ │ │ │ ├── RoundMarkErrorStrip.java
│ │ │ │ ├── TextPage.java
│ │ │ │ ├── TypePage.java
│ │ │ │ ├── TypeReferencePage.java
│ │ │ │ ├── WebXmlFilePage.java
│ │ │ │ └── XmlFilePage.java
│ │ │ └── data/
│ │ │ └── TreeNodeBean.java
│ │ └── resources/
│ │ ├── META-INF/
│ │ │ └── services/
│ │ │ ├── org.jd.gui.spi.ContainerFactory
│ │ │ ├── org.jd.gui.spi.ContextualActionsFactory
│ │ │ ├── org.jd.gui.spi.FileLoader
│ │ │ ├── org.jd.gui.spi.Indexer
│ │ │ ├── org.jd.gui.spi.PasteHandler
│ │ │ ├── org.jd.gui.spi.PreferencesPanel
│ │ │ ├── org.jd.gui.spi.SourceLoader
│ │ │ ├── org.jd.gui.spi.SourceSaver
│ │ │ ├── org.jd.gui.spi.TreeNodeFactory
│ │ │ ├── org.jd.gui.spi.TypeFactory
│ │ │ └── org.jd.gui.spi.UriLoader
│ │ └── rsyntaxtextarea/
│ │ ├── RSyntaxTextArea_License.txt
│ │ └── themes/
│ │ └── eclipse.xml
│ └── test/
│ └── java/
│ └── org/
│ └── jd/
│ └── gui/
│ ├── util/
│ │ └── matcher/
│ │ └── DescriptorMatcherTest.java
│ └── view/
│ └── component/
│ ├── ClassFilePageTest.java
│ └── JavaFilePageTest.java
├── settings.gradle
└── src/
├── linux/
│ └── resources/
│ └── jd-gui.desktop
├── osx/
│ ├── dist/
│ │ └── JD-GUI.app/
│ │ └── Contents/
│ │ └── Resources/
│ │ └── jd-gui.icns
│ └── resources/
│ ├── Info.plist
│ └── universalJavaApplicationStub.sh
└── proguard/
└── resources/
└── proguard.config.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Declare OSX files that will always have LF line endings on checkout.
Info.plist text eol=lf
# Declare script files that will always have LF line endings on checkout.
*.sh text eol=lf
# Declare script files that will always have CR/LF line endings on checkout.
*.bat text eol=crlf
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
*.gif binary
*.icns binary
================================================
FILE: .gitignore
================================================
# Java
*.class
# JD
debug*
# JD-GUI
src-generated/
jd-gui.cfg
# Idea
.idea/
out/
*.ipr
*.iml
*.iws
# Eclipse
.settings/
classes/
.classpath
.project
# Mac
.DS_Store
#Windows
Thumbs.db
# Maven
log/
target/
# Gradle
.gradle/
build/
!gradle/wrapper/*
# WinMerge
*.bak
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
JD-GUI, a standalone graphical utility that displays Java sources from
CLASS files
Copyright (C) 2008-2019 Emmanuel Dupuy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
JD-GUI Copyright (C) 2008-2019 Emmanuel Dupuy
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: NOTICE
================================================
JD-GUI license - GPLv3
Libraries used:
Groovy - Apache License 2.0
Gradle - Apache License 2.0
JD-Core Java Release - GPLv3
RSyntaxTextArea - Modified BSD license
JD-GUI Mac OSX distribution:
universalJavaApplicationStub - MIT License
JD-GUI Windows distribution:
Launch4j - MIT License
================================================
FILE: README.md
================================================
# JD-GUI
JD-GUI, a standalone graphical utility that displays Java sources from CLASS files.

- Java Decompiler projects home page: [http://java-decompiler.github.io](http://java-decompiler.github.io)
- JD-GUI source code: [https://github.com/java-decompiler/jd-gui](https://github.com/java-decompiler/jd-gui)
## Description
JD-GUI is a standalone graphical utility that displays Java source codes of
".class" files. You can browse the reconstructed source code with the JD-GUI
for instant access to methods and fields.
## How to build JD-GUI ?
```
> git clone https://github.com/java-decompiler/jd-gui.git
> cd jd-gui
> ./gradlew build
```
generate :
- _"build/libs/jd-gui-x.y.z.jar"_
- _"build/libs/jd-gui-x.y.z-min.jar"_
- _"build/distributions/jd-gui-windows-x.y.z.zip"_
- _"build/distributions/jd-gui-osx-x.y.z.tar"_
- _"build/distributions/jd-gui-x.y.z.deb"_
- _"build/distributions/jd-gui-x.y.z.rpm"_
## How to launch JD-GUI ?
- Double-click on _"jd-gui-x.y.z.jar"_
- Double-click on _"jd-gui.exe"_ application from Windows
- Double-click on _"JD-GUI"_ application from Mac OSX
- Execute _"java -jar jd-gui-x.y.z.jar"_ or _"java -classpath jd-gui-x.y.z.jar org.jd.gui.App"_
## How to use JD-GUI ?
- Open a file with menu "File > Open File..."
- Open recent files with menu "File > Recent Files"
- Drag and drop files from your file explorer
## How to extend JD-GUI ?
```
> ./gradlew idea
```
generate Idea Intellij project
```
> ./gradlew eclipse
```
generate Eclipse project
```
> java -classpath jd-gui-x.y.z.jar;myextension1.jar;myextension2.jar org.jd.gui.App
```
launch JD-GUI with your extensions
## How to uninstall JD-GUI ?
- Java: Delete "jd-gui-x.y.z.jar" and "jd-gui.cfg".
- Mac OSX: Drag and drop "JD-GUI" application into the trash.
- Windows: Delete "jd-gui.exe" and "jd-gui.cfg".
## License
Released under the [GNU GPL v3](LICENSE).
## Donations
Did JD-GUI help you to solve a critical situation? Do you use JD-Eclipse daily? What about making a donation?
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=C88ZMVZ78RF22) [](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CRMXT4Y4QLQGU)
================================================
FILE: api/build.gradle
================================================
apply plugin: 'java'
version = '1.0.0'
================================================
FILE: api/src/main/java/org/jd/gui/api/API.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api;
import org.jd.gui.api.feature.UriGettable;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.spi.*;
import javax.swing.*;
import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Future;
public interface API {
boolean openURI(URI uri);
boolean openURI(int x, int y, Collection entries, String query, String fragment);
void addURI(URI uri);
void addPanel(String title, Icon icon, String tip, T component);
Collection getContextualActions(Container.Entry entry, String fragment);
UriLoader getUriLoader(URI uri);
FileLoader getFileLoader(File file);
ContainerFactory getContainerFactory(Path rootPath);
PanelFactory getMainPanelFactory(Container container);
TreeNodeFactory getTreeNodeFactory(Container.Entry entry);
TypeFactory getTypeFactory(Container.Entry entry);
Indexer getIndexer(Container.Entry entry);
SourceSaver getSourceSaver(Container.Entry entry);
Map getPreferences();
Collection> getCollectionOfFutureIndexes();
interface LoadSourceListener {
void sourceLoaded(String source);
}
String getSource(Container.Entry entry);
void loadSource(Container.Entry entry, LoadSourceListener listener);
File loadSourceFile(Container.Entry entry);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/ContainerEntryGettable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import org.jd.gui.api.model.Container;
public interface ContainerEntryGettable {
Container.Entry getEntry();
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/ContentCopyable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
public interface ContentCopyable {
void copy();
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/ContentIndexable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Indexes;
public interface ContentIndexable {
Indexes index(API api);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/ContentSavable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import org.jd.gui.api.API;
import java.io.OutputStream;
public interface ContentSavable {
String getFileName();
void save(API api, OutputStream os);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/ContentSearchable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
public interface ContentSearchable {
boolean highlightText(String text, boolean caseSensitive);
void findNext(String text, boolean caseSensitive);
void findPrevious(String text, boolean caseSensitive);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/ContentSelectable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
public interface ContentSelectable {
void selectAll();
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/FocusedTypeGettable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
public interface FocusedTypeGettable extends ContainerEntryGettable {
String getFocusedTypeName();
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/IndexesChangeListener.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import org.jd.gui.api.model.Indexes;
import java.util.Collection;
import java.util.concurrent.Future;
public interface IndexesChangeListener {
void indexesChanged(Collection> collectionOfFutureIndexes);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/LineNumberNavigable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
public interface LineNumberNavigable {
int getMaximumLineNumber();
void goToLineNumber(int lineNumber);
boolean checkLineNumber(int lineNumber);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/PageChangeListener.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import javax.swing.*;
public interface PageChangeListener {
void pageChanged(T page);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/PageChangeable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
public interface PageChangeable {
void addPageChangeListener(PageChangeListener listener);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/PageClosable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
public interface PageClosable {
boolean closePage();
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/PageCreator.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import org.jd.gui.api.API;
import javax.swing.*;
public interface PageCreator {
T createPage(API api);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/PreferencesChangeListener.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import java.util.Map;
public interface PreferencesChangeListener {
void preferencesChanged(Map preferences);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/SourcesSavable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import org.jd.gui.api.API;
import java.nio.file.Path;
public interface SourcesSavable {
String getSourceFileName();
int getFileCount();
void save(API api, Controller controller, Listener listener, Path path);
interface Controller {
boolean isCancelled();
}
interface Listener {
void pathSaved(Path path);
}
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/TreeNodeExpandable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import org.jd.gui.api.API;
public interface TreeNodeExpandable {
void populateTreeNode(API api);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/UriGettable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import java.net.URI;
public interface UriGettable {
URI getUri();
}
================================================
FILE: api/src/main/java/org/jd/gui/api/feature/UriOpenable.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.feature;
import java.net.URI;
/**
* uri : scheme '://' path ('?' query)? ('#' fragment)?
* scheme : 'generic' | 'jar' | 'war' | 'ear' | 'dex' | ...
* path : singlePath('!' singlePath)*
* singlePath : [path/to/dir/] | [path/to/file]
* query : queryLineNumber | queryPosition | querySearch
* queryLineNumber : 'lineNumber=' [numeric]
* queryPosition : 'position=' [numeric]
* querySearch : 'highlightPattern=' queryPattern '&highlightFlags=' queryFlags ('&highlightScope=' typeName)?
* queryPattern : [start of string] | [start of type name] | [start of field name] | [start of method name]
* queryFlags : 'd'? // Match declarations
* 'r'? // Match references
* 't'? // Match types
* 'c'? // Match constructors
* 'm'? // Match methods
* 'f'? // Match fields
* 's'? // Match strings
* fragment : fragmentType | fragmentField | fragmentMethod
* fragmentType : typeName
* fragmentField : typeName '-' [field name] '-' descriptor
* fragmentMethod : typeName '-' [method name] '-' methodDescriptor
* methodDescriptor : '(*)?' | // Match all method descriptors
* '(' descriptor* ')' descriptor
* descriptor : '?' | // Match a primitive or a type name
* '['* primitiveOrTypeName
* primitiveOrTypeName : 'B' | 'C' | 'D' | 'F' | 'I' | 'J' | 'L' typeName ';' | 'S' | 'Z'
* typeName : [internal qualified name] | '*\/' [name]
*
* Examples:
*
* - file://dir1/dir2/
* - file://dir1/dir2/file
* - jar://dir1/dir2/
* - jar://dir1/dir2/file
*
* - jar://dir1/dir2/javafile
* - jar://dir1/dir2/javafile#type
* - jar://dir1/dir2/javafile#type-fieldName-descriptor
* - jar://dir1/dir2/javafile#type-methodName-descriptor
* - jar://dir1/dir2/javafile#innertype
* - jar://dir1/dir2/javafile#innertype-fieldName-?
* - jar://dir1/dir2/javafile#innertype-methodName-(*)?
* - jar://dir1/dir2/javafile#innertype-methodName-(?JZLjava/lang/Sting;C)I
* - jar://dir1/dir2/javafile#innertype-fieldName-descriptor
* - jar://dir1/dir2/javafile#innertype-methodName-descriptor
*
* - file://dir1/dir2/file?lineNumber=numeric
* - file://dir1/dir2/file?position=numeric
* - file://dir1/dir2/file?highlightPattern=hello&highlightFlags=drtcmfs&highlightScope=java/lang/String
* - file://dir1/dir2/file?highlightPattern=hello&highlightFlags=drtcmfs&highlightScope=*\/String
*
*/
public interface UriOpenable {
boolean openUri(URI uri);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/model/Container.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.model;
import java.io.InputStream;
import java.net.URI;
import java.util.Collection;
public interface Container {
String getType();
Entry getRoot();
/**
* File or directory
*/
interface Entry {
Container getContainer();
Entry getParent();
URI getUri();
String getPath();
boolean isDirectory();
long length();
InputStream getInputStream();
Collection getChildren();
}
}
================================================
FILE: api/src/main/java/org/jd/gui/api/model/Indexes.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.model;
import java.util.Collection;
import java.util.Map;
/**
* Whatever the language/file format (Java|Groovy|Scala/Class|DEX, Java|Javascript/Source, C#/CIL, ...), type names,
* stored in the indexes, use the JVM internal format (package separator = '/', inner class separator = '$').
*
* List of default indexes:
*
* -
* Map "strings"
* key: a string
* value: a list of entries containing the string
*
* -
* Map "typeDeclarations"
* key: a type name using internal JVM internal format
* value: a list of entries containing the type declaration
*
* -
* Map "constructorDeclarations"
* key: a type name using internal JVM internal format
* value: a list of entries containing the constructor declaration
*
* -
* Map "constructorReferences"
* key: a type name using internal JVM internal format
* value: a list of entries containing the constructor reference
*
* -
* Map "methodDeclarations"
* key: a method name
* value: a list of entries containing the method declaration
*
* -
* Map "methodReferences"
* key: a method name
* value: a list of entries containing the method reference
*
* -
* Map "fieldDeclarations"
* key: a field name
* value: a list of entries containing the field declaration
*
* -
* Map "fieldReferences"
* key: a field name
* value: a list of entries containing the field reference
*
* -
* Map "subTypeNames"
* key: a super type name using internal JVM internal format
* value: a list of sub type names using internal JVM internal format
*
*
*/
public interface Indexes {
Map getIndex(String name);
}
================================================
FILE: api/src/main/java/org/jd/gui/api/model/TreeNodeData.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.model;
import javax.swing.*;
public interface TreeNodeData {
String getLabel();
String getTip();
Icon getIcon();
Icon getOpenIcon();
}
================================================
FILE: api/src/main/java/org/jd/gui/api/model/Type.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.api.model;
import javax.swing.*;
import java.util.Collection;
public interface Type {
int FLAG_PUBLIC = 1;
int FLAG_PRIVATE = 2;
int FLAG_PROTECTED = 4;
int FLAG_STATIC = 8;
int FLAG_FINAL = 16;
int FLAG_VARARGS = 128;
int FLAG_INTERFACE = 512;
int FLAG_ABSTRACT = 1024;
int FLAG_ANNOTATION = 8192;
int FLAG_ENUM = 16384;
int getFlags();
String getName();
String getSuperName();
String getOuterName();
String getDisplayTypeName();
String getDisplayInnerTypeName();
String getDisplayPackageName();
Icon getIcon();
Collection getInnerTypes();
Collection getFields();
Collection getMethods();
interface Field {
int getFlags();
String getName();
String getDescriptor();
String getDisplayName();
Icon getIcon();
}
interface Method {
int getFlags();
String getName();
String getDescriptor();
String getDisplayName();
Icon getIcon();
}
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/ContainerFactory.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import java.nio.file.Path;
public interface ContainerFactory {
String getType();
boolean accept(API api, Path rootPath);
Container make(API api, Container.Entry parentEntry, Path rootPath);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/ContextualActionsFactory.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import javax.swing.*;
import java.util.Collection;
public interface ContextualActionsFactory {
String GROUP_NAME = "GroupNameKey";
/**
* Build a collection of actions for 'entry' and 'fragment', grouped by GROUP_NAME and sorted by NAME. Null values
* are added for separators.
*
* @param fragment @see jd.gui.api.feature.UriOpenable
* @return a collection of actions
*/
Collection make(API api, Container.Entry entry, String fragment);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/FileLoader.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import java.io.File;
public interface FileLoader {
String[] getExtensions();
String getDescription();
boolean accept(API api, File file);
boolean load(API api, File file);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/Indexer.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import java.util.regex.Pattern;
public interface Indexer {
String[] getSelectors();
Pattern getPathPattern();
void index(API api, Container.Entry entry, Indexes indexes);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/PanelFactory.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.UriGettable;
import org.jd.gui.api.model.Container;
import javax.swing.*;
public interface PanelFactory {
String[] getTypes();
T make(API api, Container container);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/PasteHandler.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
public interface PasteHandler {
boolean accept(Object obj);
void paste(API api, Object obj);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/PreferencesPanel.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import javax.swing.*;
import java.awt.*;
import java.util.Map;
public interface PreferencesPanel {
String getPreferencesGroupTitle();
String getPreferencesPanelTitle();
JComponent getPanel();
void init(Color errorBackgroundColor);
boolean isActivated();
void loadPreferences(Map preferences);
void savePreferences(Map preferences);
boolean arePreferencesValid();
void addPreferencesChangeListener(PreferencesPanelChangeListener listener);
interface PreferencesPanelChangeListener {
void preferencesPanelChanged(PreferencesPanel source);
}
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/SourceLoader.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import java.io.File;
public interface SourceLoader {
String getSource(API api, Container.Entry entry);
String loadSource(API api, Container.Entry entry);
File loadSourceFile(API api, Container.Entry entry);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/SourceSaver.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import java.nio.file.Path;
import java.util.regex.Pattern;
public interface SourceSaver {
String[] getSelectors();
Pattern getPathPattern();
String getSourcePath(Container.Entry entry);
int getFileCount(API api, Container.Entry entry);
/**
* Check parent path, build source file name, create NIO path and save the content.
*/
void save(API api, Controller controller, Listener listener, Path rootPath, Container.Entry entry);
/**
* Save content:
*
* - For file, save the source content.
* - For directory, call 'save' for each children.
*
*/
void saveContent(API api, Controller controller, Listener listener, Path rootPath, Path path, Container.Entry entry);
interface Controller {
boolean isCancelled();
}
interface Listener {
void pathSaved(Path path);
}
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/TreeNodeFactory.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.ContainerEntryGettable;
import org.jd.gui.api.feature.UriGettable;
import org.jd.gui.api.model.Container;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.regex.Pattern;
public interface TreeNodeFactory {
String[] getSelectors();
Pattern getPathPattern();
T make(API api, Container.Entry entry);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/TypeFactory.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Type;
import java.util.Collection;
import java.util.regex.Pattern;
public interface TypeFactory {
String[] getSelectors();
Pattern getPathPattern();
/**
* @return all root types contains in 'entry'
*/
Collection make(API api, Container.Entry entry);
/**
* @param fragment @see jd.gui.api.feature.UriOpenable
* @return if 'fragment' is null, return the main type in 'entry',
* otherwise, return the type or sub-type matching with 'fragment'
*/
Type make(API api, Container.Entry entry, String fragment);
}
================================================
FILE: api/src/main/java/org/jd/gui/spi/UriLoader.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.spi;
import org.jd.gui.api.API;
import java.net.URI;
public interface UriLoader {
String[] getSchemes();
boolean accept(API api, URI uri);
boolean load(API api, URI uri);
}
================================================
FILE: app/build.gradle
================================================
apply plugin: 'java'
dependencies {
provided 'com.yuvimasory:orange-extensions:1.3.0' // OSX support
compile project(':api')
runtime project(':services')
}
version = parent.version
================================================
FILE: app/src/main/java/org/jd/gui/App.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui;
import org.jd.gui.controller.MainController;
import org.jd.gui.model.configuration.Configuration;
import org.jd.gui.service.configuration.ConfigurationPersister;
import org.jd.gui.service.configuration.ConfigurationPersisterService;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.net.InterProcessCommunicationUtil;
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class App {
protected static final String SINGLE_INSTANCE = "UIMainWindowPreferencesProvider.singleInstance";
protected static MainController controller;
public static void main(String[] args) {
if (checkHelpFlag(args)) {
JOptionPane.showMessageDialog(null, "Usage: jd-gui [option] [input-file] ...\n\nOption:\n -h Show this help message and exit", Constants.APP_NAME, JOptionPane.INFORMATION_MESSAGE);
} else {
// Load preferences
ConfigurationPersister persister = ConfigurationPersisterService.getInstance().get();
Configuration configuration = persister.load();
Runtime.getRuntime().addShutdownHook(new Thread(() -> persister.save(configuration)));
if ("true".equals(configuration.getPreferences().get(SINGLE_INSTANCE))) {
InterProcessCommunicationUtil ipc = new InterProcessCommunicationUtil();
try {
ipc.listen(receivedArgs -> controller.openFiles(newList(receivedArgs)));
} catch (Exception notTheFirstInstanceException) {
// Send args to main windows and exit
ipc.send(args);
System.exit(0);
}
}
// Create SwingBuilder, set look and feel
try {
UIManager.setLookAndFeel(configuration.getLookAndFeel());
} catch (Exception e) {
configuration.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
try {
UIManager.setLookAndFeel(configuration.getLookAndFeel());
} catch (Exception ee) {
assert ExceptionUtil.printStackTrace(ee);
}
}
// Create main controller and show main frame
controller = new MainController(configuration);
controller.show(newList(args));
}
}
protected static boolean checkHelpFlag(String[] args) {
if (args != null) {
for (String arg : args) {
if ("-h".equals(arg)) {
return true;
}
}
}
return false;
}
protected static List newList(String[] paths) {
if (paths == null) {
return Collections.emptyList();
} else {
ArrayList files = new ArrayList<>(paths.length);
for (String path : paths) {
files.add(new File(path));
}
return files;
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/Constants.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui;
public class Constants {
public static final String APP_NAME = "JD-GUI";
public static final int DEFAULT_WIDTH = 600;
public static final int DEFAULT_HEIGHT = 400;
public static final int MINIMAL_WIDTH = 500;
public static final int MINIMAL_HEIGHT = 160;
public static final String CONFIG_FILENAME = "jd-gui.cfg";
public static final int MAX_RECENT_FILES = 10;
public static final int RECENT_FILE_MAX_LENGTH = 200;
}
================================================
FILE: app/src/main/java/org/jd/gui/OsxApp.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui;
import com.apple.eawt.Application;
public class OsxApp extends App {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// Create an instance of the mac OSX Application class
Application application = Application.getApplication();
App.main(args);
// Add an handle invoked when the application is asked to open a list of files
application.setOpenFileHandler(e -> controller.openFiles(e.getFiles()));
// Add an handle invoked when the application is asked to quit
application.setQuitHandler((e, r) -> System.exit(0));
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/AboutController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.view.AboutView;
import javax.swing.*;
public class AboutController {
protected AboutView aboutView;
public AboutController(JFrame mainFrame) {
// Create UI
aboutView = new AboutView(mainFrame);
}
public void show() {
// Show
aboutView.show();
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/GoToController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.api.feature.LineNumberNavigable;
import org.jd.gui.model.configuration.Configuration;
import org.jd.gui.view.GoToView;
import javax.swing.*;
import java.util.function.IntConsumer;
public class GoToController {
protected GoToView goToView;
public GoToController(Configuration configuration, JFrame mainFrame) {
// Create UI
goToView = new GoToView(configuration, mainFrame);
}
public void show(LineNumberNavigable navigator, IntConsumer okCallback) {
// Show
goToView.show(navigator, okCallback);
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/MainController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.*;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.model.configuration.Configuration;
import org.jd.gui.model.history.History;
import org.jd.gui.service.actions.ContextualActionsFactoryService;
import org.jd.gui.service.container.ContainerFactoryService;
import org.jd.gui.service.fileloader.FileLoaderService;
import org.jd.gui.service.indexer.IndexerService;
import org.jd.gui.service.mainpanel.PanelFactoryService;
import org.jd.gui.service.pastehandler.PasteHandlerService;
import org.jd.gui.service.platform.PlatformService;
import org.jd.gui.service.preferencespanel.PreferencesPanelService;
import org.jd.gui.service.sourceloader.SourceLoaderService;
import org.jd.gui.service.sourcesaver.SourceSaverService;
import org.jd.gui.service.treenode.TreeNodeFactoryService;
import org.jd.gui.service.type.TypeFactoryService;
import org.jd.gui.service.uriloader.UriLoaderService;
import org.jd.gui.spi.*;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.net.UriUtil;
import org.jd.gui.util.swing.SwingUtil;
import org.jd.gui.view.MainView;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.Path;
import java.util.*;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainController implements API {
protected Configuration configuration;
protected MainView mainView;
protected GoToController goToController;
protected OpenTypeController openTypeController;
protected OpenTypeHierarchyController openTypeHierarchyController;
protected PreferencesController preferencesController;
protected SearchInConstantPoolsController searchInConstantPoolsController;
protected SaveAllSourcesController saveAllSourcesController;
protected SelectLocationController selectLocationController;
protected AboutController aboutController;
protected SourceLoaderService sourceLoaderService;
protected History history = new History();
protected JComponent currentPage = null;
protected ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
protected ArrayList containerChangeListeners = new ArrayList<>();
@SuppressWarnings("unchecked")
public MainController(Configuration configuration) {
this.configuration = configuration;
SwingUtil.invokeLater(() -> {
if (PlatformService.getInstance().isLinux()) {
// Fix for GTKLookAndFeel
SwingUtil.installGtkPopupBugWorkaround();
}
// Create main frame
mainView = new MainView(
configuration, this, history,
e -> onOpen(),
e -> onClose(),
e -> onSaveSource(),
e -> onSaveAllSources(),
e -> System.exit(0),
e -> onCopy(),
e -> onPaste(),
e -> onSelectAll(),
e -> onFind(),
e -> onFindPrevious(),
e -> onFindNext(),
e -> onFindCriteriaChanged(),
() -> onFindCriteriaChanged(),
e -> onOpenType(),
e -> onOpenTypeHierarchy(),
e -> onGoTo(),
e -> openURI(history.backward()),
e -> openURI(history.forward()),
e -> onSearch(),
e -> onJdWebSite(),
e -> onJdGuiIssues(),
e -> onJdCoreIssues(),
e -> onPreferences(),
e -> onAbout(),
() -> panelClosed(),
page -> onCurrentPageChanged((JComponent)page),
file -> openFile((File)file));
});
}
// --- Show GUI --- //
@SuppressWarnings("unchecked")
public void show(List files) {
SwingUtil.invokeLater(() -> {
// Show main frame
mainView.show(configuration.getMainWindowLocation(), configuration.getMainWindowSize(), configuration.isMainWindowMaximize());
if (!files.isEmpty()) {
openFiles(files);
}
});
// Background initializations
executor.schedule(() -> {
// Background service initialization
UriLoaderService.getInstance();
FileLoaderService.getInstance();
ContainerFactoryService.getInstance();
IndexerService.getInstance();
TreeNodeFactoryService.getInstance();
TypeFactoryService.getInstance();
SwingUtil.invokeLater(() -> {
// Populate recent files menu
mainView.updateRecentFilesMenu(configuration.getRecentFiles());
// Background controller creation
JFrame mainFrame = mainView.getMainFrame();
saveAllSourcesController = new SaveAllSourcesController(MainController.this, mainFrame);
containerChangeListeners.add(openTypeController = new OpenTypeController(MainController.this, executor, mainFrame));
containerChangeListeners.add(openTypeHierarchyController = new OpenTypeHierarchyController(MainController.this, executor, mainFrame));
goToController = new GoToController(configuration, mainFrame);
containerChangeListeners.add(searchInConstantPoolsController = new SearchInConstantPoolsController(MainController.this, executor, mainFrame));
preferencesController = new PreferencesController(configuration, mainFrame, PreferencesPanelService.getInstance().getProviders());
selectLocationController = new SelectLocationController(MainController.this, mainFrame);
aboutController = new AboutController(mainFrame);
sourceLoaderService = new SourceLoaderService();
// Add listeners
mainFrame.addComponentListener(new MainFrameListener(configuration));
// Set drop files transfer handler
mainFrame.setTransferHandler(new FilesTransferHandler());
// Background class loading
new JFileChooser().addChoosableFileFilter(new FileNameExtensionFilter("", "dummy"));
FileSystemView.getFileSystemView().isFileSystemRoot(new File("dummy"));
new JLayer();
});
}, 400, TimeUnit.MILLISECONDS);
PasteHandlerService.getInstance();
PreferencesPanelService.getInstance();
ContextualActionsFactoryService.getInstance();
SourceSaverService.getInstance();
}
// --- Actions --- //
protected void onOpen() {
Map loaders = FileLoaderService.getInstance().getMapProviders();
StringBuilder sb = new StringBuilder();
ArrayList extensions = new ArrayList<>(loaders.keySet());
extensions.sort(null);
for (String extension : extensions) {
sb.append("*.").append(extension).append(", ");
}
sb.setLength(sb.length()-2);
String description = sb.toString();
String[] array = extensions.toArray(new String[0]);
JFileChooser chooser = new JFileChooser();
chooser.removeChoosableFileFilter(chooser.getFileFilter());
chooser.addChoosableFileFilter(new FileNameExtensionFilter("All files (" + description + ")", array));
for (String extension : extensions) {
FileLoader loader = loaders.get(extension);
chooser.addChoosableFileFilter(new FileNameExtensionFilter(loader.getDescription(), loader.getExtensions()));
}
chooser.setCurrentDirectory(configuration.getRecentLoadDirectory());
if (chooser.showOpenDialog(mainView.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
configuration.setRecentLoadDirectory(chooser.getCurrentDirectory());
openFile(chooser.getSelectedFile());
}
}
protected void onClose() {
mainView.closeCurrentTab();
}
protected void onSaveSource() {
if (currentPage instanceof ContentSavable) {
JFileChooser chooser = new JFileChooser();
JFrame mainFrame = mainView.getMainFrame();
chooser.setSelectedFile(new File(configuration.getRecentSaveDirectory(), ((ContentSavable)currentPage).getFileName()));
if (chooser.showSaveDialog(mainFrame) == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
configuration.setRecentSaveDirectory(chooser.getCurrentDirectory());
if (selectedFile.exists()) {
String title = "Are you sure?";
String message = "The file '" + selectedFile.getAbsolutePath() + "' already isContainsIn.\n Do you want to replace the existing file?";
if (JOptionPane.showConfirmDialog(mainFrame, message, title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
save(selectedFile);
}
} else {
save(selectedFile);
}
}
}
}
protected void save(File selectedFile) {
try (OutputStream os = new FileOutputStream(selectedFile)) {
((ContentSavable)currentPage).save(this, os);
} catch (IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
}
protected void onSaveAllSources() {
if (! saveAllSourcesController.isActivated()) {
JComponent currentPanel = mainView.getSelectedMainPanel();
if (currentPanel instanceof SourcesSavable) {
SourcesSavable sourcesSavable = (SourcesSavable)currentPanel;
JFileChooser chooser = new JFileChooser();
JFrame mainFrame = mainView.getMainFrame();
chooser.setSelectedFile(new File(configuration.getRecentSaveDirectory(), sourcesSavable.getSourceFileName()));
if (chooser.showSaveDialog(mainFrame) == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
configuration.setRecentSaveDirectory(chooser.getCurrentDirectory());
if (selectedFile.exists()) {
String title = "Are you sure?";
String message = "The file '" + selectedFile.getAbsolutePath() + "' already isContainsIn.\n Do you want to replace the existing file?";
if (JOptionPane.showConfirmDialog(mainFrame, message, title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
saveAllSourcesController.show(executor, sourcesSavable, selectedFile);
}
} else {
saveAllSourcesController.show(executor, sourcesSavable, selectedFile);
}
}
}
}
}
protected void onCopy() {
if (currentPage instanceof ContentCopyable) {
((ContentCopyable)currentPage).copy();
}
}
protected void onPaste() {
try {
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if ((transferable != null) && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
Object obj = transferable.getTransferData(DataFlavor.stringFlavor);
PasteHandler pasteHandler = PasteHandlerService.getInstance().get(obj);
if (pasteHandler != null) {
pasteHandler.paste(this, obj);
}
}
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
}
protected void onSelectAll() {
if (currentPage instanceof ContentSelectable) {
((ContentSelectable)currentPage).selectAll();
}
}
protected void onFind() {
if (currentPage instanceof ContentSearchable) {
mainView.showFindPanel();
}
}
protected void onFindCriteriaChanged() {
if (currentPage instanceof ContentSearchable) {
mainView.setFindBackgroundColor(((ContentSearchable)currentPage).highlightText(mainView.getFindText(), mainView.getFindCaseSensitive()));
}
}
protected void onFindNext() {
if (currentPage instanceof ContentSearchable) {
((ContentSearchable)currentPage).findNext(mainView.getFindText(), mainView.getFindCaseSensitive());
}
}
protected void onOpenType() {
openTypeController.show(getCollectionOfFutureIndexes(), uri -> openURI(uri));
}
protected void onOpenTypeHierarchy() {
if (currentPage instanceof FocusedTypeGettable) {
FocusedTypeGettable ftg = (FocusedTypeGettable)currentPage;
openTypeHierarchyController.show(getCollectionOfFutureIndexes(), ftg.getEntry(), ftg.getFocusedTypeName(), uri -> openURI(uri));
}
}
protected void onGoTo() {
if (currentPage instanceof LineNumberNavigable) {
LineNumberNavigable lnn = (LineNumberNavigable)currentPage;
goToController.show(lnn, lineNumber -> lnn.goToLineNumber(lineNumber));
}
}
protected void onSearch() {
searchInConstantPoolsController.show(getCollectionOfFutureIndexes(), uri -> openURI(uri));
}
protected void onFindPrevious() {
if (currentPage instanceof ContentSearchable) {
ContentSearchable cs = (ContentSearchable)currentPage;
cs.findPrevious(mainView.getFindText(), mainView.getFindCaseSensitive());
}
}
protected void onJdWebSite() {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(URI.create("http://java-decompiler.github.io"));
} catch (IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
}
}
}
protected void onJdGuiIssues() {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(URI.create("https://github.com/java-decompiler/jd-gui/issues"));
} catch (IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
}
}
}
protected void onJdCoreIssues() {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(URI.create("https://github.com/java-decompiler/jd-core/issues"));
} catch (IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
}
}
}
@SuppressWarnings("unchecked")
protected void onPreferences() {
preferencesController.show(() -> {
checkPreferencesChange(currentPage);
mainView.preferencesChanged(getPreferences());
});
}
protected void onAbout() {
aboutController.show();
}
protected void onCurrentPageChanged(JComponent page) {
currentPage = page;
checkPreferencesChange(page);
checkIndexesChange(page);
}
protected void checkPreferencesChange(JComponent page) {
if (page instanceof PreferencesChangeListener) {
Map preferences = configuration.getPreferences();
Integer currentHashcode = Integer.valueOf(preferences.hashCode());
Integer lastHashcode = (Integer)page.getClientProperty("preferences-hashCode");
if (!currentHashcode.equals(lastHashcode)) {
((PreferencesChangeListener)page).preferencesChanged(preferences);
page.putClientProperty("preferences-hashCode", currentHashcode);
}
}
}
protected void checkIndexesChange(JComponent page) {
if (page instanceof IndexesChangeListener) {
Collection> collectionOfFutureIndexes = getCollectionOfFutureIndexes();
Integer currentHashcode = Integer.valueOf(collectionOfFutureIndexes.hashCode());
Integer lastHashcode = (Integer)page.getClientProperty("collectionOfFutureIndexes-hashCode");
if (!currentHashcode.equals(lastHashcode)) {
((IndexesChangeListener)page).indexesChanged(collectionOfFutureIndexes);
page.putClientProperty("collectionOfFutureIndexes-hashCode", currentHashcode);
}
}
}
// --- Operations --- //
public void openFile(File file) {
openFiles(Collections.singletonList(file));
}
@SuppressWarnings("unchecked")
public void openFiles(List files) {
ArrayList errors = new ArrayList<>();
for (File file : files) {
// Check input file
if (file.exists()) {
FileLoader loader = getFileLoader(file);
if ((loader != null) && !loader.accept(this, file)) {
errors.add("Invalid input fileloader: '" + file.getAbsolutePath() + "'");
}
} else {
errors.add("File not found: '" + file.getAbsolutePath() + "'");
}
}
if (errors.isEmpty()) {
for (File file : files) {
if (openURI(file.toURI())) {
configuration.addRecentFile(file);
mainView.updateRecentFilesMenu(configuration.getRecentFiles());
}
}
} else {
StringBuilder messages = new StringBuilder();
int index = 0;
for (String error : errors) {
if (index > 0) {
messages.append('\n');
}
if (index >= 20) {
messages.append("...");
break;
}
messages.append(error);
index++;
}
JOptionPane.showMessageDialog(mainView.getMainFrame(), messages.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
// --- Drop files transfer handler --- //
protected class FilesTransferHandler extends TransferHandler {
@Override
public boolean canImport(TransferHandler.TransferSupport info) {
return info.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
@Override
@SuppressWarnings("unchecked")
public boolean importData(TransferHandler.TransferSupport info) {
if (info.isDrop() && info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
try {
openFiles((List)info.getTransferable().getTransferData(DataFlavor.javaFileListFlavor));
return true;
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
}
return false;
}
}
// --- ComponentListener --- //
protected class MainFrameListener extends ComponentAdapter {
protected Configuration configuration;
public MainFrameListener(Configuration configuration) {
this.configuration = configuration;
}
@Override
public void componentMoved(ComponentEvent e) {
JFrame mainFrame = mainView.getMainFrame();
if ((mainFrame.getExtendedState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
configuration.setMainWindowMaximize(true);
} else {
configuration.setMainWindowLocation(mainFrame.getLocation());
configuration.setMainWindowMaximize(false);
}
}
@Override
public void componentResized(ComponentEvent e) {
JFrame mainFrame = mainView.getMainFrame();
if ((mainFrame.getExtendedState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
configuration.setMainWindowMaximize(true);
} else {
configuration.setMainWindowSize(mainFrame.getSize());
configuration.setMainWindowMaximize(false);
}
}
}
protected void panelClosed() {
SwingUtil.invokeLater(() -> {
// Fire 'indexesChanged' event
Collection> collectionOfFutureIndexes = getCollectionOfFutureIndexes();
for (IndexesChangeListener listener : containerChangeListeners) {
listener.indexesChanged(collectionOfFutureIndexes);
}
if (currentPage instanceof IndexesChangeListener) {
((IndexesChangeListener)currentPage).indexesChanged(collectionOfFutureIndexes);
}
});
}
// --- API --- //
@Override
@SuppressWarnings("unchecked")
public boolean openURI(URI uri) {
if (uri != null) {
boolean success = mainView.openUri(uri);
if (success == false) {
UriLoader uriLoader = getUriLoader(uri);
if (uriLoader != null) {
success = uriLoader.load(this, uri);
}
}
if (success) {
addURI(uri);
}
return success;
}
return false;
}
@Override
public boolean openURI(int x, int y, Collection entries, String query, String fragment) {
if (entries != null) {
if (entries.size() == 1) {
// Open the single entry uri
Container.Entry entry = entries.iterator().next();
return openURI(UriUtil.createURI(this, getCollectionOfFutureIndexes(), entry, query, fragment));
} else {
// Multiple entries -> Open a "Select location" popup
Collection> collectionOfFutureIndexes = getCollectionOfFutureIndexes();
selectLocationController.show(
new Point(x+(16+2), y+2),
entries,
entry -> openURI(UriUtil.createURI(this, collectionOfFutureIndexes, entry, query, fragment)), // entry selected closure
() -> {}); // popup close closure
return true;
}
}
return false;
}
@Override
public void addURI(URI uri) {
history.add(uri);
SwingUtil.invokeLater(() -> {
mainView.updateHistoryActions();
});
}
@Override
@SuppressWarnings("unchecked")
public void addPanel(String title, Icon icon, String tip, T component) {
mainView.addMainPanel(title, icon, tip, component);
if (component instanceof ContentIndexable) {
Future futureIndexes = executor.submit(() -> {
Indexes indexes = ((ContentIndexable)component).index(this);
SwingUtil.invokeLater(() -> {
// Fire 'indexesChanged' event
Collection> collectionOfFutureIndexes = getCollectionOfFutureIndexes();
for (IndexesChangeListener listener : containerChangeListeners) {
listener.indexesChanged(collectionOfFutureIndexes);
}
if (currentPage instanceof IndexesChangeListener) {
((IndexesChangeListener) currentPage).indexesChanged(collectionOfFutureIndexes);
}
});
return indexes;
});
component.putClientProperty("indexes", futureIndexes);
}
}
@Override public Collection getContextualActions(Container.Entry entry, String fragment) { return ContextualActionsFactoryService.getInstance().get(this, entry, fragment); }
@Override public FileLoader getFileLoader(File file) { return FileLoaderService.getInstance().get(this, file); }
@Override public UriLoader getUriLoader(URI uri) { return UriLoaderService.getInstance().get(this, uri); }
@Override public PanelFactory getMainPanelFactory(Container container) { return PanelFactoryService.getInstance().get(container); }
@Override public ContainerFactory getContainerFactory(Path rootPath) { return ContainerFactoryService.getInstance().get(this, rootPath); }
@Override public TreeNodeFactory getTreeNodeFactory(Container.Entry entry) { return TreeNodeFactoryService.getInstance().get(entry); }
@Override public TypeFactory getTypeFactory(Container.Entry entry) { return TypeFactoryService.getInstance().get(entry); }
@Override public Indexer getIndexer(Container.Entry entry) { return IndexerService.getInstance().get(entry); }
@Override public SourceSaver getSourceSaver(Container.Entry entry) { return SourceSaverService.getInstance().get(entry); }
@Override public Map getPreferences() { return configuration.getPreferences(); }
@Override
@SuppressWarnings("unchecked")
public Collection> getCollectionOfFutureIndexes() {
List mainPanels = mainView.getMainPanels();
ArrayList> list = new ArrayList>(mainPanels.size()) {
@Override
public int hashCode() {
int hashCode = 1;
try {
for (Future futureIndexes : this) {
hashCode *= 31;
if (futureIndexes.isDone()) {
hashCode += futureIndexes.get().hashCode();
}
}
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
return hashCode;
}
};
for (JComponent panel : mainPanels) {
Future futureIndexes = (Future)panel.getClientProperty("indexes");
if (futureIndexes != null) {
list.add(futureIndexes);
}
}
return list;
}
@Override
public String getSource(Container.Entry entry) {
return sourceLoaderService.getSource(this, entry);
}
@Override
public void loadSource(Container.Entry entry, LoadSourceListener listener) {
executor.execute(() -> {
String source = sourceLoaderService.loadSource(this, entry);
if ((source != null) && !source.isEmpty()) {
listener.sourceLoaded(source);
}
});
}
@Override
public File loadSourceFile(Container.Entry entry) {
return sourceLoaderService.getSourceFile(this, entry);
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/OpenTypeController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.IndexesChangeListener;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.net.UriUtil;
import org.jd.gui.view.OpenTypeView;
import javax.swing.*;
import java.awt.*;
import java.net.URI;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import java.util.regex.Pattern;
public class OpenTypeController implements IndexesChangeListener {
protected static final int CACHE_MAX_ENTRIES = 5*20;
protected API api;
protected ScheduledExecutorService executor;
protected Collection> collectionOfFutureIndexes;
protected Consumer openCallback;
protected JFrame mainFrame;
protected OpenTypeView openTypeView;
protected SelectLocationController selectLocationController;
protected long indexesHashCode = 0L;
protected Map> cache;
public OpenTypeController(API api, ScheduledExecutorService executor, JFrame mainFrame) {
this.api = api;
this.executor = executor;
this.mainFrame = mainFrame;
// Create UI
openTypeView = new OpenTypeView(api, mainFrame, this::updateList, this::onTypeSelected);
selectLocationController = new SelectLocationController(api, mainFrame);
// Create result cache
cache = new LinkedHashMap>(CACHE_MAX_ENTRIES*3/2, 0.7f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry> eldest) {
return size() > CACHE_MAX_ENTRIES;
}
};
}
public void show(Collection> collectionOfFutureIndexes, Consumer openCallback) {
// Init attributes
this.collectionOfFutureIndexes = collectionOfFutureIndexes;
this.openCallback = openCallback;
// Refresh view
long hashCode = collectionOfFutureIndexes.hashCode();
if (hashCode != indexesHashCode) {
// List of indexes has changed -> Refresh result list
updateList(openTypeView.getPattern());
indexesHashCode = hashCode;
}
// Show
openTypeView.show();
}
@SuppressWarnings("unchecked")
protected void updateList(String pattern) {
int patternLength = pattern.length();
if (patternLength == 0) {
// Display
openTypeView.updateList(Collections.emptyMap());
} else {
executor.execute(() -> {
// Waiting the end of indexation...
openTypeView.showWaitCursor();
Pattern regExpPattern = createRegExpPattern(pattern);
Map> result = new HashMap<>();
try {
for (Future futureIndexes : collectionOfFutureIndexes) {
if (futureIndexes.isDone()) {
Indexes indexes = futureIndexes.get();
String key = String.valueOf(indexes.hashCode()) + "***" + pattern;
Map matchingEntries = cache.get(key);
if (matchingEntries != null) {
// Merge 'result' and 'matchingEntries'
for (Map.Entry mapEntry : matchingEntries.entrySet()) {
Collection collection = result.get(mapEntry.getKey());
if (collection == null) {
result.put(mapEntry.getKey(), collection = new HashSet<>());
}
collection.addAll(mapEntry.getValue());
}
} else {
// Waiting the end of indexation...
Map index = indexes.getIndex("typeDeclarations");
if ((index != null) && !index.isEmpty()) {
matchingEntries = new HashMap<>();
// Filter
if (patternLength == 1) {
match(pattern.charAt(0), index, matchingEntries);
} else {
String lastKey = key.substring(0, patternLength - 1);
Map lastResult = cache.get(lastKey);
if (lastResult != null) {
match(regExpPattern, lastResult, matchingEntries);
} else {
match(regExpPattern, index, matchingEntries);
}
}
// Store 'matchingEntries'
cache.put(key, matchingEntries);
// Merge 'result' and 'matchingEntries'
for (Map.Entry mapEntry : matchingEntries.entrySet()) {
Collection collection = result.get(mapEntry.getKey());
if (collection == null) {
result.put(mapEntry.getKey(), collection = new HashSet<>());
}
collection.addAll(mapEntry.getValue());
}
}
}
}
}
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
SwingUtilities.invokeLater(() -> {
openTypeView.hideWaitCursor();
// Display
openTypeView.updateList(result);
});
});
}
}
@SuppressWarnings("unchecked")
protected static void match(char c, Map index, Map result) {
// Filter
if (Character.isLowerCase(c)) {
char upperCase = Character.toUpperCase(c);
for (Map.Entry mapEntry : index.entrySet()) {
String typeName = mapEntry.getKey();
Collection entries = mapEntry.getValue();
// Search last package separator
int lastPackageSeparatorIndex = typeName.lastIndexOf('/') + 1;
int lastTypeNameSeparatorIndex = typeName.lastIndexOf('$') + 1;
int lastIndex = Math.max(lastPackageSeparatorIndex, lastTypeNameSeparatorIndex);
if (lastIndex < typeName.length()) {
char first = typeName.charAt(lastIndex);
if ((first == c) || (first == upperCase)) {
add(result, typeName, entries);
}
}
}
} else {
for (Map.Entry mapEntry : index.entrySet()) {
String typeName = mapEntry.getKey();
Collection entries = mapEntry.getValue();
// Search last package separator
int lastPackageSeparatorIndex = typeName.lastIndexOf('/') + 1;
int lastTypeNameSeparatorIndex = typeName.lastIndexOf('$') + 1;
int lastIndex = Math.max(lastPackageSeparatorIndex, lastTypeNameSeparatorIndex);
if ((lastIndex < typeName.length()) && (typeName.charAt(lastIndex) == c)) {
add(result, typeName, entries);
}
}
}
}
/**
* Create a regular expression to match package, type and inner type name.
*
* Rules:
* '*' matches 0 ou N characters
* '?' matches 1 character
* lower case matches insensitive case
* upper case matches upper case
*/
protected static Pattern createRegExpPattern(String pattern) {
// Create regular expression
int patternLength = pattern.length();
StringBuilder sbPattern = new StringBuilder(patternLength * 4);
for (int i=0; i 1) {
sbPattern.append(".*");
}
sbPattern.append(c);
} else if (Character.isLowerCase(c)) {
sbPattern.append('[').append(c).append(Character.toUpperCase(c)).append(']');
} else if (c == '*') {
sbPattern.append(".*");
} else if (c == '?') {
sbPattern.append(".");
} else {
sbPattern.append(c);
}
}
sbPattern.append(".*");
return Pattern.compile(sbPattern.toString());
}
@SuppressWarnings("unchecked")
protected static void match(Pattern regExpPattern, Map index, Map result) {
for (Map.Entry mapEntry : index.entrySet()) {
String typeName = mapEntry.getKey();
Collection entries = mapEntry.getValue();
// Search last package separator
int lastPackageSeparatorIndex = typeName.lastIndexOf('/') + 1;
int lastTypeNameSeparatorIndex = typeName.lastIndexOf('$') + 1;
int lastIndex = Math.max(lastPackageSeparatorIndex, lastTypeNameSeparatorIndex);
if (regExpPattern.matcher(typeName.substring(lastIndex)).matches()) {
add(result, typeName, entries);
}
}
}
@SuppressWarnings("unchecked")
protected static void add(Map map, String key, Collection value) {
Collection collection = map.get(key);
if (collection == null) {
map.put(key, collection = new HashSet<>());
}
collection.addAll(value);
}
protected void onTypeSelected(Point leftBottom, Collection entries, String typeName) {
if (entries.size() == 1) {
// Open the single entry uri
openCallback.accept(UriUtil.createURI(api, collectionOfFutureIndexes, entries.iterator().next(), null, typeName));
} else {
// Multiple entries -> Open a "Select location" popup
selectLocationController.show(
new Point(leftBottom.x+(16+2), leftBottom.y+2),
entries,
(entry) -> openCallback.accept(UriUtil.createURI(api, collectionOfFutureIndexes, entry, null, typeName)), // entry selected callback
() -> openTypeView.focus()); // popup close callback
}
}
// --- IndexesChangeListener --- //
public void indexesChanged(Collection> collectionOfFutureIndexes) {
if (openTypeView.isVisible()) {
// Update the list of containers
this.collectionOfFutureIndexes = collectionOfFutureIndexes;
// And refresh
updateList(openTypeView.getPattern());
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/OpenTypeHierarchyController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.IndexesChangeListener;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.util.net.UriUtil;
import org.jd.gui.view.OpenTypeHierarchyView;
import javax.swing.*;
import java.awt.*;
import java.net.URI;
import java.util.Collection;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
public class OpenTypeHierarchyController implements IndexesChangeListener {
protected API api;
private ScheduledExecutorService executor;
protected JFrame mainFrame;
protected OpenTypeHierarchyView openTypeHierarchyView;
protected SelectLocationController selectLocationController;
protected Collection> collectionOfFutureIndexes;
protected Consumer openCallback;
public OpenTypeHierarchyController(API api, ScheduledExecutorService executor, JFrame mainFrame) {
this.api = api;
this.executor = executor;
this.mainFrame = mainFrame;
// Create UI
openTypeHierarchyView = new OpenTypeHierarchyView(api, mainFrame, this::onTypeSelected);
selectLocationController = new SelectLocationController(api, mainFrame);
}
public void show(Collection> collectionOfFutureIndexes, Container.Entry entry, String typeName, Consumer openCallback) {
// Init attributes
this.collectionOfFutureIndexes = collectionOfFutureIndexes;
this.openCallback = openCallback;
executor.execute(() -> {
// Waiting the end of indexation...
openTypeHierarchyView.showWaitCursor();
SwingUtilities.invokeLater(() -> {
openTypeHierarchyView.hideWaitCursor();
// Show
openTypeHierarchyView.show(collectionOfFutureIndexes, entry, typeName);
});
});
}
protected void onTypeSelected(Point leftBottom, Collection entries, String typeName) {
if (entries.size() == 1) {
// Open the single entry uri
openCallback.accept(UriUtil.createURI(api, collectionOfFutureIndexes, entries.iterator().next(), null, typeName));
} else {
// Multiple entries -> Open a "Select location" popup
selectLocationController.show(
new Point(leftBottom.x+(16+2), leftBottom.y+2),
entries,
(entry) -> openCallback.accept(UriUtil.createURI(api, collectionOfFutureIndexes, entry, null, typeName)), // entry selected
() -> openTypeHierarchyView.focus()); // popup closeClosure
}
}
// --- IndexesChangeListener --- //
public void indexesChanged(Collection> collectionOfFutureIndexes) {
if (openTypeHierarchyView.isVisible()) {
// Update the list of containers
this.collectionOfFutureIndexes = collectionOfFutureIndexes;
// And refresh
openTypeHierarchyView.updateTree(collectionOfFutureIndexes);
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/PreferencesController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.model.configuration.Configuration;
import org.jd.gui.spi.PreferencesPanel;
import org.jd.gui.view.PreferencesView;
import javax.swing.*;
import java.util.Collection;
public class PreferencesController {
protected PreferencesView preferencesView;
public PreferencesController(Configuration configuration, JFrame mainFrame, Collection panels) {
// Create UI
preferencesView = new PreferencesView(configuration, mainFrame, panels);
}
public void show(Runnable okCallback) {
// Show
preferencesView.show(okCallback);
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/SaveAllSourcesController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.SourcesSavable;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.view.SaveAllSourcesView;
import javax.swing.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ScheduledExecutorService;
public class SaveAllSourcesController implements SourcesSavable.Controller, SourcesSavable.Listener {
protected API api;
protected SaveAllSourcesView saveAllSourcesView;
protected boolean cancel;
protected int counter;
protected int mask;
public SaveAllSourcesController(API api, JFrame mainFrame) {
this.api = api;
// Create UI
this.saveAllSourcesView = new SaveAllSourcesView(mainFrame, this::onCanceled);
}
public void show(ScheduledExecutorService executor, SourcesSavable savable, File file) {
// Show
this.saveAllSourcesView.show(file);
// Execute background task
executor.execute(() -> {
int fileCount = savable.getFileCount();
saveAllSourcesView.updateProgressBar(0);
saveAllSourcesView.setMaxValue(fileCount);
cancel = false;
counter = 0;
mask = 2;
while (fileCount > 64) {
fileCount >>= 1;
mask <<= 1;
}
mask--;
try {
Path path = Paths.get(file.toURI());
Files.deleteIfExists(path);
try {
savable.save(api, this, this, path);
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
saveAllSourcesView.showActionFailedDialog();
cancel = true;
}
if (cancel) {
Files.deleteIfExists(path);
}
} catch (Throwable t) {
assert ExceptionUtil.printStackTrace(t);
}
saveAllSourcesView.hide();
});
}
public boolean isActivated() { return saveAllSourcesView.isVisible(); }
protected void onCanceled() { cancel = true; }
// --- SourcesSavable.Controller --- //
@Override public boolean isCancelled() { return cancel; }
// --- SourcesSavable.Listener --- //
@Override
public void pathSaved(Path path) {
if (((counter++) & mask) == 0) {
saveAllSourcesView.updateProgressBar(counter);
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/SearchInConstantPoolsController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.IndexesChangeListener;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.api.model.Type;
import org.jd.gui.model.container.DelegatingFilterContainer;
import org.jd.gui.service.type.TypeFactoryService;
import org.jd.gui.spi.TypeFactory;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.function.TriConsumer;
import org.jd.gui.view.SearchInConstantPoolsView;
import javax.swing.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.regex.Pattern;
public class SearchInConstantPoolsController implements IndexesChangeListener {
protected static final int CACHE_MAX_ENTRIES = 5*20*9;
protected API api;
protected ScheduledExecutorService executor;
protected JFrame mainFrame;
protected SearchInConstantPoolsView searchInConstantPoolsView;
protected Map> cache;
protected Set delegatingFilterContainers = new HashSet<>();
protected Collection> collectionOfFutureIndexes;
protected Consumer openCallback;
protected long indexesHashCode = 0L;
@SuppressWarnings("unchecked")
public SearchInConstantPoolsController(API api, ScheduledExecutorService executor, JFrame mainFrame) {
this.api = api;
this.executor = executor;
this.mainFrame = mainFrame;
// Create UI
this.searchInConstantPoolsView = new SearchInConstantPoolsView(
api, mainFrame,
new BiConsumer() {
@Override public void accept(String pattern, Integer flags) { updateTree(pattern, flags); }
},
new TriConsumer() {
@Override public void accept(URI uri, String pattern, Integer flags) { onTypeSelected(uri, pattern, flags); }
}
);
// Create result cache
this.cache = new LinkedHashMap>(CACHE_MAX_ENTRIES*3/2, 0.7f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry> eldest) {
return size() > CACHE_MAX_ENTRIES;
}
};
}
public void show(Collection> collectionOfFutureIndexes, Consumer openCallback) {
// Init attributes
this.collectionOfFutureIndexes = collectionOfFutureIndexes;
this.openCallback = openCallback;
// Refresh view
long hashCode = collectionOfFutureIndexes.hashCode();
if (hashCode != indexesHashCode) {
// List of indexes has changed
updateTree(searchInConstantPoolsView.getPattern(), searchInConstantPoolsView.getFlags());
indexesHashCode = hashCode;
}
// Show
searchInConstantPoolsView.show();
}
@SuppressWarnings("unchecked")
protected void updateTree(String pattern, int flags) {
delegatingFilterContainers.clear();
executor.execute(() -> {
// Waiting the end of indexation...
searchInConstantPoolsView.showWaitCursor();
int matchingTypeCount = 0;
int patternLength = pattern.length();
if (patternLength > 0) {
try {
for (Future futureIndexes : collectionOfFutureIndexes) {
if (futureIndexes.isDone()) {
Indexes indexes = futureIndexes.get();
HashSet matchingEntries = new HashSet<>();
// Find matched entries
filter(indexes, pattern, flags, matchingEntries);
if (!matchingEntries.isEmpty()) {
// Search root container with first matching entry
Container.Entry parentEntry = matchingEntries.iterator().next();
Container container = null;
while (parentEntry.getContainer().getRoot() != null) {
container = parentEntry.getContainer();
parentEntry = container.getRoot().getParent();
}
// TODO In a future release, display matching strings, types, inner-types, fields and methods, not only matching files
matchingEntries = getOuterEntries(matchingEntries);
matchingTypeCount += matchingEntries.size();
// Create a filtered container
delegatingFilterContainers.add(new DelegatingFilterContainer(container, matchingEntries));
}
}
}
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
}
final int count = matchingTypeCount;
searchInConstantPoolsView.hideWaitCursor();
searchInConstantPoolsView.updateTree(delegatingFilterContainers, count);
});
}
protected HashSet getOuterEntries(Set matchingEntries) {
HashMap innerTypeEntryToOuterTypeEntry = new HashMap<>();
HashSet matchingOuterEntriesSet = new HashSet<>();
for (Container.Entry entry : matchingEntries) {
TypeFactory typeFactory = TypeFactoryService.getInstance().get(entry);
if (typeFactory != null) {
Type type = typeFactory.make(api, entry, null);
if ((type != null) && (type.getOuterName() != null)) {
Container.Entry outerTypeEntry = innerTypeEntryToOuterTypeEntry.get(entry);
if (outerTypeEntry == null) {
HashMap typeNameToEntry = new HashMap<>();
HashMap innerTypeNameToOuterTypeName = new HashMap<>();
// Populate "typeNameToEntry" and "innerTypeNameToOuterTypeName"
for (Container.Entry e : entry.getParent().getChildren()) {
typeFactory = TypeFactoryService.getInstance().get(e);
if (typeFactory != null) {
type = typeFactory.make(api, e, null);
if (type != null) {
typeNameToEntry.put(type.getName(), e);
if (type.getOuterName() != null) {
innerTypeNameToOuterTypeName.put(type.getName(), type.getOuterName());
}
}
}
}
// Search outer type entries and populate "innerTypeEntryToOuterTypeEntry"
for (Map.Entry e : innerTypeNameToOuterTypeName.entrySet()) {
Container.Entry innerTypeEntry = typeNameToEntry.get(e.getKey());
if (innerTypeEntry != null) {
String outerTypeName = e.getValue();
for (;;) {
String typeName = innerTypeNameToOuterTypeName.get(outerTypeName);
if (typeName != null) {
outerTypeName = typeName;
} else {
break;
}
}
outerTypeEntry = typeNameToEntry.get(outerTypeName);
if (outerTypeEntry != null) {
innerTypeEntryToOuterTypeEntry.put(innerTypeEntry, outerTypeEntry);
}
}
}
// Get outer type entry
outerTypeEntry = innerTypeEntryToOuterTypeEntry.get(entry);
if (outerTypeEntry == null) {
outerTypeEntry = entry;
}
}
matchingOuterEntriesSet.add(outerTypeEntry);
} else{
matchingOuterEntriesSet.add(entry);
}
}
}
return matchingOuterEntriesSet;
}
protected void filter(Indexes indexes, String pattern, int flags, Set matchingEntries) {
boolean declarations = ((flags & SearchInConstantPoolsView.SEARCH_DECLARATION) != 0);
boolean references = ((flags & SearchInConstantPoolsView.SEARCH_REFERENCE) != 0);
if ((flags & SearchInConstantPoolsView.SEARCH_TYPE) != 0) {
if (declarations)
match(indexes, "typeDeclarations", pattern,
SearchInConstantPoolsController::matchTypeEntriesWithChar,
SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
if (references)
match(indexes, "typeReferences", pattern,
SearchInConstantPoolsController::matchTypeEntriesWithChar,
SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
}
if ((flags & SearchInConstantPoolsView.SEARCH_CONSTRUCTOR) != 0) {
if (declarations)
match(indexes, "constructorDeclarations", pattern,
SearchInConstantPoolsController::matchTypeEntriesWithChar,
SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
if (references)
match(indexes, "constructorReferences", pattern,
SearchInConstantPoolsController::matchTypeEntriesWithChar,
SearchInConstantPoolsController::matchTypeEntriesWithString, matchingEntries);
}
if ((flags & SearchInConstantPoolsView.SEARCH_METHOD) != 0) {
if (declarations)
match(indexes, "methodDeclarations", pattern,
SearchInConstantPoolsController::matchWithChar,
SearchInConstantPoolsController::matchWithString, matchingEntries);
if (references)
match(indexes, "methodReferences", pattern,
SearchInConstantPoolsController::matchWithChar,
SearchInConstantPoolsController::matchWithString, matchingEntries);
}
if ((flags & SearchInConstantPoolsView.SEARCH_FIELD) != 0) {
if (declarations)
match(indexes, "fieldDeclarations", pattern,
SearchInConstantPoolsController::matchWithChar,
SearchInConstantPoolsController::matchWithString, matchingEntries);
if (references)
match(indexes, "fieldReferences", pattern,
SearchInConstantPoolsController::matchWithChar,
SearchInConstantPoolsController::matchWithString, matchingEntries);
}
if ((flags & SearchInConstantPoolsView.SEARCH_STRING) != 0) {
if (declarations || references)
match(indexes, "strings", pattern,
SearchInConstantPoolsController::matchWithChar,
SearchInConstantPoolsController::matchWithString, matchingEntries);
}
if ((flags & SearchInConstantPoolsView.SEARCH_MODULE) != 0) {
if (declarations)
match(indexes, "javaModuleDeclarations", pattern,
SearchInConstantPoolsController::matchWithChar,
SearchInConstantPoolsController::matchWithString, matchingEntries);
if (references)
match(indexes, "javaModuleReferences", pattern,
SearchInConstantPoolsController::matchWithChar,
SearchInConstantPoolsController::matchWithString, matchingEntries);
}
}
@SuppressWarnings("unchecked")
protected void match(Indexes indexes, String indexName, String pattern,
BiFunction, Map> matchWithCharFunction,
BiFunction, Map> matchWithStringFunction,
Set matchingEntries) {
int patternLength = pattern.length();
if (patternLength > 0) {
String key = String.valueOf(indexes.hashCode()) + "***" + indexName + "***" + pattern;
Map matchedEntries = cache.get(key);
if (matchedEntries == null) {
Map index = indexes.getIndex(indexName);
if (index != null) {
if (patternLength == 1) {
matchedEntries = matchWithCharFunction.apply(pattern.charAt(0), index);
} else {
String lastKey = key.substring(0, key.length() - 1);
Map lastMatchedTypes = cache.get(lastKey);
if (lastMatchedTypes != null) {
matchedEntries = matchWithStringFunction.apply(pattern, lastMatchedTypes);
} else {
matchedEntries = matchWithStringFunction.apply(pattern, index);
}
}
}
// Cache matchingEntries
cache.put(key, matchedEntries);
}
if (matchedEntries != null) {
for (Collection entries : matchedEntries.values()) {
matchingEntries.addAll(entries);
}
}
}
}
protected static Map matchTypeEntriesWithChar(char c, Map index) {
if ((c == '*') || (c == '?')) {
return index;
} else {
Map map = new HashMap<>();
for (String typeName : index.keySet()) {
// Search last package separator
int lastPackageSeparatorIndex = typeName.lastIndexOf('/') + 1;
int lastTypeNameSeparatorIndex = typeName.lastIndexOf('$') + 1;
int lastIndex = Math.max(lastPackageSeparatorIndex, lastTypeNameSeparatorIndex);
if ((lastIndex < typeName.length()) && (typeName.charAt(lastIndex) == c)) {
map.put(typeName, index.get(typeName));
}
}
return map;
}
}
protected static Map matchTypeEntriesWithString(String pattern, Map index) {
Pattern p = createPattern(pattern);
Map map = new HashMap<>();
for (String typeName : index.keySet()) {
// Search last package separator
int lastPackageSeparatorIndex = typeName.lastIndexOf('/') + 1;
int lastTypeNameSeparatorIndex = typeName.lastIndexOf('$') + 1;
int lastIndex = Math.max(lastPackageSeparatorIndex, lastTypeNameSeparatorIndex);
if (p.matcher(typeName.substring(lastIndex)).matches()) {
map.put(typeName, index.get(typeName));
}
}
return map;
}
protected static Map matchWithChar(char c, Map index) {
if ((c == '*') || (c == '?')) {
return index;
} else {
Map map = new HashMap<>();
for (String key : index.keySet()) {
if (!key.isEmpty() && (key.charAt(0) == c)) {
map.put(key, index.get(key));
}
}
return map;
}
}
protected static Map matchWithString(String pattern, Map index) {
Pattern p = createPattern(pattern);
Map map = new HashMap<>();
for (String key : index.keySet()) {
if (p.matcher(key).matches()) {
map.put(key, index.get(key));
}
}
return map;
}
/**
* Create a simple regular expression
*
* Rules:
* '*' matchTypeEntries 0 ou N characters
* '?' matchTypeEntries 1 character
*/
protected static Pattern createPattern(String pattern) {
int patternLength = pattern.length();
StringBuilder sbPattern = new StringBuilder(patternLength * 2);
for (int i = 0; i < patternLength; i++) {
char c = pattern.charAt(i);
if (c == '*') {
sbPattern.append(".*");
} else if (c == '?') {
sbPattern.append('.');
} else if (c == '.') {
sbPattern.append("\\.");
} else {
sbPattern.append(c);
}
}
sbPattern.append(".*");
return Pattern.compile(sbPattern.toString());
}
protected void onTypeSelected(URI uri, String pattern, int flags) {
// Open the single entry uri
Container.Entry entry = null;
for (DelegatingFilterContainer container : delegatingFilterContainers) {
entry = container.getEntry(uri);
if (entry != null)
break;
}
if (entry != null) {
StringBuilder sbPattern = new StringBuilder(200 + pattern.length());
sbPattern.append("highlightPattern=");
sbPattern.append(pattern);
sbPattern.append("&highlightFlags=");
if ((flags & SearchInConstantPoolsView.SEARCH_DECLARATION) != 0)
sbPattern.append('d');
if ((flags & SearchInConstantPoolsView.SEARCH_REFERENCE) != 0)
sbPattern.append('r');
if ((flags & SearchInConstantPoolsView.SEARCH_TYPE) != 0)
sbPattern.append('t');
if ((flags & SearchInConstantPoolsView.SEARCH_CONSTRUCTOR) != 0)
sbPattern.append('c');
if ((flags & SearchInConstantPoolsView.SEARCH_METHOD) != 0)
sbPattern.append('m');
if ((flags & SearchInConstantPoolsView.SEARCH_FIELD) != 0)
sbPattern.append('f');
if ((flags & SearchInConstantPoolsView.SEARCH_STRING) != 0)
sbPattern.append('s');
if ((flags & SearchInConstantPoolsView.SEARCH_MODULE) != 0)
sbPattern.append('M');
// TODO In a future release, add 'highlightScope' to display search results in correct type and inner-type
// def type = TypeFactoryService.instance.get(entry)?.make(api, entry, null)
// if (type) {
// sbPattern.append('&highlightScope=')
// sbPattern.append(type.name)
//
// def query = sbPattern.toString()
// def outerPath = UriUtil.getOuterPath(collectionOfFutureIndexes, entry, type)
//
// openClosure(new URI(entry.uri.scheme, entry.uri.host, outerPath, query, null))
// } else {
String query = sbPattern.toString();
URI u = entry.getUri();
try {
openCallback.accept(new URI(u.getScheme(), u.getHost(), u.getPath(), query, null));
} catch (URISyntaxException e) {
assert ExceptionUtil.printStackTrace(e);
}
// }
}
}
// --- IndexesChangeListener --- //
public void indexesChanged(Collection> collectionOfFutureIndexes) {
if (searchInConstantPoolsView.isVisible()) {
// Update the list of containers
this.collectionOfFutureIndexes = collectionOfFutureIndexes;
// And refresh
updateTree(searchInConstantPoolsView.getPattern(), searchInConstantPoolsView.getFlags());
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/controller/SelectLocationController.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.controller;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Type;
import org.jd.gui.model.container.DelegatingFilterContainer;
import org.jd.gui.service.type.TypeFactoryService;
import org.jd.gui.spi.TypeFactory;
import org.jd.gui.view.SelectLocationView;
import javax.swing.*;
import java.awt.*;
import java.net.URI;
import java.util.*;
import java.util.function.Consumer;
public class SelectLocationController {
protected static final ContainerEntryComparator CONTAINER_ENTRY_COMPARATOR = new ContainerEntryComparator();
protected API api;
protected SelectLocationView selectLocationView;
public SelectLocationController(API api, JFrame mainFrame) {
this.api = api;
// Create UI
selectLocationView = new SelectLocationView(api, mainFrame);
}
@SuppressWarnings("unchecked")
public void show(Point location, Collection entries, Consumer selectedLocationCallback, Runnable closeCallback) {
// Show UI
HashMap> map = new HashMap<>();
for (Container.Entry entry : entries) {
Container container = entry.getContainer();
// Search root container
while (true) {
Container parentContainer = container.getRoot().getParent().getContainer();
if (parentContainer.getRoot() == null) {
break;
} else {
container = parentContainer;
}
}
ArrayList list = map.get(container);
if (list == null) {
map.put(container, list=new ArrayList<>());
}
list.add(entry);
}
HashSet delegatingFilterContainers = new HashSet<>();
for (Map.Entry> mapEntry : map.entrySet()) {
Container container = mapEntry.getKey();
// Create a filtered container
// TODO In a future release, display matching types and inner-types, not only matching files
delegatingFilterContainers.add(new DelegatingFilterContainer(container, getOuterEntries(mapEntry.getValue())));
}
Consumer selectedEntryCallback = uri -> onLocationSelected(delegatingFilterContainers, uri, selectedLocationCallback);
selectLocationView.show(location, delegatingFilterContainers, entries.size(), selectedEntryCallback, closeCallback);
}
protected Collection getOuterEntries(Collection entries) {
HashMap innerTypeEntryToOuterTypeEntry = new HashMap<>();
HashSet outerEntriesSet = new HashSet<>();
for (Container.Entry entry : entries) {
Container.Entry outerTypeEntry = null;
TypeFactory factory = TypeFactoryService.getInstance().get(entry);
if (factory != null) {
Type type = factory.make(api, entry, null);
if ((type != null) && (type.getOuterName() != null)) {
outerTypeEntry = innerTypeEntryToOuterTypeEntry.get(entry);
if (outerTypeEntry == null) {
HashMap typeNameToEntry = new HashMap<>();
HashMap innerTypeNameToOuterTypeName = new HashMap<>();
// Populate "typeNameToEntry" and "innerTypeNameToOuterTypeName"
for (Container.Entry e : entry.getParent().getChildren()) {
factory = TypeFactoryService.getInstance().get(e);
if (factory != null) {
type = factory.make(api, e, null);
if (type != null) {
typeNameToEntry.put(type.getName(), e);
if (type.getOuterName() != null) {
innerTypeNameToOuterTypeName.put(type.getName(), type.getOuterName());
}
}
}
}
// Search outer type entries and populate "innerTypeEntryToOuterTypeEntry"
for (Map.Entry e : innerTypeNameToOuterTypeName.entrySet()) {
Container.Entry innerTypeEntry = typeNameToEntry.get(e.getKey());
if (innerTypeEntry != null) {
String outerTypeName = e.getValue();
for (;;) {
String typeName = innerTypeNameToOuterTypeName.get(outerTypeName);
if (typeName != null) {
outerTypeName = typeName;
} else {
break;
}
}
outerTypeEntry = typeNameToEntry.get(outerTypeName);
if (outerTypeEntry != null) {
innerTypeEntryToOuterTypeEntry.put(innerTypeEntry, outerTypeEntry);
}
}
}
// Get outer type entry
outerTypeEntry = innerTypeEntryToOuterTypeEntry.get(entry);
}
}
}
if (outerTypeEntry != null) {
outerEntriesSet.add(outerTypeEntry);
} else {
outerEntriesSet.add(entry);
}
}
// Return outer type entries sorted by path
ArrayList result = new ArrayList<>(outerEntriesSet);
result.sort(CONTAINER_ENTRY_COMPARATOR);
return result;
}
protected void onLocationSelected(Set delegatingFilterContainers, URI uri, Consumer selectedLocationCallback) {
// Open the single entry uri
Container.Entry entry = null;
for (DelegatingFilterContainer container : delegatingFilterContainers) {
entry = container.getEntry(uri);
if (entry != null) {
break;
}
}
if (entry != null) {
selectedLocationCallback.accept(entry);
}
}
protected static class ContainerEntryComparator implements Comparator {
@Override
public int compare(Container.Entry e1, Container.Entry e2) {
return e1.getPath().compareTo(e2.getPath());
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/model/configuration/Configuration.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.model.configuration;
import org.jd.gui.Constants;
import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Configuration {
protected Point mainWindowLocation;
protected Dimension mainWindowSize;
protected boolean mainWindowMaximize;
protected String lookAndFeel;
protected List recentFiles = new ArrayList<>();
protected File recentLoadDirectory;
protected File recentSaveDirectory;
protected Map preferences = new HashMap<>();
public Point getMainWindowLocation() {
return mainWindowLocation;
}
public Dimension getMainWindowSize() {
return mainWindowSize;
}
public boolean isMainWindowMaximize() {
return mainWindowMaximize;
}
public String getLookAndFeel() {
return lookAndFeel;
}
public List getRecentFiles() {
return recentFiles;
}
public File getRecentLoadDirectory() {
return recentLoadDirectory;
}
public File getRecentSaveDirectory() {
return recentSaveDirectory;
}
public Map getPreferences() {
return preferences;
}
public void setMainWindowLocation(Point mainWindowLocation) {
this.mainWindowLocation = mainWindowLocation;
}
public void setMainWindowSize(Dimension mainWindowSize) {
this.mainWindowSize = mainWindowSize;
}
public void setMainWindowMaximize(boolean mainWindowMaximize) {
this.mainWindowMaximize = mainWindowMaximize;
}
public void setLookAndFeel(String lookAndFeel) {
this.lookAndFeel = lookAndFeel;
}
public void setRecentFiles(List recentFiles) {
this.recentFiles = recentFiles;
}
public void setRecentLoadDirectory(File recentLoadDirectory) {
this.recentLoadDirectory = recentLoadDirectory;
}
public void setRecentSaveDirectory(File recentSaveDirectory) {
this.recentSaveDirectory = recentSaveDirectory;
}
public void setPreferences(Map preferences) {
this.preferences = preferences;
}
public void addRecentFile(File file) {
recentFiles.remove(file);
recentFiles.add(0, file);
if (recentFiles.size() > Constants.MAX_RECENT_FILES) {
recentFiles.remove(Constants.MAX_RECENT_FILES);
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/model/container/DelegatingFilterContainer.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.model.container;
import org.jd.gui.api.model.Container;
import java.io.InputStream;
import java.net.URI;
import java.util.*;
public class DelegatingFilterContainer implements Container {
protected static final URI DEFAULT_ROOT_URI = URI.create("file:.");
protected Container container;
protected DelegatedEntry root;
protected Set validEntries = new HashSet<>();
protected Map uriToDelegatedEntry = new HashMap<>();
protected Map uriToDelegatedContainer = new HashMap<>();
public DelegatingFilterContainer(Container container, Collection entries) {
this.container = container;
this.root = getDelegatedEntry(container.getRoot());
for (Entry entry : entries) {
while ((entry != null) && !validEntries.contains(entry.getUri())) {
validEntries.add(entry.getUri());
entry = entry.getParent();
}
}
}
@Override public String getType() { return container.getType(); }
@Override public Container.Entry getRoot() { return root; }
public Container.Entry getEntry(URI uri) { return uriToDelegatedEntry.get(uri); }
public Set getUris() { return validEntries; }
protected DelegatedEntry getDelegatedEntry(Container.Entry entry) {
URI uri = entry.getUri();
DelegatedEntry delegatedEntry = uriToDelegatedEntry.get(uri);
if (delegatedEntry == null) {
uriToDelegatedEntry.put(uri, delegatedEntry =new DelegatedEntry(entry));
}
return delegatedEntry;
}
protected DelegatedContainer getDelegatedContainer(Container container) {
Entry root = container.getRoot();
URI uri = (root == null) ? DEFAULT_ROOT_URI : root.getUri();
DelegatedContainer delegatedContainer = uriToDelegatedContainer.get(uri);
if (delegatedContainer == null) {
uriToDelegatedContainer.put(uri, delegatedContainer =new DelegatedContainer(container));
}
return delegatedContainer;
}
protected class DelegatedEntry implements Entry, Comparable {
protected Entry entry;
protected Collection children;
public DelegatedEntry(Entry entry) {
this.entry = entry;
}
@Override public Container getContainer() { return getDelegatedContainer(entry.getContainer()); }
@Override public Entry getParent() { return getDelegatedEntry(entry.getParent()); }
@Override public URI getUri() { return entry.getUri(); }
@Override public String getPath() { return entry.getPath(); }
@Override public boolean isDirectory() { return entry.isDirectory(); }
@Override public long length() { return entry.length(); }
@Override public InputStream getInputStream() { return entry.getInputStream(); }
@Override
public Collection getChildren() {
if (children == null) {
children = new ArrayList<>();
for (Entry child : entry.getChildren()) {
if (validEntries.contains(child.getUri())) {
children.add(getDelegatedEntry(child));
}
}
}
return children;
}
@Override
public int compareTo(DelegatedEntry other) {
if (entry.isDirectory()) {
if (!other.isDirectory()) {
return -1;
}
} else {
if (other.isDirectory()) {
return 1;
}
}
return entry.getPath().compareTo(other.getPath());
}
}
protected class DelegatedContainer implements Container {
protected Container container;
public DelegatedContainer(Container container) {
this.container = container;
}
@Override public String getType() { return container.getType(); }
@Override public Entry getRoot() { return getDelegatedEntry(container.getRoot()); }
}
}
================================================
FILE: app/src/main/java/org/jd/gui/model/history/History.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.model.history;
import java.net.URI;
import java.util.ArrayList;
public class History {
protected URI current = null;
protected ArrayList backward = new ArrayList<>();
protected ArrayList forward = new ArrayList<>();
public void add(URI uri) {
if (current == null) {
// Init history
forward.clear();
current = uri;
return;
}
if (current.equals(uri)) {
// Already stored -> Nothing to do
return;
}
if (uri.getPath().toString().equals(current.getPath().toString())) {
if ((uri.getFragment() == null) && (uri.getQuery() == null)) {
// Ignore
} else if ((current.getFragment() == null) && (current.getQuery() == null)) {
// Replace current URI
current = uri;
} else {
// Store URI
forward.clear();
backward.add(current);
current = uri;
}
return;
}
if (uri.toString().startsWith(current.toString())) {
// Replace current URI
current = uri;
return;
}
if (current.toString().startsWith(uri.toString())) {
// Parent URI -> Nothing to do
return;
}
// Store URI
forward.clear();
backward.add(current);
current = uri;
}
public URI backward() {
if (! backward.isEmpty()) {
forward.add(current);
int size = backward.size();
current = backward.remove(size-1);
}
return current;
}
public URI forward() {
if (! forward.isEmpty()) {
backward.add(current);
int size = forward.size();
current = forward.remove(size-1);
}
return current;
}
public boolean canBackward() { return !backward.isEmpty(); }
public boolean canForward() { return !forward.isEmpty(); }
}
================================================
FILE: app/src/main/java/org/jd/gui/service/actions/ContextualActionsFactoryService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.actions;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.ContextualActionsFactory;
import javax.swing.*;
import java.util.*;
public class ContextualActionsFactoryService {
protected static final ContextualActionsFactoryService CONTEXTUAL_ACTIONS_FACTORY_SERVICE = new ContextualActionsFactoryService();
public static ContextualActionsFactoryService getInstance() { return CONTEXTUAL_ACTIONS_FACTORY_SERVICE; }
protected static final ActionNameComparator COMPARATOR = new ActionNameComparator();
protected final Collection providers = ExtensionService.getInstance().load(ContextualActionsFactory.class);
public Collection get(API api, Container.Entry entry, String fragment) {
HashMap> mapActions = new HashMap<>();
for (ContextualActionsFactory provider : providers) {
Collection actions = provider.make(api, entry, fragment);
for (Action action : actions) {
String groupName = (String)action.getValue(ContextualActionsFactory.GROUP_NAME);
ArrayList list = mapActions.get(groupName);
if (list == null) {
mapActions.put(groupName, list=new ArrayList<>());
}
list.add(action);
}
}
if (!mapActions.isEmpty()) {
ArrayList result = new ArrayList<>();
// Sort by group names
ArrayList groupNames = new ArrayList<>(mapActions.keySet());
Collections.sort(groupNames);
for (String groupName : groupNames) {
if (! result.isEmpty()) {
// Add 'null' to mark a separator
result.add(null);
}
// Sort by names
ArrayList actions = mapActions.get(groupName);
Collections.sort(actions, COMPARATOR);
result.addAll(actions);
}
return result;
} else {
return Collections.emptyList();
}
}
protected static class ActionNameComparator implements Comparator {
@Override
public int compare(Action a1, Action a2) {
String n1 = (String)a1.getValue(Action.NAME);
if (n1 == null) {
n1 = "";
}
String n2 = (String)a2.getValue(Action.NAME);
if (n2 == null) {
n2 = "";
}
return n1.compareTo(n2);
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/configuration/ConfigurationPersister.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.configuration;
import org.jd.gui.model.configuration.Configuration;
public interface ConfigurationPersister {
Configuration load();
void save(Configuration configuration);
}
================================================
FILE: app/src/main/java/org/jd/gui/service/configuration/ConfigurationPersisterService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.configuration;
public class ConfigurationPersisterService {
protected static final ConfigurationPersisterService CONFIGURATION_PERSISTER_SERVICE = new ConfigurationPersisterService();
protected ConfigurationPersister provider = new ConfigurationXmlPersisterProvider();
public static ConfigurationPersisterService getInstance() { return CONFIGURATION_PERSISTER_SERVICE; }
protected ConfigurationPersisterService() {}
public ConfigurationPersister get() {
return provider;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/configuration/ConfigurationXmlPersisterProvider.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.configuration;
import org.jd.gui.Constants;
import org.jd.gui.model.configuration.Configuration;
import org.jd.gui.service.platform.PlatformService;
import org.jd.gui.util.exception.ExceptionUtil;
import javax.swing.*;
import javax.xml.stream.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.jar.Manifest;
public class ConfigurationXmlPersisterProvider implements ConfigurationPersister {
protected static final String ERROR_BACKGROUND_COLOR = "JdGuiPreferences.errorBackgroundColor";
protected static final String JD_CORE_VERSION = "JdGuiPreferences.jdCoreVersion";
protected static final File FILE = getConfigFile();
protected static File getConfigFile() {
String configFilePath = System.getProperty(Constants.CONFIG_FILENAME);
if (configFilePath != null) {
File configFile = new File(configFilePath);
if (configFile.exists()) {
return configFile;
}
}
if (PlatformService.getInstance().isLinux()) {
// See: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
String xdgConfigHome = System.getenv("XDG_CONFIG_HOME");
if (xdgConfigHome != null) {
File xdgConfigHomeFile = new File(xdgConfigHome);
if (xdgConfigHomeFile.exists()) {
return new File(xdgConfigHomeFile, Constants.CONFIG_FILENAME);
}
}
File userConfigFile = new File(System.getProperty("user.home"), ".config");
if (userConfigFile.exists()) {
return new File(userConfigFile, Constants.CONFIG_FILENAME);
}
} else if (PlatformService.getInstance().isWindows()) {
// See: http://blogs.msdn.com/b/patricka/archive/2010/03/18/where-should-i-store-my-data-and-configuration-files-if-i-target-multiple-os-versions.aspx
String roamingConfigHome = System.getenv("APPDATA");
if (roamingConfigHome != null) {
File roamingConfigHomeFile = new File(roamingConfigHome);
if (roamingConfigHomeFile.exists()) {
return new File(roamingConfigHomeFile, Constants.CONFIG_FILENAME);
}
}
}
return new File(Constants.CONFIG_FILENAME);
}
@Override
public Configuration load() {
// Default values
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = (screenSize.width>Constants.DEFAULT_WIDTH) ? Constants.DEFAULT_WIDTH : screenSize.width;
int h = (screenSize.height>Constants.DEFAULT_HEIGHT) ? Constants.DEFAULT_HEIGHT : screenSize.height;
int x = (screenSize.width-w)/2;
int y = (screenSize.height-h)/2;
Configuration config = new Configuration();
config.setMainWindowLocation(new Point(x, y));
config.setMainWindowSize(new Dimension(w, h));
config.setMainWindowMaximize(false);
String defaultLaf = System.getProperty("swing.defaultlaf");
config.setLookAndFeel((defaultLaf != null) ? defaultLaf : UIManager.getSystemLookAndFeelClassName());
File recentSaveDirectory = new File(System.getProperty("user.dir"));
config.setRecentLoadDirectory(recentSaveDirectory);
config.setRecentSaveDirectory(recentSaveDirectory);
if (FILE.exists()) {
try (FileInputStream fis = new FileInputStream(FILE)) {
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(fis);
// Load values
String name = "";
Stack names = new Stack<>();
List recentFiles = new ArrayList<>();
boolean maximize = false;
Map preferences = config.getPreferences();
while (reader.hasNext()) {
switch (reader.next()) {
case XMLStreamConstants.START_ELEMENT:
names.push(name);
name += '/' + reader.getLocalName();
switch (name) {
case "/configuration/gui/mainWindow/location":
x = Integer.parseInt(reader.getAttributeValue(null, "x"));
y = Integer.parseInt(reader.getAttributeValue(null, "y"));
break;
case "/configuration/gui/mainWindow/size":
w = Integer.parseInt(reader.getAttributeValue(null, "w"));
h = Integer.parseInt(reader.getAttributeValue(null, "h"));
break;
}
break;
case XMLStreamConstants.END_ELEMENT:
name = names.pop();
break;
case XMLStreamConstants.CHARACTERS:
switch (name) {
case "/configuration/recentFilePaths/filePath":
File file = new File(reader.getText().trim());
if (file.exists()) {
recentFiles.add(file);
}
break;
case "/configuration/recentDirectories/loadPath":
file = new File(reader.getText().trim());
if (file.exists()) {
config.setRecentLoadDirectory(file);
}
break;
case "/configuration/recentDirectories/savePath":
file = new File(reader.getText().trim());
if (file.exists()) {
config.setRecentSaveDirectory(file);
}
break;
case "/configuration/gui/lookAndFeel":
config.setLookAndFeel(reader.getText().trim());
break;
case "/configuration/gui/mainWindow/maximize":
maximize = Boolean.parseBoolean(reader.getText().trim());
break;
default:
if (name.startsWith("/configuration/preferences/")) {
String key = name.substring("/configuration/preferences/".length());
preferences.put(key, reader.getText().trim());
}
break;
}
break;
}
}
if (recentFiles.size() > Constants.MAX_RECENT_FILES) {
// Truncate
recentFiles = recentFiles.subList(0, Constants.MAX_RECENT_FILES);
}
config.setRecentFiles(recentFiles);
if ((x >= 0) && (y >= 0) && (x + w < screenSize.width) && (y + h < screenSize.height)) {
// Update preferences
config.setMainWindowLocation(new Point(x, y));
config.setMainWindowSize(new Dimension(w, h));
config.setMainWindowMaximize(maximize);
}
reader.close();
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
}
if (! config.getPreferences().containsKey(ERROR_BACKGROUND_COLOR)) {
config.getPreferences().put(ERROR_BACKGROUND_COLOR, "0xFF6666");
}
config.getPreferences().put(JD_CORE_VERSION, getJdCoreVersion());
return config;
}
protected String getJdCoreVersion() {
try {
Enumeration enumeration = ConfigurationXmlPersisterProvider.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
while (enumeration.hasMoreElements()) {
try (InputStream is = enumeration.nextElement().openStream()) {
String attribute = new Manifest(is).getMainAttributes().getValue("JD-Core-Version");
if (attribute != null) {
return attribute;
}
}
}
} catch (IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
return "SNAPSHOT";
}
@Override
public void save(Configuration configuration) {
Point l = configuration.getMainWindowLocation();
Dimension s = configuration.getMainWindowSize();
try (FileOutputStream fos = new FileOutputStream(FILE)) {
XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(fos);
// Save values
writer.writeStartDocument();
writer.writeCharacters("\n");
writer.writeStartElement("configuration");
writer.writeCharacters("\n\t");
writer.writeStartElement("gui");
writer.writeCharacters("\n\t\t");
writer.writeStartElement("mainWindow");
writer.writeCharacters("\n\t\t\t");
writer.writeStartElement("location");
writer.writeAttribute("x", String.valueOf(l.x));
writer.writeAttribute("y", String.valueOf(l.y));
writer.writeEndElement();
writer.writeCharacters("\n\t\t\t");
writer.writeStartElement("size");
writer.writeAttribute("w", String.valueOf(s.width));
writer.writeAttribute("h", String.valueOf(s.height));
writer.writeEndElement();
writer.writeCharacters("\n\t\t\t");
writer.writeStartElement("maximize");
writer.writeCharacters(String.valueOf(configuration.isMainWindowMaximize()));
writer.writeEndElement();
writer.writeCharacters("\n\t\t");
writer.writeEndElement();
writer.writeCharacters("\n\t\t");
writer.writeStartElement("lookAndFeel");
writer.writeCharacters(configuration.getLookAndFeel());
writer.writeEndElement();
writer.writeCharacters("\n\t");
writer.writeEndElement();
writer.writeCharacters("\n\t");
writer.writeStartElement("recentFilePaths");
for (File recentFile : configuration.getRecentFiles()) {
writer.writeCharacters("\n\t\t");
writer.writeStartElement("filePath");
writer.writeCharacters(recentFile.getAbsolutePath());
writer.writeEndElement();
}
writer.writeCharacters("\n\t");
writer.writeEndElement();
writer.writeCharacters("\n\t");
writer.writeStartElement("recentDirectories");
writer.writeCharacters("\n\t\t");
writer.writeStartElement("loadPath");
writer.writeCharacters(configuration.getRecentLoadDirectory().getAbsolutePath());
writer.writeEndElement();
writer.writeCharacters("\n\t\t");
writer.writeStartElement("savePath");
writer.writeCharacters(configuration.getRecentSaveDirectory().getAbsolutePath());
writer.writeEndElement();
writer.writeCharacters("\n\t");
writer.writeEndElement();
writer.writeCharacters("\n\t");
writer.writeStartElement("preferences");
for (Map.Entry preference : configuration.getPreferences().entrySet()) {
writer.writeCharacters("\n\t\t");
writer.writeStartElement(preference.getKey());
writer.writeCharacters(preference.getValue());
writer.writeEndElement();
}
writer.writeCharacters("\n\t");
writer.writeEndElement();
writer.writeCharacters("\n");
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/container/ContainerFactoryService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.container;
import org.jd.gui.api.API;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.ContainerFactory;
import java.nio.file.Path;
import java.util.Collection;
public class ContainerFactoryService {
protected static final ContainerFactoryService CONTAINER_FACTORY_SERVICE = new ContainerFactoryService();
public static ContainerFactoryService getInstance() { return CONTAINER_FACTORY_SERVICE; }
protected final Collection providers = ExtensionService.getInstance().load(ContainerFactory.class);
public ContainerFactory get(API api, Path rootPath) {
for (ContainerFactory containerFactory : providers) {
if (containerFactory.accept(api, rootPath)) {
return containerFactory;
}
}
return null;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/extension/ExtensionService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.extension;
import org.jd.gui.util.exception.ExceptionUtil;
import java.io.File;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
public class ExtensionService {
protected static final ExtensionService EXTENSION_SERVICE = new ExtensionService();
protected static final UrlComparator URL_COMPARATOR = new UrlComparator();
protected ClassLoader extensionClassLoader;
public static ExtensionService getInstance() {
return EXTENSION_SERVICE;
}
protected ExtensionService() {
try {
URI jarUri = ExtensionService.class.getProtectionDomain().getCodeSource().getLocation().toURI();
File baseDirectory = new File(jarUri).getParentFile();
File extDirectory = new File(baseDirectory, "ext");
if (extDirectory.exists() && extDirectory.isDirectory()) {
ArrayList urls = new ArrayList<>();
searchJarAndMetaInf(urls, extDirectory);
if (!urls.isEmpty()) {
URL[] array = urls.toArray(new URL[urls.size()]);
Arrays.sort(array, URL_COMPARATOR);
extensionClassLoader = new URLClassLoader(array, ExtensionService.class.getClassLoader());
}
}
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
extensionClassLoader = ExtensionService.class.getClassLoader();
}
protected void searchJarAndMetaInf(List urls, File directory) throws Exception {
File metaInf = new File(directory, "META-INF");
if (metaInf.exists() && metaInf.isDirectory()) {
urls.add(directory.toURI().toURL());
} else {
for (File child : directory.listFiles()) {
if (child.isDirectory()) {
searchJarAndMetaInf(urls, child);
} else if (child.getName().toLowerCase().endsWith(".jar")) {
urls.add(new URL("jar", "", child.toURI().toURL().toString() + "!/"));
}
}
}
}
public Collection load(Class service) {
ArrayList list = new ArrayList<>();
Iterator iterator = ServiceLoader.load(service, extensionClassLoader).iterator();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
protected static class UrlComparator implements Comparator {
@Override
public int compare(URL url1, URL url2) {
return url1.getPath().compareTo(url2.getPath());
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/fileloader/FileLoaderService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.fileloader;
import org.jd.gui.api.API;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.FileLoader;
import java.io.File;
import java.util.Collection;
import java.util.HashMap;
public class FileLoaderService {
protected static final FileLoaderService FILE_LOADER_SERVICE = new FileLoaderService();
public static FileLoaderService getInstance() { return FILE_LOADER_SERVICE; }
protected final Collection providers = ExtensionService.getInstance().load(FileLoader.class);
protected HashMap mapProviders = new HashMap<>();
protected FileLoaderService() {
for (FileLoader provider : providers) {
for (String extension : provider.getExtensions()) {
mapProviders.put(extension, provider);
}
}
}
public FileLoader get(API api, File file) {
String name = file.getName();
int lastDot = name.lastIndexOf('.');
String extension = name.substring(lastDot+1);
FileLoader provider = mapProviders.get(extension);
return provider;
}
public HashMap getMapProviders() {
return mapProviders;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/indexer/IndexerService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.indexer;
import org.jd.gui.api.model.Container;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.Indexer;
import java.util.Collection;
import java.util.HashMap;
public class IndexerService {
protected static final IndexerService INDEXER_SERVICE = new IndexerService();
public static IndexerService getInstance() { return INDEXER_SERVICE; }
protected HashMap mapProviders = new HashMap<>();
protected IndexerService() {
Collection providers = ExtensionService.getInstance().load(Indexer.class);
for (Indexer provider : providers) {
for (String selector : provider.getSelectors()) {
Indexers indexers = mapProviders.get(selector);
if (indexers == null) {
mapProviders.put(selector, indexers=new Indexers());
}
indexers.add(provider);
}
}
}
public Indexer get(Container.Entry entry) {
Indexer indexer = get(entry.getContainer().getType(), entry);
return (indexer != null) ? indexer : get("*", entry);
}
protected Indexer get(String containerType, Container.Entry entry) {
String path = entry.getPath();
String type = entry.isDirectory() ? "dir" : "file";
String prefix = containerType + ':' + type;
Indexer indexer = null;
Indexers indexers = mapProviders.get(prefix + ':' + path);
if (indexers != null) {
indexer = indexers.match(path);
}
if (indexer == null) {
int lastSlashIndex = path.lastIndexOf('/');
String name = path.substring(lastSlashIndex+1);
indexers = mapProviders.get(prefix + ":*/" + name);
if (indexers != null) {
indexer = indexers.match(path);
}
if (indexer == null) {
int index = name.lastIndexOf('.');
if (index != -1) {
String extension = name.substring(index + 1);
indexers = mapProviders.get(prefix + ":*." + extension);
if (indexers != null) {
indexer = indexers.match(path);
}
}
if (indexer == null) {
indexers = mapProviders.get(prefix + ":*");
if (indexers != null) {
indexer = indexers.match(path);
}
}
}
}
return indexer;
}
protected static class Indexers {
protected HashMap indexers = new HashMap<>();
protected Indexer defaultIndexer;
public void add(Indexer indexer) {
if (indexer.getPathPattern() != null) {
indexers.put(indexer.getPathPattern().pattern(), indexer);
} else {
defaultIndexer = indexer;
}
}
public Indexer match(String path) {
for (Indexer indexer : indexers.values()) {
if (indexer.getPathPattern().matcher(path).matches()) {
return indexer;
}
}
return defaultIndexer;
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/mainpanel/ContainerPanelFactoryProvider.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.mainpanel;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.ContentIndexable;
import org.jd.gui.api.feature.SourcesSavable;
import org.jd.gui.api.feature.UriGettable;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.spi.Indexer;
import org.jd.gui.spi.PanelFactory;
import org.jd.gui.spi.SourceSaver;
import org.jd.gui.spi.TreeNodeFactory;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.view.component.panel.TreeTabbedPanel;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
public class ContainerPanelFactoryProvider implements PanelFactory {
protected static final String[] TYPES = { "default" };
@Override public String[] getTypes() { return TYPES; }
@Override
@SuppressWarnings("unchecked")
public T make(API api, Container container) {
return (T)new ContainerPanel(api, container);
}
protected class ContainerPanel extends TreeTabbedPanel implements ContentIndexable, SourcesSavable {
protected Container.Entry entry;
public ContainerPanel(API api, Container container) {
super(api, container.getRoot().getParent().getUri());
this.entry = container.getRoot().getParent();
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
for (Container.Entry entry : container.getRoot().getChildren()) {
TreeNodeFactory factory = api.getTreeNodeFactory(entry);
if (factory != null) {
root.add(factory.make(api, entry));
}
}
tree.setModel(new DefaultTreeModel(root));
}
// --- ContentIndexable --- //
@Override
public Indexes index(API api) {
HashMap> map = new HashMap<>();
DelegatedMapMapWithDefault mapWithDefault = new DelegatedMapMapWithDefault(map);
// Index populating value automatically
Indexes indexesWithDefault = name -> mapWithDefault.get(name);
// Index entry
Indexer indexer = api.getIndexer(entry);
if (indexer != null) {
indexer.index(api, entry, indexesWithDefault);
}
// To prevent memory leaks, return an index without the 'populate' behaviour
return name -> map.get(name);
}
// --- SourcesSavable --- //
@Override
public String getSourceFileName() {
SourceSaver saver = api.getSourceSaver(entry);
if (saver != null) {
String path = saver.getSourcePath(entry);
int index = path.lastIndexOf('/');
return path.substring(index+1);
} else {
return null;
}
}
@Override
public int getFileCount() {
SourceSaver saver = api.getSourceSaver(entry);
return (saver != null) ? saver.getFileCount(api, entry) : 0;
}
@Override
public void save(API api, Controller controller, Listener listener, Path path) {
try {
Path parentPath = path.getParent();
if ((parentPath != null) && !Files.exists(parentPath)) {
Files.createDirectories(parentPath);
}
URI uri = path.toUri();
URI archiveUri = new URI("jar:" + uri.getScheme(), uri.getHost(), uri.getPath() + "!/", null);
try (FileSystem archiveFs = FileSystems.newFileSystem(archiveUri, Collections.singletonMap("create", "true"))) {
Path archiveRootPath = archiveFs.getPath("/");
SourceSaver saver = api.getSourceSaver(entry);
if (saver != null) {
saver.saveContent(
api,
() -> controller.isCancelled(),
(p) -> listener. pathSaved(p),
archiveRootPath, archiveRootPath, entry);
}
}
} catch (URISyntaxException|IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
}
}
protected static class DelegatedMap implements Map {
protected Map map;
public DelegatedMap(Map map) { this.map = map; }
@Override public int size() { return map.size(); }
@Override public boolean isEmpty() { return map.isEmpty(); }
@Override public boolean containsKey(Object o) { return map.containsKey(o); }
@Override public boolean containsValue(Object o) { return map.containsValue(o); }
@Override public V get(Object o) { return map.get(o); }
@Override public V put(K k, V v) { return map.put(k, v); }
@Override public V remove(Object o) { return map.remove(o); }
@Override public void putAll(Map extends K, ? extends V> map) { this.map.putAll(map); }
@Override public void clear() { map.clear(); }
@Override public Set keySet() { return map.keySet(); }
@Override public Collection values() { return map.values(); }
@Override public Set> entrySet() { return map.entrySet(); }
@Override public boolean equals(Object o) { return map.equals(o); }
@Override public int hashCode() { return map.hashCode(); }
}
protected static class DelegatedMapWithDefault extends DelegatedMap {
public DelegatedMapWithDefault(Map map) { super(map); }
@Override public Collection get(Object o) {
Collection value = map.get(o);
if (value == null) {
String key = o.toString();
map.put(key, value=new ArrayList());
}
return value;
}
}
protected static class DelegatedMapMapWithDefault extends DelegatedMap> {
protected HashMap> wrappers = new HashMap<>();
public DelegatedMapMapWithDefault(Map> map) { super(map); }
@Override public Map get(Object o) {
Map value = wrappers.get(o);
if (value == null) {
String key = o.toString();
HashMap m = new HashMap<>();
map.put(key, m);
wrappers.put(key, value=new DelegatedMapWithDefault(m));
}
return value;
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/mainpanel/PanelFactoryService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.mainpanel;
import org.jd.gui.api.model.Container;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.PanelFactory;
import java.util.Collection;
import java.util.HashMap;
public class PanelFactoryService {
protected static final PanelFactoryService PANEL_FACTORY_SERVICE = new PanelFactoryService();
public static PanelFactoryService getInstance() { return PANEL_FACTORY_SERVICE; }
protected HashMap mapProviders = new HashMap<>();
protected PanelFactoryService() {
Collection providers = ExtensionService.getInstance().load(PanelFactory.class);
for (PanelFactory provider : providers) {
for (String type : provider.getTypes()) {
mapProviders.put(type, provider);
}
}
}
public PanelFactory get(Container container) {
PanelFactory factory = mapProviders.get(container.getType());
return (factory != null) ? factory : mapProviders.get("default");
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/pastehandler/PasteHandlerService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.pastehandler;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.PasteHandler;
import java.util.Collection;
public class PasteHandlerService {
protected static final PasteHandlerService PASTE_HANDLER_SERVICE = new PasteHandlerService();
public static PasteHandlerService getInstance() { return PASTE_HANDLER_SERVICE; }
protected final Collection providers = ExtensionService.getInstance().load(PasteHandler.class);
public PasteHandler get(Object obj) {
for (PasteHandler provider : providers) {
if (provider.accept(obj)) {
return provider;
}
}
return null;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/platform/PlatformService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.platform;
public class PlatformService {
protected static final PlatformService PLATFORM_SERVICE = new PlatformService();
public enum OS { Linux, MacOSX, Windows }
protected OS os;
protected PlatformService() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("windows")) {
os = OS.Windows;
} else if (osName.contains("mac os")) {
os = OS.MacOSX;
} else {
os = OS.Linux;
}
}
public static PlatformService getInstance() { return PLATFORM_SERVICE; }
public OS getOs() { return os; }
public boolean isLinux() { return os == OS.Linux; }
public boolean isMac() { return os == OS.MacOSX; }
public boolean isWindows() { return os == OS.Windows; }
}
================================================
FILE: app/src/main/java/org/jd/gui/service/preferencespanel/PreferencesPanelService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.preferencespanel;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.PreferencesPanel;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
public class PreferencesPanelService {
protected static final PreferencesPanelService PREFERENCES_PANEL_SERVICE = new PreferencesPanelService();
public static PreferencesPanelService getInstance() { return PREFERENCES_PANEL_SERVICE; }
protected final Collection providers;
protected PreferencesPanelService() {
Collection list = ExtensionService.getInstance().load(PreferencesPanel.class);
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
if (!iterator.next().isActivated()) {
iterator.remove();
}
}
HashMap map = new HashMap<>();
for (PreferencesPanel panel : list) {
map.put(panel.getPreferencesGroupTitle() + '$' + panel.getPreferencesPanelTitle(), panel);
}
providers = map.values();
}
public Collection getProviders() {
return providers;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/preferencespanel/UISingleInstancePreferencesProvider.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.preferencespanel;
import org.jd.gui.service.platform.PlatformService;
import org.jd.gui.spi.PreferencesPanel;
import javax.swing.*;
import java.awt.*;
import java.util.Map;
/**
* Single instance is the default mode on Mac OSX, so this panel is not activated.
*/
public class UISingleInstancePreferencesProvider extends JPanel implements PreferencesPanel {
protected static final String SINGLE_INSTANCE = "UIMainWindowPreferencesProvider.singleInstance";
protected JCheckBox singleInstanceTabsCheckBox;
public UISingleInstancePreferencesProvider() {
super(new GridLayout(0,1));
singleInstanceTabsCheckBox = new JCheckBox("Single instance");
add(singleInstanceTabsCheckBox);
}
// --- PreferencesPanel --- //
@Override public String getPreferencesGroupTitle() { return "User Interface"; }
@Override public String getPreferencesPanelTitle() { return "Main window"; }
@Override public JComponent getPanel() { return this; }
@Override public void init(Color errorBackgroundColor) {}
@Override public boolean isActivated() { return !PlatformService.getInstance().isMac(); }
@Override
public void loadPreferences(Map preferences) {
singleInstanceTabsCheckBox.setSelected("true".equals(preferences.get(SINGLE_INSTANCE)));
}
@Override
public void savePreferences(Map preferences) {
preferences.put(SINGLE_INSTANCE, Boolean.toString(singleInstanceTabsCheckBox.isSelected()));
}
@Override public boolean arePreferencesValid() { return true; }
@Override public void addPreferencesChangeListener(PreferencesPanel.PreferencesPanelChangeListener listener) {}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/preferencespanel/UITabsPreferencesProvider.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.preferencespanel;
import org.jd.gui.service.platform.PlatformService;
import org.jd.gui.spi.PreferencesPanel;
import javax.swing.*;
import java.awt.*;
import java.util.Map;
/**
* JTabbedPane.WRAP_TAB_LAYOUT is not supported by Aqua L&F.
* This panel is not activated on Mac OSX.
*/
public class UITabsPreferencesProvider extends JPanel implements PreferencesPanel {
protected static final String TAB_LAYOUT = "UITabsPreferencesProvider.singleLineTabs";
protected JCheckBox singleLineTabsCheckBox;
public UITabsPreferencesProvider() {
super(new GridLayout(0,1));
singleLineTabsCheckBox = new JCheckBox("Tabs on a single line");
add(singleLineTabsCheckBox);
}
// --- PreferencesPanel --- //
@Override public String getPreferencesGroupTitle() { return "User Interface"; }
@Override public String getPreferencesPanelTitle() { return "Tabs"; }
@Override public JComponent getPanel() { return this; }
@Override public void init(Color errorBackgroundColor) {}
@Override public boolean isActivated() { return !PlatformService.getInstance().isMac(); }
@Override public void loadPreferences(Map preferences) {
singleLineTabsCheckBox.setSelected("true".equals(preferences.get(TAB_LAYOUT)));
}
@Override public void savePreferences(Map preferences) {
preferences.put(TAB_LAYOUT, Boolean.toString(singleLineTabsCheckBox.isSelected()));
}
@Override public boolean arePreferencesValid() { return true; }
@Override public void addPreferencesChangeListener(PreferencesPanel.PreferencesPanelChangeListener listener) {}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/sourceloader/SourceLoaderService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.sourceloader;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.SourceLoader;
import java.io.File;
import java.util.Collection;
public class SourceLoaderService {
protected static final SourceLoaderService SOURCE_LOADER_SERVICE = new SourceLoaderService();
public static SourceLoaderService getInstance() { return SOURCE_LOADER_SERVICE; }
protected Collection providers = ExtensionService.getInstance().load(SourceLoader.class);
public String getSource(API api, Container.Entry entry) {
for (SourceLoader provider : providers) {
String source = provider.getSource(api, entry);
if ((source != null) && !source.isEmpty()) {
return source;
}
}
return null;
}
public String loadSource(API api, Container.Entry entry) {
for (SourceLoader provider : providers) {
String source = provider.loadSource(api, entry);
if ((source != null) && !source.isEmpty()) {
return source;
}
}
return null;
}
public File getSourceFile(API api, Container.Entry entry) {
for (SourceLoader provider : providers) {
File file = provider.loadSourceFile(api, entry);
if (file != null) {
return file;
}
}
return null;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/sourcesaver/SourceSaverService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.sourcesaver;
import org.jd.gui.api.model.Container;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.SourceSaver;
import java.util.Collection;
import java.util.HashMap;
public class SourceSaverService {
protected static final SourceSaverService SOURCE_SAVER_SERVICE = new SourceSaverService();
public static SourceSaverService getInstance() { return SOURCE_SAVER_SERVICE; }
protected HashMap mapProviders = new HashMap<>();
protected SourceSaverService() {
Collection providers = ExtensionService.getInstance().load(SourceSaver.class);
for (SourceSaver provider : providers) {
for (String selector : provider.getSelectors()) {
SourceSavers savers = mapProviders.get(selector);
if (savers == null) {
mapProviders.put(selector, savers=new SourceSavers());
}
savers.add(provider);
}
}
}
public SourceSaver get(Container.Entry entry) {
SourceSaver saver = get(entry.getContainer().getType(), entry);
return (saver != null) ? saver : get("*", entry);
}
protected SourceSaver get(String containerType, Container.Entry entry) {
String path = entry.getPath();
String type = entry.isDirectory() ? "dir" : "file";
String prefix = containerType + ':' + type;
SourceSaver saver = null;
SourceSavers savers = mapProviders.get(prefix + ':' + path);
if (savers != null) {
saver = savers.match(path);
}
if (saver == null) {
int lastSlashIndex = path.lastIndexOf('/');
String name = path.substring(lastSlashIndex+1);
savers = mapProviders.get(prefix + ":*/" + path);
if (savers != null) {
saver = savers.match(path);
}
if (saver == null) {
int index = name.lastIndexOf('.');
if (index != -1) {
String extension = name.substring(index + 1);
savers = mapProviders.get(prefix + ":*." + extension);
if (savers != null) {
saver = savers.match(path);
}
}
if (saver == null) {
savers = mapProviders.get(prefix + ":*");
if (savers != null) {
saver = savers.match(path);
}
}
}
}
return saver;
}
protected static class SourceSavers {
protected HashMap savers = new HashMap<>();
protected SourceSaver defaultSaver;
void add(SourceSaver saver) {
if (saver.getPathPattern() != null) {
savers.put(saver.getPathPattern().pattern(), saver);
} else {
defaultSaver = saver;
}
}
SourceSaver match(String path) {
for (SourceSaver saver : savers.values()) {
if (saver.getPathPattern().matcher(path).matches()) {
return saver;
}
}
return defaultSaver;
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/treenode/TreeNodeFactoryService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.treenode;
import org.jd.gui.api.model.Container;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.TreeNodeFactory;
import java.util.Collection;
import java.util.HashMap;
public class TreeNodeFactoryService {
protected static final TreeNodeFactoryService TREE_NODE_FACTORY_SERVICE = new TreeNodeFactoryService();
public static TreeNodeFactoryService getInstance() { return TREE_NODE_FACTORY_SERVICE; }
protected HashMap mapProviders = new HashMap<>();
protected TreeNodeFactoryService() {
Collection providers = ExtensionService.getInstance().load(TreeNodeFactory.class);
for (TreeNodeFactory provider : providers) {
for (String selector : provider.getSelectors()) {
TreeNodeFactories factories = mapProviders.get(selector);
if (factories == null) {
mapProviders.put(selector, factories=new TreeNodeFactories());
}
factories.add(provider);
}
}
}
public TreeNodeFactory get(Container.Entry entry) {
TreeNodeFactory factory = get(entry.getContainer().getType(), entry);
return (factory != null) ? factory : get("*", entry);
}
protected TreeNodeFactory get(String containerType, Container.Entry entry) {
String path = entry.getPath();
String type = entry.isDirectory() ? "dir" : "file";
String prefix = containerType + ':' + type + ':';
TreeNodeFactory factory = null;
TreeNodeFactories factories = mapProviders.get(prefix + path);
if (factories != null) {
factory = factories.match(path);
}
if (factory == null) {
int lastSlashIndex = path.lastIndexOf('/');
String name = path.substring(lastSlashIndex+1);
factories = mapProviders.get(prefix + "*/" + name);
if (factories != null) {
factory = factories.match(path);
}
if (factory == null) {
int index = name.lastIndexOf('.');
if (index != -1) {
String extension = name.substring(index + 1);
factories = mapProviders.get(prefix + "*." + extension);
if (factories != null) {
factory = factories.match(path);
}
}
if (factory == null) {
factories = mapProviders.get(prefix + "*");
if (factories != null) {
factory = factories.match(path);
}
}
}
}
return factory;
}
protected static class TreeNodeFactories {
protected HashMap factories = new HashMap<>();
protected TreeNodeFactory defaultFactory;
public void add(TreeNodeFactory factory) {
if (factory.getPathPattern() != null) {
factories.put(factory.getPathPattern().pattern(), factory);
} else {
defaultFactory = factory;
}
}
public TreeNodeFactory match(String path) {
for (TreeNodeFactory factory : factories.values()) {
if (factory.getPathPattern().matcher(path).matches()) {
return factory;
}
}
return defaultFactory;
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/type/TypeFactoryService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.type;
import org.jd.gui.api.model.Container;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.TypeFactory;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TypeFactoryService {
protected static final TypeFactoryService TYPE_FACTORY_SERVICE = new TypeFactoryService();
protected Map mapProviders;
public static TypeFactoryService getInstance() {
return TYPE_FACTORY_SERVICE;
}
protected TypeFactoryService() {
Collection providers = ExtensionService.getInstance().load(TypeFactory.class);
mapProviders = new HashMap<>();
for (TypeFactory provider : providers) {
for (String selector : provider.getSelectors()) {
TypeFactories typeFactories = mapProviders.get(selector);
if (typeFactories == null) {
mapProviders.put(selector, typeFactories=new TypeFactories());
}
typeFactories.add(provider);
}
}
}
public TypeFactory get(Container.Entry entry) {
TypeFactory typeFactory = get(entry.getContainer().getType(), entry);
return (typeFactory != null) ? typeFactory : get("*", entry);
}
public TypeFactory get(String containerType, Container.Entry entry) {
String path = entry.getPath();
String type = entry.isDirectory() ? "dir" : "file";
String prefix = containerType + ':' + type + ':';
TypeFactories typeFactories = mapProviders.get(prefix + path);
TypeFactory factory = null;
if (typeFactories != null) {
factory = typeFactories.match(path);
}
if (factory == null) {
int lastSlashIndex = path.lastIndexOf('/');
String name = path.substring(lastSlashIndex+1);
typeFactories = mapProviders.get(prefix + "*/" + name);
if (typeFactories != null) {
factory = typeFactories.match(path);
}
if (factory == null) {
int index = name.lastIndexOf('.');
if (index != -1) {
String extension = name.substring(index + 1);
typeFactories = mapProviders.get(prefix + "*." + extension);
if (typeFactories != null) {
factory = typeFactories.match(path);
}
}
if (factory == null) {
typeFactories = mapProviders.get(prefix + '*');
if (typeFactories != null) {
factory = typeFactories.match(path);
}
}
}
}
return factory;
}
protected static class TypeFactories {
protected HashMap factories = new HashMap<>();
protected TypeFactory defaultFactory;
public void add(TypeFactory factory) {
Pattern pathPattern = factory.getPathPattern();
if (pathPattern != null) {
factories.put(pathPattern.pattern(), factory);
} else {
defaultFactory = factory;
}
}
public TypeFactory match(String path) {
for (TypeFactory factory : factories.values()) {
Matcher matcher = factory.getPathPattern().matcher(path);
if (matcher.matches()) {
return factory;
}
}
return defaultFactory;
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/service/uriloader/UriLoaderService.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.service.uriloader;
import org.jd.gui.api.API;
import org.jd.gui.service.extension.ExtensionService;
import org.jd.gui.spi.UriLoader;
import java.net.URI;
import java.util.Collection;
import java.util.HashMap;
public class UriLoaderService {
protected static final UriLoaderService URI_LOADER_SERVICE = new UriLoaderService();
public static UriLoaderService getInstance() { return URI_LOADER_SERVICE; }
protected HashMap mapProviders = new HashMap<>();
protected UriLoaderService() {
Collection providers = ExtensionService.getInstance().load(UriLoader.class);
for (UriLoader provider : providers) {
for (String scheme : provider.getSchemes()) {
mapProviders.put(scheme, provider);
}
}
}
public UriLoader get(API api, URI uri) {
UriLoader provider = mapProviders.get(uri.getScheme());
if (provider.accept(api, uri)) {
return provider;
} else {
return null;
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/util/exception/ExceptionUtil.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.util.exception;
public class ExceptionUtil {
public static boolean printStackTrace(Throwable throwable) {
throwable.printStackTrace();
return true;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/util/function/TriConsumer.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.util.function;
import java.util.Objects;
@FunctionalInterface
public interface TriConsumer {
void accept(T t, U u, V v);
default TriConsumer andThen(TriConsumer super T, ? super U, ? super V> after) {
Objects.requireNonNull(after);
return (a, b, c) -> {
accept(a, b, c);
after.accept(a, b, c);
};
}
}
================================================
FILE: app/src/main/java/org/jd/gui/util/net/InterProcessCommunicationUtil.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.util.net;
import org.jd.gui.util.exception.ExceptionUtil;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.function.Consumer;
public class InterProcessCommunicationUtil {
protected static final int PORT = 2015_6;
public static void listen(final Consumer consumer) throws Exception {
final ServerSocket listener = new ServerSocket(PORT);
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
try (Socket socket = listener.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
// Receive args from another JD-GUI instance
String[] args = (String[])ois.readObject();
consumer.accept(args);
} catch (IOException|ClassNotFoundException e) {
assert ExceptionUtil.printStackTrace(e);
}
}
}
};
new Thread(runnable).start();
}
public static void send(String[] args) {
try (Socket socket = new Socket(InetAddress.getLocalHost(), PORT);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())) {
// Send args to the main JD-GUI instance
oos.writeObject(args);
} catch (IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
}
}
================================================
FILE: app/src/main/java/org/jd/gui/util/net/UriUtil.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.util.net;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.api.model.Type;
import org.jd.gui.service.type.TypeFactoryService;
import org.jd.gui.spi.TypeFactory;
import org.jd.gui.util.exception.ExceptionUtil;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.concurrent.Future;
public class UriUtil {
/*
* Convert inner entry URI to outer entry uri with a fragment. Example:
* file://codebase/a/b/c/D$E.class => file://codebase/a/b/c/D.class#typeDeclaration=D$E
*/
public static URI createURI(API api, Collection> collectionOfFutureIndexes, Container.Entry entry, String query, String fragment) {
URI uri = entry.getUri();
try {
String path = uri.getPath();
TypeFactory typeFactory = TypeFactoryService.getInstance().get(entry);
if (typeFactory != null) {
Type type = typeFactory.make(api, entry, fragment);
if (type != null) {
path = getOuterPath(collectionOfFutureIndexes, entry, type);
}
}
return new URI(uri.getScheme(), uri.getHost(), path, query, fragment);
} catch (URISyntaxException e) {
assert ExceptionUtil.printStackTrace(e);
return uri;
}
}
@SuppressWarnings("unchecked")
protected static String getOuterPath(Collection> collectionOfFutureIndexes, Container.Entry entry, Type type) {
String outerName = type.getOuterName();
if (outerName != null) {
try {
for (Future futureIndexes : collectionOfFutureIndexes) {
if (futureIndexes.isDone()) {
Collection outerEntries = futureIndexes.get().getIndex("typeDeclarations").get(outerName);
if (outerEntries != null) {
for (Container.Entry outerEntry : outerEntries) {
if (outerEntry.getContainer() == entry.getContainer()) {
return outerEntry.getUri().getPath();
}
}
}
}
}
} catch (Exception e) {
assert ExceptionUtil.printStackTrace(e);
}
}
return entry.getUri().getPath();
}
}
================================================
FILE: app/src/main/java/org/jd/gui/util/swing/SwingUtil.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.util.swing;
import org.jd.gui.util.exception.ExceptionUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* See: https://www.ailis.de/~k/archives/67-Workaround-for-borderless-Java-Swing-menus-on-Linux.html
*/
public class SwingUtil {
/*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to
*/
/**
* Swing menus are looking pretty bad on Linux when the GTK LaF is used (See
* bug #6925412). It will most likely never be fixed anytime soon so this
* method provides a workaround for it. It uses reflection to change the GTK
* style objects of Swing so popup menu borders have a minimum thickness of
* 1 and menu separators have a minimum vertical thickness of 1.
*/
public static void installGtkPopupBugWorkaround() {
// Get current look-and-feel implementation class
LookAndFeel laf = UIManager.getLookAndFeel();
Class> lafClass = laf.getClass();
// Do nothing when not using the problematic LaF
if (!lafClass.getName().equals("com.sun.java.swing.plaf.gtk.GTKLookAndFeel")) return;
// We do reflection from here on. Failure is silently ignored. The
// workaround is simply not installed when something goes wrong here
try {
// Access the GTK style factory
Field field = lafClass.getDeclaredField("styleFactory");
boolean accessible = field.isAccessible();
field.setAccessible(true);
Object styleFactory = field.get(laf);
field.setAccessible(accessible);
// Fix the horizontal and vertical thickness of popup menu style
Object style = getGtkStyle(styleFactory, new JPopupMenu(), "POPUP_MENU");
fixGtkThickness(style, "yThickness");
fixGtkThickness(style, "xThickness");
// Fix the vertical thickness of the popup menu separator style
style = getGtkStyle(styleFactory, new JSeparator(), "POPUP_MENU_SEPARATOR");
fixGtkThickness(style, "yThickness");
} catch (Exception e) {
// Silently ignored. Workaround can't be applied.
assert ExceptionUtil.printStackTrace(e);
}
}
/**
* Called internally by installGtkPopupBugWorkaround to fix the thickness
* of a GTK style field by setting it to a minimum value of 1.
*
* @param style
* The GTK style object.
* @param fieldName
* The field name.
* @throws Exception
* When reflection fails.
*/
private static void fixGtkThickness(Object style, String fieldName) throws Exception {
Field field = style.getClass().getDeclaredField(fieldName);
boolean accessible = field.isAccessible();
field.setAccessible(true);
field.setInt(style, Math.max(1, field.getInt(style)));
field.setAccessible(accessible);
}
/**
* Called internally by installGtkPopupBugWorkaround. Returns a specific
* GTK style object.
*
* @param styleFactory
* The GTK style factory.
* @param component
* The target component of the style.
* @param regionName
* The name of the target region of the style.
* @return The GTK style.
* @throws Exception
* When reflection fails.
*/
private static Object getGtkStyle(Object styleFactory, JComponent component, String regionName) throws Exception {
// Create the region object
Class> regionClass = Class.forName("javax.swing.plaf.synth.Region");
Field field = regionClass.getField(regionName);
Object region = field.get(regionClass);
// Get and return the style
Class> styleFactoryClass = styleFactory.getClass();
Method method = styleFactoryClass.getMethod("getStyle", JComponent.class, regionClass);
boolean accessible = method.isAccessible();
method.setAccessible(true);
Object style = method.invoke(styleFactory, component, region);
method.setAccessible(accessible);
return style;
}
public static void invokeLater(Runnable runnable) {
if (SwingUtilities.isEventDispatchThread()) {
runnable.run();
} else {
SwingUtilities.invokeLater(runnable);
}
}
public static Image getImage(String iconPath) {
return Toolkit.getDefaultToolkit().getImage(SwingUtil.class.getResource(iconPath));
}
public static ImageIcon newImageIcon(String iconPath) {
return new ImageIcon(getImage(iconPath));
}
public static Action newAction(String name, boolean enable, ActionListener listener) {
Action action = new AbstractAction(name) {
@Override
public void actionPerformed(ActionEvent actionEvent) {
listener.actionPerformed(actionEvent);
}
};
action.setEnabled(enable);
return action;
}
public static Action newAction(String name, ImageIcon icon, boolean enable, ActionListener listener) {
Action action = newAction(name, enable, listener);
action.putValue(Action.SMALL_ICON, icon);
return action;
}
public static Action newAction(ImageIcon icon, boolean enable, ActionListener listener) {
Action action = newAction(null, icon, enable, listener);
action.putValue(Action.SMALL_ICON, icon);
return action;
}
public static Action newAction(String name, ImageIcon icon, boolean enable, String shortDescription, ActionListener listener) {
Action action = newAction(name, icon, enable, listener);
action.putValue(Action.SHORT_DESCRIPTION, shortDescription);
return action;
}
public static Action newAction(String name, boolean enable, String shortDescription, ActionListener listener) {
Action action = newAction(name, enable, listener);
action.putValue(Action.SHORT_DESCRIPTION, shortDescription);
return action;
}
}
================================================
FILE: app/src/main/java/org/jd/gui/view/AboutView.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.view;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.swing.SwingUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
public class AboutView {
protected JDialog aboutDialog;
protected JButton aboutOkButton;
public AboutView(JFrame mainFrame) {
// Build GUI
SwingUtil.invokeLater(() -> {
aboutDialog = new JDialog(mainFrame, "About Java Decompiler", false);
aboutDialog.setResizable(false);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
panel.setLayout(new BorderLayout());
aboutDialog.add(panel);
Box vbox = Box.createVerticalBox();
panel.add(vbox, BorderLayout.NORTH);
JPanel subpanel = new JPanel();
vbox.add(subpanel);
subpanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
subpanel.setBackground(Color.WHITE);
subpanel.setLayout(new BorderLayout());
JLabel logo = new JLabel(new ImageIcon(SwingUtil.getImage("/org/jd/gui/images/jd_icon_64.png")));
logo.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
subpanel.add(logo, BorderLayout.WEST);
Box subvbox = Box.createVerticalBox();
subvbox.setBorder(BorderFactory.createEmptyBorder(15,0,15,15));
subpanel.add(subvbox, BorderLayout.EAST);
Box hbox = Box.createHorizontalBox();
subvbox.add(hbox);
JLabel mainLabel = new JLabel("Java Decompiler");
mainLabel.setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 14));
hbox.add(mainLabel);
hbox.add(Box.createHorizontalGlue());
hbox = Box.createHorizontalBox();
subvbox.add(hbox);
JPanel subsubpanel = new JPanel();
hbox.add(subsubpanel);
subsubpanel.setLayout(new GridLayout(2,2));
subsubpanel.setOpaque(false);
subsubpanel.setBorder(BorderFactory.createEmptyBorder(5,10,5,5));
String jdGuiVersion = "SNAPSHOT";
String jdCoreVersion = "SNAPSHOT";
try {
Enumeration enumeration = AboutView.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
while (enumeration.hasMoreElements()) {
try (InputStream is = enumeration.nextElement().openStream()) {
Attributes attributes = new Manifest(is).getMainAttributes();
String attribute = attributes.getValue("JD-GUI-Version");
if (attribute != null) {
jdGuiVersion = attribute;
}
attribute = attributes.getValue("JD-Core-Version");
if (attribute != null) {
jdCoreVersion = attribute;
}
}
}
} catch (IOException e) {
assert ExceptionUtil.printStackTrace(e);
}
subsubpanel.add(new JLabel("JD-GUI"));
subsubpanel.add(new JLabel("version " + jdGuiVersion));
subsubpanel.add(new JLabel("JD-Core"));
subsubpanel.add(new JLabel("version " + jdCoreVersion));
hbox.add(Box.createHorizontalGlue());
hbox = Box.createHorizontalBox();
hbox.add(new JLabel("Copyright © 2008, 2019 Emmanuel Dupuy"));
hbox.add(Box.createHorizontalGlue());
subvbox.add(hbox);
vbox.add(Box.createVerticalStrut(10));
hbox = Box.createHorizontalBox();
panel.add(hbox, BorderLayout.SOUTH);
hbox.add(Box.createHorizontalGlue());
aboutOkButton = new JButton(" Ok ");
Action aboutOkActionListener = new AbstractAction() {
@Override public void actionPerformed(ActionEvent actionEvent) { aboutDialog.setVisible(false); }
};
aboutOkButton.addActionListener(aboutOkActionListener);
hbox.add(aboutOkButton);
hbox.add(Box.createHorizontalGlue());
// Last setup
JRootPane rootPane = aboutDialog.getRootPane();
rootPane.setDefaultButton(aboutOkButton);
rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "AboutView.ok");
rootPane.getActionMap().put("AboutView.ok", aboutOkActionListener);
// Prepare to display
aboutDialog.pack();
});
}
public void show() {
SwingUtil.invokeLater(() -> {
// Show
aboutDialog.setLocationRelativeTo(aboutDialog.getParent());
aboutDialog.setVisible(true);
aboutOkButton.requestFocus();
});
}
}
================================================
FILE: app/src/main/java/org/jd/gui/view/GoToView.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.view;
import org.jd.gui.api.feature.LineNumberNavigable;
import org.jd.gui.model.configuration.Configuration;
import org.jd.gui.util.swing.SwingUtil;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.function.IntConsumer;
public class GoToView {
protected JDialog goToDialog;
protected JLabel goToEnterLineNumberLabel;
protected JTextField goToEnterLineNumberTextField;
protected JLabel goToEnterLineNumberErrorLabel;
protected LineNumberNavigable navigator;
protected IntConsumer okCallback;
public GoToView(Configuration configuration, JFrame mainFrame) {
// Build GUI
SwingUtil.invokeLater(() -> {
goToDialog = new JDialog(mainFrame, "Go to Line", false);
goToDialog.setResizable(false);
Box vbox = Box.createVerticalBox();
vbox.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
goToDialog.add(vbox);
// First label "Enter line number (1..xxx):"
Box hbox = Box.createHorizontalBox();
hbox.add(goToEnterLineNumberLabel = new JLabel());
hbox.add(Box.createHorizontalGlue());
vbox.add(hbox);
vbox.add(Box.createVerticalStrut(10));
// Text field
vbox.add(goToEnterLineNumberTextField = new JTextField(30));
vbox.add(Box.createVerticalStrut(10));
// Error label
hbox = Box.createHorizontalBox();
hbox.add(goToEnterLineNumberErrorLabel = new JLabel(" "));
goToEnterLineNumberTextField.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(KeyEvent e) {
if (! Character.isDigit(e.getKeyChar())) {
e.consume();
}
}
});
hbox.add(Box.createHorizontalGlue());
vbox.add(hbox);
vbox.add(Box.createVerticalStrut(15));
// Buttons "Ok" and "Cancel"
hbox = Box.createHorizontalBox();
hbox.add(Box.createHorizontalGlue());
JButton goToOkButton = new JButton(" Ok ");
hbox.add(goToOkButton);
goToOkButton.setEnabled(false);
goToOkButton.addActionListener(e -> {
okCallback.accept(Integer.valueOf(goToEnterLineNumberTextField.getText()));
goToDialog.setVisible(false);
});
hbox.add(Box.createHorizontalStrut(5));
JButton goToCancelButton = new JButton("Cancel");
hbox.add(goToCancelButton);
Action goToCancelActionListener = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) { goToDialog.setVisible(false); }
};
goToCancelButton.addActionListener(goToCancelActionListener);
vbox.add(hbox);
vbox.add(Box.createVerticalStrut(13));
// Last setup
JRootPane rootPane = goToDialog.getRootPane();
rootPane.setDefaultButton(goToOkButton);
rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "OpenTypeView.cancel");
rootPane.getActionMap().put("OpenTypeView.cancel", goToCancelActionListener);
// Add main listener
goToEnterLineNumberTextField.getDocument().addDocumentListener(new DocumentListener() {
protected Color backgroundColor = UIManager.getColor("TextField.background");
protected Color errorBackgroundColor = Color.decode(configuration.getPreferences().get("JdGuiPreferences.errorBackgroundColor"));
@Override public void insertUpdate(DocumentEvent e) { onTextChange(); }
@Override public void removeUpdate(DocumentEvent e) { onTextChange(); }
@Override public void changedUpdate(DocumentEvent e) { onTextChange(); }
protected void onTextChange() {
String text = goToEnterLineNumberTextField.getText();
if (text.length() == 0) {
goToOkButton.setEnabled(false);
clearErrorMessage();
} else {
try {
int lineNumber = Integer.valueOf(text);
if (lineNumber > navigator.getMaximumLineNumber()) {
goToOkButton.setEnabled(false);
showErrorMessage("Line number out of range");
} else if (navigator.checkLineNumber(lineNumber)) {
goToOkButton.setEnabled(true);
clearErrorMessage();
} else {
goToOkButton.setEnabled(false);
showErrorMessage("Line number not found");
}
} catch (NumberFormatException e) {
goToOkButton.setEnabled(false);
showErrorMessage("Not a number");
}
}
}
protected void showErrorMessage(String message) {
goToEnterLineNumberErrorLabel.setText(message);
goToEnterLineNumberTextField.setBackground(errorBackgroundColor);
}
protected void clearErrorMessage() {
goToEnterLineNumberErrorLabel.setText(" ");
goToEnterLineNumberTextField.setBackground(backgroundColor);
}
});
// Prepare to display
goToDialog.pack();
goToDialog.setLocationRelativeTo(mainFrame);
});
}
public void show(LineNumberNavigable navigator, IntConsumer okCallback) {
this.navigator = navigator;
this.okCallback = okCallback;
SwingUtil.invokeLater(() -> {
// Init
goToEnterLineNumberLabel.setText("Enter line number (1.." + navigator.getMaximumLineNumber() + "):");
goToEnterLineNumberTextField.setText("");
// Show
goToDialog.setVisible(true);
goToEnterLineNumberTextField.requestFocus();
});
}
}
================================================
FILE: app/src/main/java/org/jd/gui/view/MainView.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.view;
import org.jd.gui.Constants;
import org.jd.gui.api.API;
import org.jd.gui.api.feature.*;
import org.jd.gui.model.configuration.Configuration;
import org.jd.gui.model.history.History;
import org.jd.gui.service.platform.PlatformService;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.view.component.IconButton;
import org.jd.gui.view.component.panel.MainTabbedPanel;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import static org.jd.gui.util.swing.SwingUtil.*;
@SuppressWarnings("unchecked")
public class MainView implements UriOpenable, PreferencesChangeListener {
protected History history;
protected Consumer openFilesCallback;
protected JFrame mainFrame;
protected JMenu recentFiles = new JMenu("Recent Files");
protected Action closeAction;
protected Action openTypeAction;
protected Action backwardAction;
protected Action forwardAction;
protected MainTabbedPanel mainTabbedPanel;
protected Box findPanel;
protected JComboBox findComboBox;
protected JCheckBox findCaseSensitive;
protected Color findBackgroundColor;
protected Color findErrorBackgroundColor;
public MainView(
Configuration configuration, API api, History history,
ActionListener openActionListener,
ActionListener closeActionListener,
ActionListener saveActionListener,
ActionListener saveAllSourcesActionListener,
ActionListener exitActionListener,
ActionListener copyActionListener,
ActionListener pasteActionListener,
ActionListener selectAllActionListener,
ActionListener findActionListener,
ActionListener findPreviousActionListener,
ActionListener findNextActionListener,
ActionListener findCaseSensitiveActionListener,
Runnable findCriteriaChangedCallback,
ActionListener openTypeActionListener,
ActionListener openTypeHierarchyActionListener,
ActionListener goToActionListener,
ActionListener backwardActionListener,
ActionListener forwardActionListener,
ActionListener searchActionListener,
ActionListener jdWebSiteActionListener,
ActionListener jdGuiIssuesActionListener,
ActionListener jdCoreIssuesActionListener,
ActionListener preferencesActionListener,
ActionListener aboutActionListener,
Runnable panelClosedCallback,
Consumer currentPageChangedCallback,
Consumer openFilesCallback) {
this.history = history;
this.openFilesCallback = openFilesCallback;
// Build GUI
invokeLater(() -> {
mainFrame = new JFrame("Java Decompiler");
mainFrame.setIconImages(Arrays.asList(getImage("/org/jd/gui/images/jd_icon_32.png"), getImage("/org/jd/gui/images/jd_icon_64.png"), getImage("/org/jd/gui/images/jd_icon_128.png")));
mainFrame.setMinimumSize(new Dimension(Constants.MINIMAL_WIDTH, Constants.MINIMAL_HEIGHT));
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Find panel //
Action findNextAction = newAction("Next", newImageIcon("/org/jd/gui/images/next_nav.png"), true, findNextActionListener);
findPanel = Box.createHorizontalBox();
findPanel.setVisible(false);
findPanel.add(new JLabel("Find: "));
findComboBox = new JComboBox();
findComboBox.setEditable(true);
JComponent editorComponent = (JComponent)findComboBox.getEditor().getEditorComponent();
editorComponent.addKeyListener(new KeyAdapter() {
protected String lastStr = "";
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
findPanel.setVisible(false);
break;
case KeyEvent.VK_ENTER:
String str = getFindText();
if (str.length() > 1) {
int index = ((DefaultComboBoxModel)findComboBox.getModel()).getIndexOf(str);
if(index != -1 ) {
findComboBox.removeItemAt(index);
}
findComboBox.insertItemAt(str, 0);
findComboBox.setSelectedIndex(0);
findNextAction.actionPerformed(null);
}
break;
default:
str = getFindText();
if (! lastStr.equals(str)) {
findCriteriaChangedCallback.run();
lastStr = str;
}
}
}
});
editorComponent.setOpaque(true);
findComboBox.setBackground(this.findBackgroundColor = editorComponent.getBackground());
this.findErrorBackgroundColor = Color.decode(configuration.getPreferences().get("JdGuiPreferences.errorBackgroundColor"));
findPanel.add(findComboBox);
findPanel.add(Box.createHorizontalStrut(5));
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
IconButton findNextButton = new IconButton("Next", newAction(newImageIcon("/org/jd/gui/images/next_nav.png"), true, findNextActionListener));
toolBar.add(findNextButton);
toolBar.add(Box.createHorizontalStrut(5));
IconButton findPreviousButton = new IconButton("Previous", newAction(newImageIcon("/org/jd/gui/images/prev_nav.png"), true, findPreviousActionListener));
toolBar.add(findPreviousButton);
findPanel.add(toolBar);
findCaseSensitive = new JCheckBox();
findCaseSensitive.setAction(newAction("Case sensitive", true, findCaseSensitiveActionListener));
findPanel.add(findCaseSensitive);
findPanel.add(Box.createHorizontalGlue());
IconButton findCloseButton = new IconButton(newAction(null, null, true, e -> findPanel.setVisible(false)));
findCloseButton.setContentAreaFilled(false);
findCloseButton.setIcon(newImageIcon("/org/jd/gui/images/close.gif"));
findCloseButton.setRolloverIcon(newImageIcon("/org/jd/gui/images/close_active.gif"));
findPanel.add(findCloseButton);
if (PlatformService.getInstance().isMac()) {
findPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
Border border = BorderFactory.createEmptyBorder();
findNextButton.setBorder(border);
findPreviousButton.setBorder(border);
findCloseButton.setBorder(border);
} else {
findPanel.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
}
// Actions //
boolean browser = Desktop.isDesktopSupported() ? Desktop.getDesktop().isSupported(Desktop.Action.BROWSE) : false;
Action openAction = newAction("Open File...", newImageIcon("/org/jd/gui/images/open.png"), true, "Open a file", openActionListener);
closeAction = newAction("Close", false, closeActionListener);
Action saveAction = newAction("Save", newImageIcon("/org/jd/gui/images/save.png"), false, saveActionListener);
Action saveAllSourcesAction = newAction("Save All Sources", newImageIcon("/org/jd/gui/images/save_all.png"), false, saveAllSourcesActionListener);
Action exitAction = newAction("Exit", true, "Quit this program", exitActionListener);
Action copyAction = newAction("Copy", newImageIcon("/org/jd/gui/images/copy.png"), false, copyActionListener);
Action pasteAction = newAction("Paste Log", newImageIcon("/org/jd/gui/images/paste.png"), true, pasteActionListener);
Action selectAllAction = newAction("Select all", false, selectAllActionListener);
Action findAction = newAction("Find...", false, findActionListener);
openTypeAction = newAction("Open Type...", newImageIcon("/org/jd/gui/images/open_type.png"), false, openTypeActionListener);
Action openTypeHierarchyAction = newAction("Open Type Hierarchy...", false, openTypeHierarchyActionListener);
Action goToAction = newAction("Go to Line...", false, goToActionListener);
backwardAction = newAction("Back", newImageIcon("/org/jd/gui/images/backward_nav.png"), false, backwardActionListener);
forwardAction = newAction("Forward", newImageIcon("/org/jd/gui/images/forward_nav.png"), false, forwardActionListener);
Action searchAction = newAction("Search...", newImageIcon("/org/jd/gui/images/search_src.png"), false, searchActionListener);
Action jdWebSiteAction = newAction("JD Web site", browser, "Open JD Web site", jdWebSiteActionListener);
Action jdGuiIssuesActionAction = newAction("JD-GUI issues", browser, "Open JD-GUI issues page", jdGuiIssuesActionListener);
Action jdCoreIssuesActionAction = newAction("JD-Core issues", browser, "Open JD-Core issues page", jdCoreIssuesActionListener);
Action preferencesAction = newAction("Preferences...", newImageIcon("/org/jd/gui/images/preferences.png"), true, "Open the preferences panel", preferencesActionListener);
Action aboutAction = newAction("About...", true, "About JD-GUI", aboutActionListener);
// Menu //
int menuShortcutKeyMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
menu.add(openAction).setAccelerator(KeyStroke.getKeyStroke('O', menuShortcutKeyMask));
menu.addSeparator();
menu.add(closeAction).setAccelerator(KeyStroke.getKeyStroke('W', menuShortcutKeyMask));
menu.addSeparator();
menu.add(saveAction).setAccelerator(KeyStroke.getKeyStroke('S', menuShortcutKeyMask));
menu.add(saveAllSourcesAction).setAccelerator(KeyStroke.getKeyStroke('S', menuShortcutKeyMask|InputEvent.ALT_MASK));
menu.addSeparator();
menu.add(recentFiles);
if (!PlatformService.getInstance().isMac()) {
menu.addSeparator();
menu.add(exitAction).setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.ALT_MASK));
}
menu = new JMenu("Edit");
menuBar.add(menu);
menu.add(copyAction).setAccelerator(KeyStroke.getKeyStroke('C', menuShortcutKeyMask));
menu.add(pasteAction).setAccelerator(KeyStroke.getKeyStroke('V', menuShortcutKeyMask));
menu.addSeparator();
menu.add(selectAllAction).setAccelerator(KeyStroke.getKeyStroke('A', menuShortcutKeyMask));
menu.addSeparator();
menu.add(findAction).setAccelerator(KeyStroke.getKeyStroke('F', menuShortcutKeyMask));
menu = new JMenu("Navigation");
menuBar.add(menu);
menu.add(openTypeAction).setAccelerator(KeyStroke.getKeyStroke('T', menuShortcutKeyMask));
menu.add(openTypeHierarchyAction).setAccelerator(KeyStroke.getKeyStroke('H', menuShortcutKeyMask));
menu.addSeparator();
menu.add(goToAction).setAccelerator(KeyStroke.getKeyStroke('L', menuShortcutKeyMask));
menu.addSeparator();
menu.add(backwardAction).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.ALT_MASK));
menu.add(forwardAction).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.ALT_MASK));
menu = new JMenu("Search");
menuBar.add(menu);
menu.add(searchAction).setAccelerator(KeyStroke.getKeyStroke('S', menuShortcutKeyMask|InputEvent.SHIFT_MASK));
menu = new JMenu("Help");
menuBar.add(menu);
if (browser) {
menu.add(jdWebSiteAction);
menu.add(jdGuiIssuesActionAction);
menu.add(jdCoreIssuesActionAction);
menu.addSeparator();
}
menu.add(preferencesAction).setAccelerator(KeyStroke.getKeyStroke('P', menuShortcutKeyMask|InputEvent.SHIFT_MASK));
if (!PlatformService.getInstance().isMac()) {
menu.addSeparator();
menu.add(aboutAction).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
}
mainFrame.setJMenuBar(menuBar);
// Icon bar //
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
toolBar = new JToolBar();
toolBar.setFloatable(false);
toolBar.setRollover(true);
toolBar.add(new IconButton(openAction));
toolBar.addSeparator();
toolBar.add(new IconButton(openTypeAction));
toolBar.add(new IconButton(searchAction));
toolBar.addSeparator();
toolBar.add(new IconButton(backwardAction));
toolBar.add(new IconButton(forwardAction));
panel.add(toolBar, BorderLayout.PAGE_START);
mainTabbedPanel = new MainTabbedPanel(api);
mainTabbedPanel.getPageChangedListeners().add(new PageChangeListener() {
protected JComponent currentPage = null;
@Override public void pageChanged(U page) {
if (currentPage != page) {
// Update current page
currentPage = page;
currentPageChangedCallback.accept((T)page);
invokeLater(() -> {
if (page == null) {
// Update title
mainFrame.setTitle("Java Decompiler");
// Update menu
saveAction.setEnabled(false);
copyAction.setEnabled(false);
selectAllAction.setEnabled(false);
openTypeHierarchyAction.setEnabled(false);
goToAction.setEnabled(false);
// Update find panel
findPanel.setVisible(false);
} else {
// Update title
String path = page.getUri().getPath();
int index = path.lastIndexOf('/');
String name = (index == -1) ? path : path.substring(index + 1);
mainFrame.setTitle((name != null) ? name + " - Java Decompiler" : "Java Decompiler");
// Update history
history.add(page.getUri());
// Update history actions
updateHistoryActions();
// Update menu
saveAction.setEnabled(page instanceof ContentSavable);
copyAction.setEnabled(page instanceof ContentCopyable);
selectAllAction.setEnabled(page instanceof ContentSelectable);
findAction.setEnabled(page instanceof ContentSearchable);
openTypeHierarchyAction.setEnabled(page instanceof FocusedTypeGettable);
goToAction.setEnabled(page instanceof LineNumberNavigable);
// Update find panel
if (findPanel.isVisible()) {
findPanel.setVisible(page instanceof ContentSearchable);
}
}
});
}
}
});
mainTabbedPanel.getTabbedPane().addChangeListener(new ChangeListener() {
protected int lastTabCount = 0;
@Override
public void stateChanged(ChangeEvent e) {
int tabCount = mainTabbedPanel.getTabbedPane().getTabCount();
boolean enabled = (tabCount > 0);
closeAction.setEnabled(enabled);
openTypeAction.setEnabled(enabled);
searchAction.setEnabled(enabled);
saveAllSourcesAction.setEnabled((mainTabbedPanel.getTabbedPane().getSelectedComponent() instanceof SourcesSavable));
if (tabCount < lastTabCount) {
panelClosedCallback.run();
}
lastTabCount = tabCount;
}
});
mainTabbedPanel.preferencesChanged(configuration.getPreferences());
panel.add(mainTabbedPanel, BorderLayout.CENTER);
panel.add(findPanel, BorderLayout.PAGE_END);
mainFrame.add(panel);
});
}
public void show(Point location, Dimension size, boolean maximize) {
invokeLater(() -> {
// Set position, resize and show
mainFrame.setLocation(location);
mainFrame.setSize(size);
mainFrame.setExtendedState(maximize ? JFrame.MAXIMIZED_BOTH : 0);
mainFrame.setVisible(true);
});
}
public JFrame getMainFrame() {
return mainFrame;
}
public void showFindPanel() {
invokeLater(() -> {
findPanel.setVisible(true);
findComboBox.requestFocus();
});
}
public void setFindBackgroundColor(boolean wasFound) {
invokeLater(() -> {
findComboBox.getEditor().getEditorComponent().setBackground(wasFound ? findBackgroundColor : findErrorBackgroundColor);
});
}
public void addMainPanel(String title, Icon icon, String tip, T component) {
invokeLater(() -> {
mainTabbedPanel.addPage(title, icon, tip, component);
});
}
public List getMainPanels() {
return mainTabbedPanel.getPages();
}
public T getSelectedMainPanel() {
return (T)mainTabbedPanel.getTabbedPane().getSelectedComponent();
}
public void closeCurrentTab() {
invokeLater(() -> {
Component component = mainTabbedPanel.getTabbedPane().getSelectedComponent();
if (component instanceof PageClosable) {
if (!((PageClosable)component).closePage()) {
mainTabbedPanel.removeComponent(component);
}
} else {
mainTabbedPanel.removeComponent(component);
}
});
}
public void updateRecentFilesMenu(List files) {
invokeLater(() -> {
recentFiles.removeAll();
for (File file : files) {
JMenuItem menuItem = new JMenuItem(reduceRecentFilePath(file.getAbsolutePath()));
menuItem.addActionListener(e -> openFilesCallback.accept(file));
recentFiles.add(menuItem);
}
});
}
public String getFindText() {
Document doc = ((JTextField)findComboBox.getEditor().getEditorComponent()).getDocument();
try {
return doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
assert ExceptionUtil.printStackTrace(e);
return "";
}
}
public boolean getFindCaseSensitive() { return findCaseSensitive.isSelected(); }
public void updateHistoryActions() {
invokeLater(() -> {
backwardAction.setEnabled(history.canBackward());
forwardAction.setEnabled(history.canForward());
});
}
// --- Utils --- //
static String reduceRecentFilePath(String path) {
int lastSeparatorPosition = path.lastIndexOf(File.separatorChar);
if ((lastSeparatorPosition == -1) || (lastSeparatorPosition < Constants.RECENT_FILE_MAX_LENGTH)) {
return path;
}
int length = Constants.RECENT_FILE_MAX_LENGTH/2 - 2;
String left = path.substring(0, length);
String right = path.substring(path.length() - length);
return left + "..." + right;
}
// --- URIOpener --- //
@Override
public boolean openUri(URI uri) {
boolean success = mainTabbedPanel.openUri(uri);
if (success) {
closeAction.setEnabled(true);
openTypeAction.setEnabled(true);
}
return success;
}
// --- PreferencesChangeListener --- //
@Override
public void preferencesChanged(Map preferences) {
mainTabbedPanel.preferencesChanged(preferences);
}
}
================================================
FILE: app/src/main/java/org/jd/gui/view/OpenTypeHierarchyView.java
================================================
/*
* Copyright (c) 2008-2019 Emmanuel Dupuy.
* This project is distributed under the GPLv3 license.
* This is a Copyleft license that gives the user the right to use,
* copy and modify the code freely for non-commercial purposes.
*/
package org.jd.gui.view;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.api.model.Indexes;
import org.jd.gui.api.model.TreeNodeData;
import org.jd.gui.api.model.Type;
import org.jd.gui.util.exception.ExceptionUtil;
import org.jd.gui.util.function.TriConsumer;
import org.jd.gui.util.swing.SwingUtil;
import org.jd.gui.view.component.Tree;
import org.jd.gui.view.renderer.TreeNodeRenderer;
import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.Future;
public class OpenTypeHierarchyView {
protected static final ImageIcon ROOT_CLASS_ICON = new ImageIcon(OpenTypeHierarchyView.class.getClassLoader().getResource("org/jd/gui/images/generate_class.png"));
protected static final ImageIcon ROOT_INTERFACE_ICON = new ImageIcon(OpenTypeHierarchyView.class.getClassLoader().getResource("org/jd/gui/images/generate_int.png"));
protected static final TreeNodeComparator TREE_NODE_COMPARATOR = new TreeNodeComparator();
protected API api;
protected Collection> collectionOfFutureIndexes;
protected JDialog openTypeHierarchyDialog;
protected Tree openTypeHierarchyTree;
protected TriConsumer, String> selectedTypeCallback;
public OpenTypeHierarchyView(API api, JFrame mainFrame, TriConsumer, String> selectedTypeCallback) {
this.api = api;
this.selectedTypeCallback = selectedTypeCallback;
// Build GUI
SwingUtil.invokeLater(() -> {
openTypeHierarchyDialog = new JDialog(mainFrame, "Hierarchy Type", false);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
panel.setLayout(new BorderLayout());
openTypeHierarchyDialog.add(panel);
openTypeHierarchyTree = new Tree();
openTypeHierarchyTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode()));
openTypeHierarchyTree.setCellRenderer(new TreeNodeRenderer());
openTypeHierarchyTree.addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
onTypeSelected();
}
}
});
openTypeHierarchyTree.addTreeExpansionListener(new TreeExpansionListener() {
@Override public void treeExpanded(TreeExpansionEvent e) {
TreeNode node = (TreeNode)e.getPath().getLastPathComponent();
// Expand node and find the first leaf
while (node.getChildCount() > 0) {
if (((DefaultMutableTreeNode)node.getChildAt(0)).getUserObject() == null) {
// Remove dummy node and create children
populateTreeNode(node, null);
}
if (node.getChildCount() != 1) {
break;
}
node = ((TreeNode)node.getChildAt(0));
}
DefaultTreeModel model = (DefaultTreeModel)openTypeHierarchyTree.getModel();
model.reload((TreeNode)e.getPath().getLastPathComponent());
openTypeHierarchyTree.setSelectionPath(new TreePath(node.getPath()));
}
@Override public void treeCollapsed(TreeExpansionEvent e) {}
});
openTypeHierarchyTree.addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F4) {
TreeNode node = (TreeNode)openTypeHierarchyTree.getLastSelectedPathComponent();
if (node != null) {
updateTree(node.entry, node.typeName);
}
}
}
});
JScrollPane openTypeHierarchyScrollPane = new JScrollPane(openTypeHierarchyTree);
openTypeHierarchyScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
openTypeHierarchyScrollPane.setPreferredSize(new Dimension(400, 150));
panel.add(openTypeHierarchyScrollPane, BorderLayout.CENTER);
// Buttons "Open" and "Cancel"
Box vbox = Box.createVerticalBox();
panel.add(vbox, BorderLayout.SOUTH);
vbox.add(Box.createVerticalStrut(25));
Box hbox = Box.createHorizontalBox();
vbox.add(hbox);
hbox.add(Box.createHorizontalGlue());
JButton openTypeHierarchyOpenButton = new JButton("Open");
hbox.add(openTypeHierarchyOpenButton);
openTypeHierarchyOpenButton.setEnabled(false);
openTypeHierarchyOpenButton.addActionListener(e -> onTypeSelected());
hbox.add(Box.createHorizontalStrut(5));
JButton openTypeHierarchyCancelButton = new JButton("Cancel");
hbox.add(openTypeHierarchyCancelButton);
Action openTypeHierarchyCancelActionListener = new AbstractAction() {
@Override public void actionPerformed(ActionEvent actionEvent) { openTypeHierarchyDialog.setVisible(false); }
};
openTypeHierarchyCancelButton.addActionListener(openTypeHierarchyCancelActionListener);
openTypeHierarchyTree.addTreeSelectionListener(e -> {
Object o = openTypeHierarchyTree.getLastSelectedPathComponent();
if (o != null) {
o = ((TreeNode)o).entry;
}
openTypeHierarchyOpenButton.setEnabled(o != null);
});
// Last setup
JRootPane rootPane = openTypeHierarchyDialog.getRootPane();
rootPane.setDefaultButton(openTypeHierarchyOpenButton);
rootPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "OpenTypeHierarchyView.cancel");
rootPane.getActionMap().put("OpenTypeHierarchyView.cancel", openTypeHierarchyCancelActionListener);
openTypeHierarchyDialog.setMinimumSize(openTypeHierarchyDialog.getSize());
// Prepare to display
openTypeHierarchyDialog.pack();
openTypeHierarchyDialog.setLocationRelativeTo(mainFrame);
});
}
public void show(Collection> collectionOfFutureIndexes, Container.Entry entry, String typeName) {
this.collectionOfFutureIndexes = collectionOfFutureIndexes;
SwingUtil.invokeLater(() -> {
updateTree(entry, typeName);
openTypeHierarchyDialog.setVisible(true);
openTypeHierarchyTree.requestFocus();
});
}
public boolean isVisible() { return openTypeHierarchyDialog.isVisible(); }
public void showWaitCursor() {
SwingUtil.invokeLater(() -> openTypeHierarchyDialog.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)));
}
public void hideWaitCursor() {
SwingUtil.invokeLater(() -> openTypeHierarchyDialog.setCursor(Cursor.getDefaultCursor()));
}
public void updateTree(Collection