Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/keenwrite.git

Fix NPE spotted by SpotBugs

Author DaveJarvis <email>
Date 2023-05-06 16:57:31 GMT-0700
Commit bc4ac1256b6f218a86bb36ff378ad871ec8c27fe
Parent 96edd92
build.gradle
id 'org.openjfx.javafxplugin' version '0.0.14'
id 'com.palantir.git-version' version '3.0.0'
- //id "com.github.spotbugs" version "5.0.14"
+ id "com.github.spotbugs" version "5.0.14"
}
testImplementation "org.junit.jupiter:junit-jupiter-params:${v_junit}"
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
+}
+
+sourceSets {
+ main {
+ java {
+ srcDirs 'src/main'
+ }
+ }
+
+ test {
+ java {
+ srcDirs 'src/test'
+ }
+ }
}
src/main/java/com/keenwrite/AppCommands.java
import com.keenwrite.cmdline.Arguments;
import com.keenwrite.commands.ConcatenateCommand;
+import com.keenwrite.io.SysFile;
import com.keenwrite.processors.Processor;
import com.keenwrite.processors.ProcessorContext;
final var inputPath = context.getSourcePath();
final var parent = inputPath.getParent();
- final var filename = inputPath.getFileName().toString();
+ final var filename = SysFile.getFileName( inputPath );
final var extension = getExtension( filename );
src/main/java/com/keenwrite/collections/CircularQueue.java
@Override
public E next() {
- final var element = mElements[ mIndex++ ];
- mIndex %= mCapacity;
- mFirst = false;
+ try {
+ final var element = mElements[ mIndex++ ];
+ mIndex %= mCapacity;
+ mFirst = false;
- return (E) element;
+ return (E) element;
+ } catch( final IndexOutOfBoundsException ex ) {
+ throw new NoSuchElementException( "No such element at: " + mIndex );
+ }
}
};
src/main/java/com/keenwrite/events/workspace/WorkspaceLoadedEvent.java
* @return The {@link Workspace} that has loaded user preferences.
*/
- public Workspace getWorkspace() {
+ @SuppressWarnings( "unused" )
+ private Workspace getWorkspace() {
return mWorkspace;
}
src/main/java/com/keenwrite/io/FileWatchService.java
*/
public void unregister( final File file ) {
- mWatched.remove( cancel( file ) );
+ cancel( file );
+ mWatched.remove( file );
}
/**
* Cancels watching the given file for file system changes.
*
* @param file The {@link File} to watch for file events.
- * @return The given file, always.
*/
- private File cancel( final File file ) {
+ private void cancel( final File file ) {
final var watchKey = mWatched.get( file );
if( watchKey != null ) {
watchKey.cancel();
}
-
- return file;
}
} catch( final Exception ex ) {
// Create a fallback that allows the class to be instantiated and used
- // without without preventing the application from launching.
+ // without preventing the application from launching.
return new PollingWatchService();
}
src/main/java/com/keenwrite/io/SysFile.java
/**
+ * Provides {@code null}-safe machinery to get a file name.
+ *
+ * @param p The path to the file name to retrieve (may be {@code null}).
+ * @return The file name or the empty string if the path is not found.
+ */
+ public static String getFileName( final Path p ) {
+ return p == null ? "" : getPathFileName( p );
+ }
+
+ private static String getPathFileName( final Path p ) {
+ assert p != null;
+
+ final var f = p.getFileName();
+
+ return f == null ? "" : f.toString();
+ }
+
+ /**
* Changes to the PATH environment variable aren't reflected for the
* currently running task. The registry, however, contains the updated
}
+ @SuppressWarnings( "SpellCheckingInspection" )
private String pathsWindows( final Function<String, String> map ) {
try {
}
- final var subexpr = compile( quote( match ) );
- expanded = subexpr.matcher( expanded ).replaceAll( value );
+ final var subexpression = compile( quote( match ) );
+ expanded = subexpression.matcher( expanded ).replaceAll( value );
}
src/main/java/com/keenwrite/io/Zip.java
*/
public static void extract( final Path zipPath ) throws IOException {
- final var path = zipPath.getParent().normalize();
+ final var parent = zipPath.getParent();
+
+ if( parent == null ) {
+ throw new IOException( "Path to zip file has no parent." );
+ }
+
+ final var path = parent.normalize();
iterate( zipPath, ( zipFile, zipEntry ) -> {
final Path zipEntryPath ) throws IOException {
// Only extract files, skip empty directories.
- if( !zipEntry.isDirectory() ) {
- createDirectories( zipEntryPath.getParent() );
+ if( !zipEntry.isDirectory() && zipEntryPath != null ) {
+ final var parent = zipEntryPath.getParent();
- try( final var in = zipFile.getInputStream( zipEntry ) ) {
- Files.copy( in, zipEntryPath, REPLACE_EXISTING );
+ if( parent != null ) {
+ createDirectories( parent );
+
+ try( final var in = zipFile.getInputStream( zipEntry ) ) {
+ Files.copy( in, zipEntryPath, REPLACE_EXISTING );
+ }
}
}
src/main/java/com/keenwrite/preferences/SimpleTableControl.java
private static long sCounter;
- public SimpleTableControl() {}
+ public SimpleTableControl() { }
@Override
public void initializeParts() {
super.initializeParts();
- final var model = field.viewProperty();
- final var table = new TableView<>( model );
+ final var field = getField();
+ final var table = field.createTableView();
table.setColumnResizePolicy( CONSTRAINED_RESIZE_POLICY_FLEX_LAST_COLUMN );
sCounter++;
- model.add( createEntry( "key" + sCounter, "value" + sCounter ) );
+ field.add( createEntry( "key" + sCounter, "value" + sCounter ) );
}
),
*/
@Override
- public void layoutParts() {}
+ public void layoutParts() { }
}
src/main/java/com/keenwrite/preferences/TableField.java
import javafx.beans.property.Property;
import javafx.beans.property.SimpleListProperty;
+import javafx.scene.control.TableView;
import java.util.ArrayList;
}
- /**
- * Returns the data model that seeds the user interface. At any point the
- * user may cancel editing, which will revert to the previously persisted
- * set.
- *
- * @return The source for values displayed in the UI.
- */
- public ListProperty<P> viewProperty() {
- return mViewProperty;
+ public TableView<P> createTableView() {
+ return new TableView<>( mViewProperty );
+ }
+
+ public void add( final P entry ) {
+ mViewProperty.add( entry );
}
src/main/java/com/keenwrite/preview/DiagramUrlGenerator.java
package com.keenwrite.preview;
+import java.nio.charset.StandardCharsets;
import java.util.zip.Deflater;
*/
private static String encode( final String text ) {
- return getUrlEncoder().encodeToString( compress( text.getBytes() ) );
+ return getUrlEncoder().encodeToString(
+ compress( text.getBytes( StandardCharsets.UTF_8 ) )
+ );
}
src/main/java/com/keenwrite/search/SearchModel.java
final var emits = trie.parseText( haystack );
- mMatches = new CyclicIterator<>( new ArrayList<>( emits ) );
+ mMatches = new CyclicIterator<>( emits );
mMatchCount.set( emits.size() );
mNeedle = needle;
src/main/java/com/keenwrite/typesetting/GuestTypesetter.java
import com.keenwrite.io.CommandNotFoundException;
import com.keenwrite.io.StreamGobbler;
+import com.keenwrite.io.SysFile;
import com.keenwrite.typesetting.containerization.Podman;
import org.apache.commons.io.FilenameUtils;
static String removeExtension( final Path path ) {
- return FilenameUtils.removeExtension( path.toString() );
+ return FilenameUtils.removeExtension( SysFile.getFileName( path ) );
}
src/main/java/com/keenwrite/typesetting/HostTypesetter.java
// error files.
if( exit > 0 ) {
- final var xmlName = getSourcePath().getFileName().toString();
- final var srcName = getTargetPath().getFileName().toString();
+ final var xmlName = SysFile.getFileName( getSourcePath() );
+ final var srcName = SysFile.getFileName( getTargetPath() );
final var logName = newExtension( xmlName, ".log" );
final var errName = newExtension( xmlName, "-error.log" );
src/main/java/com/keenwrite/typesetting/containerization/Podman.java
import java.io.File;
+import java.io.IOException;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.List;
+import java.util.NoSuchElementException;
import static com.keenwrite.Bootstrap.CONTAINER_VERSION;
return wait( process );
- } catch( final Exception ex ) {
+ } catch( final NoSuchElementException |
+ IOException |
+ InterruptedException ex ) {
throw new CommandNotFoundException( MANAGER.toString() );
}
src/main/java/com/keenwrite/ui/actions/GuiCommands.java
import com.keenwrite.events.CaretMovedEvent;
import com.keenwrite.events.ExportFailedEvent;
-import com.keenwrite.preferences.Key;
-import com.keenwrite.preferences.PreferencesController;
-import com.keenwrite.preferences.Workspace;
-import com.keenwrite.processors.markdown.MarkdownProcessor;
-import com.keenwrite.search.SearchModel;
-import com.keenwrite.typesetting.Typesetter;
-import com.keenwrite.ui.controls.SearchBar;
-import com.keenwrite.ui.dialogs.ExportDialog;
-import com.keenwrite.ui.dialogs.ExportSettings;
-import com.keenwrite.ui.dialogs.ImageDialog;
-import com.keenwrite.ui.dialogs.LinkDialog;
-import com.keenwrite.ui.explorer.FilePicker;
-import com.keenwrite.ui.explorer.FilePickerFactory;
-import com.keenwrite.ui.logging.LogView;
-import com.vladsch.flexmark.ast.Link;
-import javafx.concurrent.Service;
-import javafx.concurrent.Task;
-import javafx.scene.control.Alert;
-import javafx.scene.control.Dialog;
-import javafx.stage.Window;
-import javafx.stage.WindowEvent;
-
-import java.io.File;
-import java.nio.file.Path;
-import java.util.List;
-import java.util.Optional;
-
-import static com.keenwrite.Bootstrap.*;
-import static com.keenwrite.ExportFormat.*;
-import static com.keenwrite.Messages.get;
-import static com.keenwrite.constants.Constants.PDF_DEFAULT;
-import static com.keenwrite.constants.Constants.USER_DIRECTORY;
-import static com.keenwrite.constants.GraphicsConstants.ICON_DIALOG_NODE;
-import static com.keenwrite.events.StatusEvent.clue;
-import static com.keenwrite.preferences.AppKeys.*;
-import static com.keenwrite.processors.ProcessorFactory.createProcessors;
-import static com.keenwrite.ui.explorer.FilePickerFactory.SelectionType;
-import static com.keenwrite.ui.explorer.FilePickerFactory.SelectionType.*;
-import static java.nio.file.Files.writeString;
-import static javafx.application.Platform.runLater;
-import static javafx.event.Event.fireEvent;
-import static javafx.scene.control.Alert.AlertType.INFORMATION;
-import static javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST;
-import static org.apache.commons.io.FilenameUtils.getExtension;
-
-/**
- * Responsible for abstracting how functionality is mapped to the application.
- * This allows users to customize accelerator keys and will provide pluggable
- * functionality so that different text markup languages can change documents
- * using their respective syntax.
- */
-public final class GuiCommands {
- private static final String STYLE_SEARCH = "search";
-
- /**
- * When an action is executed, this is one of the recipients.
- */
- private final MainPane mMainPane;
-
- private final MainScene mMainScene;
-
- private final LogView mLogView;
-
- /**
- * Tracks finding text in the active document.
- */
- private final SearchModel mSearchModel;
-
- private boolean mCanTypeset;
-
- /**
- * A {@link Task} can only be run once, so wrap it in a {@link Service} to
- * allow re-launching the typesetting task repeatedly.
- */
- private Service<Path> mTypesetService;
-
- /**
- * Prevent a race-condition between checking to see if the typesetting task
- * is running and restarting the task itself.
- */
- private final Object mMutex = new Object();
-
- public GuiCommands( final MainScene scene, final MainPane pane ) {
- mMainScene = scene;
- mMainPane = pane;
- mLogView = new LogView();
- mSearchModel = new SearchModel();
- mSearchModel.matchOffsetProperty().addListener( ( c, o, n ) -> {
- final var editor = getActiveTextEditor();
-
- // Clear highlighted areas before highlighting a new region.
- if( o != null ) {
- editor.unstylize( STYLE_SEARCH );
- }
-
- if( n != null ) {
- editor.moveTo( n.getStart() );
- editor.stylize( n, STYLE_SEARCH );
- }
- } );
-
- // When the active text editor changes ...
- mMainPane.textEditorProperty().addListener(
- ( c, o, n ) -> {
- // ... update the haystack.
- mSearchModel.search( getActiveTextEditor().getText() );
-
- // ... update the status bar with the current caret position.
- if( n != null ) {
- final var w = getWorkspace();
- final var recentDoc = w.fileProperty( KEY_UI_RECENT_DOCUMENT );
-
- // ... preserve the most recent document.
- recentDoc.setValue( n.getFile() );
- CaretMovedEvent.fire( n.getCaret() );
- }
- }
- );
- }
-
- public void file_new() {
- getMainPane().newTextEditor();
- }
-
- public void file_open() {
- pickFiles( FILE_OPEN_MULTIPLE ).ifPresent( l -> getMainPane().open( l ) );
- }
-
- public void file_close() {
- getMainPane().close();
- }
-
- public void file_close_all() {
- getMainPane().closeAll();
- }
-
- public void file_save() {
- getMainPane().save();
- }
-
- public void file_save_as() {
- pickFiles( FILE_SAVE_AS ).ifPresent( l -> getMainPane().saveAs( l ) );
- }
-
- public void file_save_all() {
- getMainPane().saveAll();
- }
-
- /**
- * Converts the actively edited file in the given file format.
- *
- * @param format The destination file format.
- */
- private void file_export( final ExportFormat format ) {
- file_export( format, false );
- }
-
- /**
- * Converts one or more files into the given file format. If {@code dir}
- * is set to true, this will first append all files in the same directory
- * as the actively edited file.
- *
- * @param format The destination file format.
- * @param dir Export all files in the actively edited file's directory.
- */
- private void file_export( final ExportFormat format, final boolean dir ) {
- final var editor = getMainPane().getTextEditor();
- final var exported = getWorkspace().fileProperty( KEY_UI_RECENT_EXPORT );
- final var exportParent = exported.get().toPath().getParent();
- final var editorParent = editor.getPath().getParent();
- final var userHomeParent = USER_DIRECTORY.toPath();
- final var exportPath = exportParent != null
- ? exportParent
- : editorParent != null
- ? editorParent
- : userHomeParent;
-
- final var filename = format.toExportFilename( editor.getPath() );
- final var selected = PDF_DEFAULT
- .getName()
- .equals( exported.get().getName() );
- final var selection = pickFile(
- selected
- ? filename
- : exported.get(),
- exportPath,
- FILE_EXPORT
- );
-
- selection.ifPresent( files -> file_export( editor, format, files, dir ) );
- }
-
- private void file_export(
- final TextEditor editor,
- final ExportFormat format,
- final List<File> files,
- final boolean dir ) {
- editor.save();
- final var main = getMainPane();
- final var exported = getWorkspace().fileProperty( KEY_UI_RECENT_EXPORT );
-
- final var sourceFile = files.get( 0 );
- final var sourcePath = sourceFile.toPath();
- final var document = dir ? append( editor ) : editor.getText();
- final var context = main.createProcessorContext( sourcePath, format );
-
- final var service = new Service<Path>() {
- @Override
- protected Task<Path> createTask() {
- final var task = new Task<Path>() {
- @Override
- protected Path call() throws Exception {
- final var chain = createProcessors( context );
- final var export = chain.apply( document );
-
- // Processors can export binary files. In such cases, processors
- // return null to prevent further processing.
- return export == null ? null : writeString( sourcePath, export );
- }
- };
-
- task.setOnSucceeded(
- e -> {
- // Remember the exported file name for next time.
- exported.setValue( sourceFile );
-
- final var result = task.getValue();
-
- // Binary formats must notify users of success independently.
- if( result != null ) {
- clue( "Main.status.export.success", result );
- }
- }
- );
-
- task.setOnFailed( e -> {
- final var ex = task.getException();
- clue( ex );
-
- if( ex instanceof TypeNotPresentException ) {
- fireExportFailedEvent();
- }
- } );
-
- return task;
- }
- };
-
- mTypesetService = service;
- typeset( service );
- }
-
- /**
- * @param dir {@code true} means to export all files in the active file
- * editor's directory; {@code false} means to export only the
- * actively edited file.
- */
- private void file_export_pdf( final boolean dir ) {
- final var workspace = getWorkspace();
- final var themes = workspace.getFile(
- KEY_TYPESET_CONTEXT_THEMES_PATH
- );
- final var theme = workspace.stringProperty(
- KEY_TYPESET_CONTEXT_THEME_SELECTION
- );
- final var chapters = workspace.stringProperty(
- KEY_TYPESET_CONTEXT_CHAPTERS
- );
- final var settings = ExportSettings
- .builder()
- .with( ExportSettings.Mutator::setTheme, theme )
- .with( ExportSettings.Mutator::setChapters, chapters )
- .build();
-
- // Don't re-validate the typesetter installation each time. If the
- // user mucks up the typesetter installation, it'll get caught the
- // next time the application is started. Don't use |= because it
- // won't short-circuit.
- mCanTypeset = mCanTypeset || Typesetter.canRun();
-
- if( mCanTypeset ) {
- // If the typesetter is installed, allow the user to select a theme. If
- // the themes aren't installed, a status message will appear.
- if( ExportDialog.choose( getWindow(), themes, settings, dir ) ) {
- file_export( APPLICATION_PDF, dir );
- }
- }
- else {
- fireExportFailedEvent();
- }
- }
-
- public void file_export_pdf() {
- file_export_pdf( false );
- }
-
- public void file_export_pdf_dir() {
- file_export_pdf( true );
- }
-
- public void file_export_html_dir() {
- file_export( XHTML_TEX, true );
- }
-
- public void file_export_repeat() {
- typeset( mTypesetService );
- }
-
- public void file_export_html_svg() {
- file_export( HTML_TEX_SVG );
- }
-
- public void file_export_html_tex() {
- file_export( HTML_TEX_DELIMITED );
- }
-
- public void file_export_xhtml_tex() {
- file_export( XHTML_TEX );
- }
-
- private void fireExportFailedEvent() {
- runLater( ExportFailedEvent::fire );
- }
-
- public void file_exit() {
- final var window = getWindow();
- fireEvent( window, new WindowEvent( window, WINDOW_CLOSE_REQUEST ) );
- }
-
- public void edit_undo() {
- getActiveTextEditor().undo();
- }
-
- public void edit_redo() {
- getActiveTextEditor().redo();
- }
-
- public void edit_cut() {
- getActiveTextEditor().cut();
- }
-
- public void edit_copy() {
- getActiveTextEditor().copy();
- }
-
- public void edit_paste() {
- getActiveTextEditor().paste();
- }
-
- public void edit_select_all() {
- getActiveTextEditor().selectAll();
- }
-
- public void edit_find() {
- final var nodes = getMainScene().getStatusBar().getLeftItems();
-
- if( nodes.isEmpty() ) {
- final var searchBar = new SearchBar();
-
- searchBar.matchIndexProperty().bind( mSearchModel.matchIndexProperty() );
- searchBar.matchCountProperty().bind( mSearchModel.matchCountProperty() );
-
- searchBar.setOnCancelAction( event -> {
- final var editor = getActiveTextEditor();
- nodes.remove( searchBar );
- editor.unstylize( STYLE_SEARCH );
- editor.getNode().requestFocus();
- } );
-
- searchBar.addInputListener( ( c, o, n ) -> {
- if( n != null && !n.isEmpty() ) {
- mSearchModel.search( n, getActiveTextEditor().getText() );
- }
- } );
-
- searchBar.setOnNextAction( event -> edit_find_next() );
- searchBar.setOnPrevAction( event -> edit_find_prev() );
-
- nodes.add( searchBar );
- searchBar.requestFocus();
- }
- }
-
- public void edit_find_next() {
- mSearchModel.advance();
- }
-
- public void edit_find_prev() {
- mSearchModel.retreat();
- }
-
- public void edit_preferences() {
- try {
- new PreferencesController( getWorkspace() ).show();
- } catch( final Exception ex ) {
- clue( ex );
- }
- }
-
- public void format_bold() {
- getActiveTextEditor().bold();
- }
-
- public void format_italic() {
- getActiveTextEditor().italic();
- }
-
- public void format_monospace() {
- getActiveTextEditor().monospace();
- }
-
- public void format_superscript() {
- getActiveTextEditor().superscript();
- }
-
- public void format_subscript() {
- getActiveTextEditor().subscript();
- }
-
- public void format_strikethrough() {
- getActiveTextEditor().strikethrough();
- }
-
- public void insert_blockquote() {
- getActiveTextEditor().blockquote();
- }
-
- public void insert_code() {
- getActiveTextEditor().code();
- }
-
- public void insert_fenced_code_block() {
- getActiveTextEditor().fencedCodeBlock();
- }
-
- public void insert_link() {
- insertObject( createLinkDialog() );
- }
-
- public void insert_image() {
- insertObject( createImageDialog() );
- }
-
- private void insertObject( final Dialog<String> dialog ) {
- final var textArea = getActiveTextEditor().getTextArea();
- dialog.showAndWait().ifPresent( textArea::replaceSelection );
- }
-
- private Dialog<String> createLinkDialog() {
- return new LinkDialog( getWindow(), createHyperlinkModel() );
- }
-
- private Dialog<String> createImageDialog() {
- final var path = getActiveTextEditor().getPath();
- final var parentDir = path.getParent();
- return new ImageDialog( getWindow(), parentDir );
- }
-
- /**
- * Returns one of: selected text, word under cursor, or parsed hyperlink from
- * the Markdown AST.
- *
- * @return An instance containing the link URL and display text.
- */
- private HyperlinkModel createHyperlinkModel() {
- final var context = getMainPane().createProcessorContext();
- final var editor = getActiveTextEditor();
- final var textArea = editor.getTextArea();
- final var selectedText = textArea.getSelectedText();
-
- // Convert current paragraph to Markdown nodes.
- final var mp = MarkdownProcessor.create( context );
- final var p = textArea.getCurrentParagraph();
- final var paragraph = textArea.getText( p );
- final var node = mp.toNode( paragraph );
- final var visitor = new LinkVisitor( textArea.getCaretColumn() );
- final var link = visitor.process( node );
-
- if( link != null ) {
- textArea.selectRange( p, link.getStartOffset(), p, link.getEndOffset() );
- }
-
- return createHyperlinkModel( link, selectedText );
- }
-
- private HyperlinkModel createHyperlinkModel(
- final Link link, final String selection ) {
-
- return link == null
- ? new HyperlinkModel( selection, "https://localhost" )
- : new HyperlinkModel( link );
- }
-
- public void insert_heading_1() {
- insert_heading( 1 );
- }
-
- public void insert_heading_2() {
- insert_heading( 2 );
- }
-
- public void insert_heading_3() {
- insert_heading( 3 );
- }
-
- private void insert_heading( final int level ) {
- getActiveTextEditor().heading( level );
- }
-
- public void insert_unordered_list() {
- getActiveTextEditor().unorderedList();
- }
-
- public void insert_ordered_list() {
- getActiveTextEditor().orderedList();
- }
-
- public void insert_horizontal_rule() {
- getActiveTextEditor().horizontalRule();
- }
-
- public void definition_create() {
- getActiveTextDefinition().createDefinition();
- }
-
- public void definition_rename() {
- getActiveTextDefinition().renameDefinition();
- }
-
- public void definition_delete() {
- getActiveTextDefinition().deleteDefinitions();
- }
-
- public void definition_autoinsert() {
- getMainPane().autoinsert();
- }
-
- public void view_refresh() {
- getMainPane().viewRefresh();
- }
-
- public void view_preview() {
- getMainPane().viewPreview();
- }
-
- public void view_outline() {
- getMainPane().viewOutline();
- }
-
- public void view_files() { getMainPane().viewFiles(); }
-
- public void view_statistics() {
- getMainPane().viewStatistics();
- }
-
- public void view_menubar() {
- getMainScene().toggleMenuBar();
- }
-
- public void view_toolbar() {
- getMainScene().toggleToolBar();
- }
-
- public void view_statusbar() {
- getMainScene().toggleStatusBar();
- }
-
- public void view_log() {
- mLogView.view();
- }
-
- public void help_about() {
- final var alert = new Alert( INFORMATION );
- final var prefix = "Dialog.about.";
- alert.setTitle( get( prefix + "title", APP_TITLE ) );
- alert.setHeaderText( get( prefix + "header", APP_TITLE ) );
- alert.setContentText( get( prefix + "content", APP_YEAR, APP_VERSION ) );
- alert.setGraphic( ICON_DIALOG_NODE );
- alert.initOwner( getWindow() );
- alert.showAndWait();
- }
-
- private <T> void typeset( final Service<T> service ) {
- synchronized( mMutex ) {
- if( service != null && !service.isRunning() ) {
- service.reset();
- service.start();
- }
- }
- }
-
- /**
- * Concatenates all the files in the same directory as the given file into
- * a string. The extension is determined by the given file name pattern; the
- * order files are concatenated is based on their numeric sort order (this
- * avoids lexicographic sorting).
- * <p>
- * If the parent path to the file being edited in the text editor cannot
- * be found then this will return the editor's text, without iterating through
- * the parent directory. (Should never happen, but who knows?)
- * </p>
- * <p>
- * New lines are automatically appended to separate each file.
- * </p>
- *
- * @param editor The text editor containing
- * @return All files in the same directory as the file being edited
- * concatenated into a single string.
- */
- private String append( final TextEditor editor ) {
- final var pattern = editor.getPath();
- final var parent = pattern.getParent();
-
- // Short-circuit because nothing else can be done.
- if( parent == null ) {
- clue( "Main.status.export.concat.parent", pattern );
- return editor.getText();
- }
-
- final var filename = pattern.getFileName().toString();
+import com.keenwrite.io.SysFile;
+import com.keenwrite.preferences.Key;
+import com.keenwrite.preferences.PreferencesController;
+import com.keenwrite.preferences.Workspace;
+import com.keenwrite.processors.markdown.MarkdownProcessor;
+import com.keenwrite.search.SearchModel;
+import com.keenwrite.typesetting.Typesetter;
+import com.keenwrite.ui.controls.SearchBar;
+import com.keenwrite.ui.dialogs.ExportDialog;
+import com.keenwrite.ui.dialogs.ExportSettings;
+import com.keenwrite.ui.dialogs.ImageDialog;
+import com.keenwrite.ui.dialogs.LinkDialog;
+import com.keenwrite.ui.explorer.FilePicker;
+import com.keenwrite.ui.explorer.FilePickerFactory;
+import com.keenwrite.ui.logging.LogView;
+import com.vladsch.flexmark.ast.Link;
+import javafx.concurrent.Service;
+import javafx.concurrent.Task;
+import javafx.scene.control.Alert;
+import javafx.scene.control.Dialog;
+import javafx.stage.Window;
+import javafx.stage.WindowEvent;
+
+import java.io.File;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Optional;
+
+import static com.keenwrite.Bootstrap.*;
+import static com.keenwrite.ExportFormat.*;
+import static com.keenwrite.Messages.get;
+import static com.keenwrite.constants.Constants.PDF_DEFAULT;
+import static com.keenwrite.constants.Constants.USER_DIRECTORY;
+import static com.keenwrite.constants.GraphicsConstants.ICON_DIALOG_NODE;
+import static com.keenwrite.events.StatusEvent.clue;
+import static com.keenwrite.preferences.AppKeys.*;
+import static com.keenwrite.processors.ProcessorFactory.createProcessors;
+import static com.keenwrite.ui.explorer.FilePickerFactory.SelectionType;
+import static com.keenwrite.ui.explorer.FilePickerFactory.SelectionType.*;
+import static java.nio.file.Files.writeString;
+import static javafx.application.Platform.runLater;
+import static javafx.event.Event.fireEvent;
+import static javafx.scene.control.Alert.AlertType.INFORMATION;
+import static javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST;
+import static org.apache.commons.io.FilenameUtils.getExtension;
+
+/**
+ * Responsible for abstracting how functionality is mapped to the application.
+ * This allows users to customize accelerator keys and will provide pluggable
+ * functionality so that different text markup languages can change documents
+ * using their respective syntax.
+ */
+public final class GuiCommands {
+ private static final String STYLE_SEARCH = "search";
+
+ /**
+ * When an action is executed, this is one of the recipients.
+ */
+ private final MainPane mMainPane;
+
+ private final MainScene mMainScene;
+
+ private final LogView mLogView;
+
+ /**
+ * Tracks finding text in the active document.
+ */
+ private final SearchModel mSearchModel;
+
+ private boolean mCanTypeset;
+
+ /**
+ * A {@link Task} can only be run once, so wrap it in a {@link Service} to
+ * allow re-launching the typesetting task repeatedly.
+ */
+ private Service<Path> mTypesetService;
+
+ /**
+ * Prevent a race-condition between checking to see if the typesetting task
+ * is running and restarting the task itself.
+ */
+ private final Object mMutex = new Object();
+
+ public GuiCommands( final MainScene scene, final MainPane pane ) {
+ mMainScene = scene;
+ mMainPane = pane;
+ mLogView = new LogView();
+ mSearchModel = new SearchModel();
+ mSearchModel.matchOffsetProperty().addListener( ( c, o, n ) -> {
+ final var editor = getActiveTextEditor();
+
+ // Clear highlighted areas before highlighting a new region.
+ if( o != null ) {
+ editor.unstylize( STYLE_SEARCH );
+ }
+
+ if( n != null ) {
+ editor.moveTo( n.getStart() );
+ editor.stylize( n, STYLE_SEARCH );
+ }
+ } );
+
+ // When the active text editor changes ...
+ mMainPane.textEditorProperty().addListener(
+ ( c, o, n ) -> {
+ // ... update the haystack.
+ mSearchModel.search( getActiveTextEditor().getText() );
+
+ // ... update the status bar with the current caret position.
+ if( n != null ) {
+ final var w = getWorkspace();
+ final var recentDoc = w.fileProperty( KEY_UI_RECENT_DOCUMENT );
+
+ // ... preserve the most recent document.
+ recentDoc.setValue( n.getFile() );
+ CaretMovedEvent.fire( n.getCaret() );
+ }
+ }
+ );
+ }
+
+ public void file_new() {
+ getMainPane().newTextEditor();
+ }
+
+ public void file_open() {
+ pickFiles( FILE_OPEN_MULTIPLE ).ifPresent( l -> getMainPane().open( l ) );
+ }
+
+ public void file_close() {
+ getMainPane().close();
+ }
+
+ public void file_close_all() {
+ getMainPane().closeAll();
+ }
+
+ public void file_save() {
+ getMainPane().save();
+ }
+
+ public void file_save_as() {
+ pickFiles( FILE_SAVE_AS ).ifPresent( l -> getMainPane().saveAs( l ) );
+ }
+
+ public void file_save_all() {
+ getMainPane().saveAll();
+ }
+
+ /**
+ * Converts the actively edited file in the given file format.
+ *
+ * @param format The destination file format.
+ */
+ private void file_export( final ExportFormat format ) {
+ file_export( format, false );
+ }
+
+ /**
+ * Converts one or more files into the given file format. If {@code dir}
+ * is set to true, this will first append all files in the same directory
+ * as the actively edited file.
+ *
+ * @param format The destination file format.
+ * @param dir Export all files in the actively edited file's directory.
+ */
+ private void file_export( final ExportFormat format, final boolean dir ) {
+ final var editor = getMainPane().getTextEditor();
+ final var exported = getWorkspace().fileProperty( KEY_UI_RECENT_EXPORT );
+ final var exportParent = exported.get().toPath().getParent();
+ final var editorParent = editor.getPath().getParent();
+ final var userHomeParent = USER_DIRECTORY.toPath();
+ final var exportPath = exportParent != null
+ ? exportParent
+ : editorParent != null
+ ? editorParent
+ : userHomeParent;
+
+ final var filename = format.toExportFilename( editor.getPath() );
+ final var selected = PDF_DEFAULT
+ .getName()
+ .equals( exported.get().getName() );
+ final var selection = pickFile(
+ selected
+ ? filename
+ : exported.get(),
+ exportPath,
+ FILE_EXPORT
+ );
+
+ selection.ifPresent( files -> file_export( editor, format, files, dir ) );
+ }
+
+ private void file_export(
+ final TextEditor editor,
+ final ExportFormat format,
+ final List<File> files,
+ final boolean dir ) {
+ editor.save();
+ final var main = getMainPane();
+ final var exported = getWorkspace().fileProperty( KEY_UI_RECENT_EXPORT );
+
+ final var sourceFile = files.get( 0 );
+ final var sourcePath = sourceFile.toPath();
+ final var document = dir ? append( editor ) : editor.getText();
+ final var context = main.createProcessorContext( sourcePath, format );
+
+ final var service = new Service<Path>() {
+ @Override
+ protected Task<Path> createTask() {
+ final var task = new Task<Path>() {
+ @Override
+ protected Path call() throws Exception {
+ final var chain = createProcessors( context );
+ final var export = chain.apply( document );
+
+ // Processors can export binary files. In such cases, processors
+ // return null to prevent further processing.
+ return export == null ? null : writeString( sourcePath, export );
+ }
+ };
+
+ task.setOnSucceeded(
+ e -> {
+ // Remember the exported file name for next time.
+ exported.setValue( sourceFile );
+
+ final var result = task.getValue();
+
+ // Binary formats must notify users of success independently.
+ if( result != null ) {
+ clue( "Main.status.export.success", result );
+ }
+ }
+ );
+
+ task.setOnFailed( e -> {
+ final var ex = task.getException();
+ clue( ex );
+
+ if( ex instanceof TypeNotPresentException ) {
+ fireExportFailedEvent();
+ }
+ } );
+
+ return task;
+ }
+ };
+
+ mTypesetService = service;
+ typeset( service );
+ }
+
+ /**
+ * @param dir {@code true} means to export all files in the active file
+ * editor's directory; {@code false} means to export only the
+ * actively edited file.
+ */
+ private void file_export_pdf( final boolean dir ) {
+ final var workspace = getWorkspace();
+ final var themes = workspace.getFile(
+ KEY_TYPESET_CONTEXT_THEMES_PATH
+ );
+ final var theme = workspace.stringProperty(
+ KEY_TYPESET_CONTEXT_THEME_SELECTION
+ );
+ final var chapters = workspace.stringProperty(
+ KEY_TYPESET_CONTEXT_CHAPTERS
+ );
+ final var settings = ExportSettings
+ .builder()
+ .with( ExportSettings.Mutator::setTheme, theme )
+ .with( ExportSettings.Mutator::setChapters, chapters )
+ .build();
+
+ // Don't re-validate the typesetter installation each time. If the
+ // user mucks up the typesetter installation, it'll get caught the
+ // next time the application is started. Don't use |= because it
+ // won't short-circuit.
+ mCanTypeset = mCanTypeset || Typesetter.canRun();
+
+ if( mCanTypeset ) {
+ // If the typesetter is installed, allow the user to select a theme. If
+ // the themes aren't installed, a status message will appear.
+ if( ExportDialog.choose( getWindow(), themes, settings, dir ) ) {
+ file_export( APPLICATION_PDF, dir );
+ }
+ }
+ else {
+ fireExportFailedEvent();
+ }
+ }
+
+ public void file_export_pdf() {
+ file_export_pdf( false );
+ }
+
+ public void file_export_pdf_dir() {
+ file_export_pdf( true );
+ }
+
+ public void file_export_html_dir() {
+ file_export( XHTML_TEX, true );
+ }
+
+ public void file_export_repeat() {
+ typeset( mTypesetService );
+ }
+
+ public void file_export_html_svg() {
+ file_export( HTML_TEX_SVG );
+ }
+
+ public void file_export_html_tex() {
+ file_export( HTML_TEX_DELIMITED );
+ }
+
+ public void file_export_xhtml_tex() {
+ file_export( XHTML_TEX );
+ }
+
+ private void fireExportFailedEvent() {
+ runLater( ExportFailedEvent::fire );
+ }
+
+ public void file_exit() {
+ final var window = getWindow();
+ fireEvent( window, new WindowEvent( window, WINDOW_CLOSE_REQUEST ) );
+ }
+
+ public void edit_undo() {
+ getActiveTextEditor().undo();
+ }
+
+ public void edit_redo() {
+ getActiveTextEditor().redo();
+ }
+
+ public void edit_cut() {
+ getActiveTextEditor().cut();
+ }
+
+ public void edit_copy() {
+ getActiveTextEditor().copy();
+ }
+
+ public void edit_paste() {
+ getActiveTextEditor().paste();
+ }
+
+ public void edit_select_all() {
+ getActiveTextEditor().selectAll();
+ }
+
+ public void edit_find() {
+ final var nodes = getMainScene().getStatusBar().getLeftItems();
+
+ if( nodes.isEmpty() ) {
+ final var searchBar = new SearchBar();
+
+ searchBar.matchIndexProperty().bind( mSearchModel.matchIndexProperty() );
+ searchBar.matchCountProperty().bind( mSearchModel.matchCountProperty() );
+
+ searchBar.setOnCancelAction( event -> {
+ final var editor = getActiveTextEditor();
+ nodes.remove( searchBar );
+ editor.unstylize( STYLE_SEARCH );
+ editor.getNode().requestFocus();
+ } );
+
+ searchBar.addInputListener( ( c, o, n ) -> {
+ if( n != null && !n.isEmpty() ) {
+ mSearchModel.search( n, getActiveTextEditor().getText() );
+ }
+ } );
+
+ searchBar.setOnNextAction( event -> edit_find_next() );
+ searchBar.setOnPrevAction( event -> edit_find_prev() );
+
+ nodes.add( searchBar );
+ searchBar.requestFocus();
+ }
+ }
+
+ public void edit_find_next() {
+ mSearchModel.advance();
+ }
+
+ public void edit_find_prev() {
+ mSearchModel.retreat();
+ }
+
+ public void edit_preferences() {
+ try {
+ new PreferencesController( getWorkspace() ).show();
+ } catch( final Exception ex ) {
+ clue( ex );
+ }
+ }
+
+ public void format_bold() {
+ getActiveTextEditor().bold();
+ }
+
+ public void format_italic() {
+ getActiveTextEditor().italic();
+ }
+
+ public void format_monospace() {
+ getActiveTextEditor().monospace();
+ }
+
+ public void format_superscript() {
+ getActiveTextEditor().superscript();
+ }
+
+ public void format_subscript() {
+ getActiveTextEditor().subscript();
+ }
+
+ public void format_strikethrough() {
+ getActiveTextEditor().strikethrough();
+ }
+
+ public void insert_blockquote() {
+ getActiveTextEditor().blockquote();
+ }
+
+ public void insert_code() {
+ getActiveTextEditor().code();
+ }
+
+ public void insert_fenced_code_block() {
+ getActiveTextEditor().fencedCodeBlock();
+ }
+
+ public void insert_link() {
+ insertObject( createLinkDialog() );
+ }
+
+ public void insert_image() {
+ insertObject( createImageDialog() );
+ }
+
+ private void insertObject( final Dialog<String> dialog ) {
+ final var textArea = getActiveTextEditor().getTextArea();
+ dialog.showAndWait().ifPresent( textArea::replaceSelection );
+ }
+
+ private Dialog<String> createLinkDialog() {
+ return new LinkDialog( getWindow(), createHyperlinkModel() );
+ }
+
+ private Dialog<String> createImageDialog() {
+ final var path = getActiveTextEditor().getPath();
+ final var parentDir = path.getParent();
+ return new ImageDialog( getWindow(), parentDir );
+ }
+
+ /**
+ * Returns one of: selected text, word under cursor, or parsed hyperlink from
+ * the Markdown AST.
+ *
+ * @return An instance containing the link URL and display text.
+ */
+ private HyperlinkModel createHyperlinkModel() {
+ final var context = getMainPane().createProcessorContext();
+ final var editor = getActiveTextEditor();
+ final var textArea = editor.getTextArea();
+ final var selectedText = textArea.getSelectedText();
+
+ // Convert current paragraph to Markdown nodes.
+ final var mp = MarkdownProcessor.create( context );
+ final var p = textArea.getCurrentParagraph();
+ final var paragraph = textArea.getText( p );
+ final var node = mp.toNode( paragraph );
+ final var visitor = new LinkVisitor( textArea.getCaretColumn() );
+ final var link = visitor.process( node );
+
+ if( link != null ) {
+ textArea.selectRange( p, link.getStartOffset(), p, link.getEndOffset() );
+ }
+
+ return createHyperlinkModel( link, selectedText );
+ }
+
+ private HyperlinkModel createHyperlinkModel(
+ final Link link, final String selection ) {
+
+ return link == null
+ ? new HyperlinkModel( selection, "https://localhost" )
+ : new HyperlinkModel( link );
+ }
+
+ public void insert_heading_1() {
+ insert_heading( 1 );
+ }
+
+ public void insert_heading_2() {
+ insert_heading( 2 );
+ }
+
+ public void insert_heading_3() {
+ insert_heading( 3 );
+ }
+
+ private void insert_heading( final int level ) {
+ getActiveTextEditor().heading( level );
+ }
+
+ public void insert_unordered_list() {
+ getActiveTextEditor().unorderedList();
+ }
+
+ public void insert_ordered_list() {
+ getActiveTextEditor().orderedList();
+ }
+
+ public void insert_horizontal_rule() {
+ getActiveTextEditor().horizontalRule();
+ }
+
+ public void definition_create() {
+ getActiveTextDefinition().createDefinition();
+ }
+
+ public void definition_rename() {
+ getActiveTextDefinition().renameDefinition();
+ }
+
+ public void definition_delete() {
+ getActiveTextDefinition().deleteDefinitions();
+ }
+
+ public void definition_autoinsert() {
+ getMainPane().autoinsert();
+ }
+
+ public void view_refresh() {
+ getMainPane().viewRefresh();
+ }
+
+ public void view_preview() {
+ getMainPane().viewPreview();
+ }
+
+ public void view_outline() {
+ getMainPane().viewOutline();
+ }
+
+ public void view_files() { getMainPane().viewFiles(); }
+
+ public void view_statistics() {
+ getMainPane().viewStatistics();
+ }
+
+ public void view_menubar() {
+ getMainScene().toggleMenuBar();
+ }
+
+ public void view_toolbar() {
+ getMainScene().toggleToolBar();
+ }
+
+ public void view_statusbar() {
+ getMainScene().toggleStatusBar();
+ }
+
+ public void view_log() {
+ mLogView.view();
+ }
+
+ public void help_about() {
+ final var alert = new Alert( INFORMATION );
+ final var prefix = "Dialog.about.";
+ alert.setTitle( get( prefix + "title", APP_TITLE ) );
+ alert.setHeaderText( get( prefix + "header", APP_TITLE ) );
+ alert.setContentText( get( prefix + "content", APP_YEAR, APP_VERSION ) );
+ alert.setGraphic( ICON_DIALOG_NODE );
+ alert.initOwner( getWindow() );
+ alert.showAndWait();
+ }
+
+ private <T> void typeset( final Service<T> service ) {
+ synchronized( mMutex ) {
+ if( service != null && !service.isRunning() ) {
+ service.reset();
+ service.start();
+ }
+ }
+ }
+
+ /**
+ * Concatenates all the files in the same directory as the given file into
+ * a string. The extension is determined by the given file name pattern; the
+ * order files are concatenated is based on their numeric sort order (this
+ * avoids lexicographic sorting).
+ * <p>
+ * If the parent path to the file being edited in the text editor cannot
+ * be found then this will return the editor's text, without iterating through
+ * the parent directory. (Should never happen, but who knows?)
+ * </p>
+ * <p>
+ * New lines are automatically appended to separate each file.
+ * </p>
+ *
+ * @param editor The text editor containing
+ * @return All files in the same directory as the file being edited
+ * concatenated into a single string.
+ */
+ private String append( final TextEditor editor ) {
+ final var pattern = editor.getPath();
+ final var parent = pattern.getParent();
+
+ // Short-circuit because nothing else can be done.
+ if( parent == null ) {
+ clue( "Main.status.export.concat.parent", pattern );
+ return editor.getText();
+ }
+
+ final var filename = SysFile.getFileName( pattern );
final var extension = getExtension( filename );
src/main/java/com/keenwrite/ui/dialogs/ExportDialog.java
import com.keenwrite.events.ExportFailedEvent;
+import com.keenwrite.io.SysFile;
import com.keenwrite.util.Diacritics;
import com.keenwrite.util.FileWalker;
*/
public boolean matches( final String themeDir ) {
- final var path = path().getFileName().toString();
+ final var f = SysFile.getFileName( path() );
- return path.equalsIgnoreCase( Diacritics.remove( themeDir ) );
+ return f.equalsIgnoreCase( Diacritics.remove( themeDir ) );
}
@Override
public int compareTo( final Theme o ) {
+ assert o != null;
+
return name().compareTo( o.name() );
}
final var theme = mComboBox.getSelectionModel().getSelectedItem();
final var path = theme.path();
- final var filename = path.getFileName().toString();
+ final var filename = SysFile.getFileName( path.getFileName() );
+
mSettings.themeProperty().setValue( filename );
src/main/java/com/keenwrite/ui/explorer/FilesView.java
import com.keenwrite.events.FileOpenEvent;
+import com.keenwrite.io.SysFile;
import com.keenwrite.ui.controls.BrowseButton;
import javafx.beans.property.*;
import java.util.List;
import java.util.Locale;
-import java.util.Objects;
import java.util.Optional;
@Override
- public void setInitialFilename( final File file ) {
- }
+ public void setInitialFilename( final File file ) { }
@Override
}
- for( final var f : Objects.requireNonNull( directory.list() ) ) {
- if( !f.startsWith( "." ) ) {
- mItems.add( pathEntry( Paths.get( directory.toString(), f ) ) );
+ final var list = directory.list();
+
+ if( list != null ) {
+ for( final var f : list ) {
+ if( !f.startsWith( "." ) ) {
+ mItems.add( pathEntry( Paths.get( directory.toString(), f ) ) );
+ }
}
}
this(
path,
- path.getFileName().toString(),
+ SysFile.getFileName( path ),
size( path ),
ofEpochMilli( path.toFile().lastModified() )
src/main/java/com/keenwrite/ui/fonts/IconFactory.java
import com.keenwrite.io.MediaType;
import com.keenwrite.io.MediaTypeExtension;
+import com.keenwrite.io.SysFile;
import javafx.scene.Node;
import javafx.scene.image.Image;
public static ImageView createFileIcon( final Path path ) throws IOException {
final var attrs = readAttributes( path, BasicFileAttributes.class );
- final var filename = path.getFileName().toString();
+ final var filename = SysFile.getFileName( path );
String extension;
* create an icon for display.
*/
- private IconFactory() {}
+ private IconFactory() { }
}
src/main/java/com/keenwrite/util/AlphanumComparator.java
package com.keenwrite.util;
+import java.io.Serializable;
import java.util.Comparator;
* </p>
*/
-public final class AlphanumComparator<T> implements Comparator<T> {
+public final class AlphanumComparator<T> implements
+ Comparator<T>, Serializable {
+
/**
* Returns a chunk of text that is continuous with respect to digits or
src/main/java/com/keenwrite/util/CyclicIterator.java
package com.keenwrite.util;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.NoSuchElementException;
+import java.util.*;
/**
* @param list The list to cycle through indefinitely.
*/
- public CyclicIterator( final List<T> list ) {
- mList = list;
+ public CyclicIterator( final Collection<T> list ) {
+ mList = new ArrayList<>( list );
}
src/main/java/com/keenwrite/util/DataTypeConverter.java
public static byte[] hash( final String s ) throws NoSuchAlgorithmException {
final var digest = MessageDigest.getInstance( "SHA-1" );
- return digest.digest( s.getBytes() );
+ return digest.digest( s.getBytes( UTF_8 ) );
}
}
src/test/java/com/keenwrite/io/MediaTypeTest.java
assertEquals( v, response.getMediaType() );
} catch( final Exception e ) {
- fail();
+ throw new RuntimeException( e );
}
} );
src/test/java/com/keenwrite/io/downloads/DownloadManagerTest.java
assertFalse( future.isDone() );
assertTrue( complete.get() < 100 );
+ System.out.println( "tx.get: " + transferred.get() );
assertTrue( transferred.get() > 100_000 );
Delta 744 lines added, 680 lines removed, 64-line increase