Dave Jarvis' Repositories

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

Moved embedded startup script into user preference.

Authordjarvis <email>
Date2017-01-22 19:39:44 GMT-0800
Commite27db649c236db5201dcd658d4b40dc1be4018e7
Parent607cfad
build.gradle
compile 'com.googlecode.juniversalchardet:juniversalchardet:1.0.3'
compile 'org.apache.commons:commons-configuration2:2.1'
- compile files('libs/renjin-script-engine-0.8.2309-jar-with-dependencies.jar')
+ compile files('libs/renjin-script-engine-0.8.2320-jar-with-dependencies.jar')
}
libs/renjin-script-engine-0.8.2309-jar-with-dependencies.jar
Binary files differ
libs/renjin-script-engine-0.8.2320-jar-with-dependencies.jar
Binary files differ
src/main/java/com/scrivenvar/Constants.java
}
- private static int get( final String key, int defaultValue ) {
+ private static int get( final String key, final int defaultValue ) {
return SETTINGS.getSetting( key, defaultValue );
}
public static final String FILE_LOGO_256 = get( "file.logo.256" );
public static final String FILE_LOGO_512 = get( "file.logo.512" );
-
- public static final String FILE_R_STARTUP = get( "file.r.startup" );
public static final String CARET_POSITION_BASE = get( "caret.token.base" );
public static final String CARET_POSITION_MD = get( "caret.token.markdown" );
public static final String CARET_POSITION_HTML = get( "caret.token.html" );
public static final String PREFS_ROOT = get( "preferences.root" );
public static final String PREFS_STATE = get( "preferences.root.state" );
public static final String PREFS_OPTIONS = get( "preferences.root.options" );
- public static final String PREFS_DEFINITION_SOURCE = get( "preferences.root.definitionSource" );
// Refer to filename extension settings in the configuration file. Do not
public static final String STATUS_BAR_LINE = "Main.statusbar.line";
// "OK" text
- public static final String STATUS_BAR_DEFAULT = Messages.get( "Main.statusbar.state.default" );
+ public static final String STATUS_BAR_DEFAULT = get( "Main.statusbar.state.default" );
public static final String STATUS_PARSE_ERROR = "Main.statusbar.parse.error";
+
+ // Persistent storage settings.
+
+ /**
+ * Location of the definition source file.
+ */
+ public static final String PERSIST_DEFINITION_SOURCE = "definitionSource";
+
+ /**
+ * Content of the R startup script.
+ */
+ public static final String PERSIST_R_STARTUP = "rStartup";
}
src/main/java/com/scrivenvar/FileEditorTabPane.java
import org.fxmisc.wellbehaved.event.EventPattern;
import org.fxmisc.wellbehaved.event.InputMap;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
/**
src/main/java/com/scrivenvar/Main.java
import static com.scrivenvar.Constants.*;
+import static com.scrivenvar.Messages.get;
import com.scrivenvar.preferences.FilePreferencesFactory;
import com.scrivenvar.service.Options;
import javafx.scene.image.Image;
import javafx.stage.Stage;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
+import static com.scrivenvar.Messages.get;
/**
private String getApplicationTitle() {
- return Messages.get( "Main.title" );
+ return get( "Main.title" );
}
src/main/java/com/scrivenvar/MainWindow.java
import static com.scrivenvar.Messages.get;
import com.scrivenvar.definition.*;
-import com.scrivenvar.editors.EditorPane;
-import com.scrivenvar.editors.VariableNameInjector;
-import com.scrivenvar.editors.markdown.MarkdownEditorPane;
-import com.scrivenvar.predicates.files.FileTypePredicate;
-import com.scrivenvar.preview.HTMLPreviewPane;
-import com.scrivenvar.processors.Processor;
-import com.scrivenvar.processors.ProcessorFactory;
-import com.scrivenvar.service.Options;
-import com.scrivenvar.service.Settings;
-import com.scrivenvar.service.Snitch;
-import com.scrivenvar.service.events.Notifier;
-import com.scrivenvar.util.Action;
-import com.scrivenvar.util.ActionUtils;
-import static com.scrivenvar.util.StageState.*;
-import static de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon.*;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Observable;
-import java.util.Observer;
-import java.util.Optional;
-import java.util.function.Function;
-import java.util.prefs.Preferences;
-import javafx.application.Platform;
-import javafx.beans.binding.Bindings;
-import javafx.beans.binding.BooleanBinding;
-import javafx.beans.property.BooleanProperty;
-import javafx.beans.property.SimpleBooleanProperty;
-import javafx.beans.value.ObservableBooleanValue;
-import javafx.beans.value.ObservableValue;
-import javafx.collections.ListChangeListener.Change;
-import javafx.collections.ObservableList;
-import static javafx.event.Event.fireEvent;
-import javafx.geometry.Insets;
-import javafx.geometry.Pos;
-import javafx.scene.Node;
-import javafx.scene.Scene;
-import javafx.scene.control.Alert;
-import javafx.scene.control.Alert.AlertType;
-import javafx.scene.control.ButtonBar.ButtonData;
-import javafx.scene.control.ButtonType;
-import javafx.scene.control.Dialog;
-import javafx.scene.control.Menu;
-import javafx.scene.control.MenuBar;
-import javafx.scene.control.SplitPane;
-import javafx.scene.control.Tab;
-import javafx.scene.control.TextArea;
-import javafx.scene.control.TextField;
-import javafx.scene.control.ToolBar;
-import javafx.scene.control.TreeView;
-import javafx.scene.image.Image;
-import javafx.scene.image.ImageView;
-import static javafx.scene.input.KeyCode.ESCAPE;
-import javafx.scene.input.KeyEvent;
-import static javafx.scene.input.KeyEvent.CHAR_UNDEFINED;
-import static javafx.scene.input.KeyEvent.KEY_PRESSED;
-import javafx.scene.layout.BorderPane;
-import javafx.scene.layout.GridPane;
-import javafx.scene.layout.VBox;
-import javafx.scene.text.Text;
-import javafx.stage.Window;
-import javafx.stage.WindowEvent;
-import static javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST;
-import org.controlsfx.control.StatusBar;
-import org.fxmisc.richtext.model.TwoDimensional.Position;
-
-/**
- * Main window containing a tab pane in the center for file editors.
- *
- * @author Karl Tauber and White Magic Software, Ltd.
- */
-public class MainWindow implements Observer {
-
- private final Options options = Services.load( Options.class );
- private final Settings settings = Services.load( Settings.class );
- private final Snitch snitch = Services.load( Snitch.class );
- private final Notifier notifier = Services.load( Notifier.class );
-
- private Scene scene;
- private MenuBar menuBar;
- private StatusBar statusBar;
- private Text lineNumberText;
- private TextField findTextField;
-
- private DefinitionSource definitionSource;
- private DefinitionPane definitionPane;
- private FileEditorTabPane fileEditorPane;
- private HTMLPreviewPane previewPane;
-
- /**
- * Prevent re-instantiation processing classes.
- */
- private Map<FileEditorTab, Processor<String>> processors;
-
- public MainWindow() {
- initLayout();
- initFindInput();
- initSnitch();
- initDefinitionListener();
- initTabAddedListener();
- initTabChangedListener();
- initPreferences();
- }
-
- public Settings getSettings() {
- return settings;
- }
-
- /**
- * Watch for changes to external files. In particular, this awaits
- * modifications to any XSL files associated with XML files being edited. When
- * an XSL file is modified (external to the application), the snitch's ears
- * perk up and the file is reloaded. This keeps the XSL transformation up to
- * date with what's on the file system.
- */
- private void initSnitch() {
- getSnitch().addObserver( this );
- }
-
- /**
- * Initialize the find input text field to listen on F3, ENTER, and ESCAPE key
- * presses.
- */
- private void initFindInput() {
- final TextField input = getFindTextField();
-
- input.setOnKeyPressed( (KeyEvent event) -> {
- switch( event.getCode() ) {
- case F3:
- case ENTER:
- findNext();
- break;
- case F:
- if( !event.isControlDown() ) {
- break;
- }
- case ESCAPE:
- getStatusBar().setGraphic( null );
- getActiveFileEditor().getEditorPane().requestFocus();
- break;
- }
- } );
-
- // Remove when the input field loses focus.
- input.focusedProperty().addListener(
- (
- final ObservableValue<? extends Boolean> focused,
- final Boolean oFocus,
- final Boolean nFocus) -> {
- if( !nFocus ) {
- getStatusBar().setGraphic( null );
- }
- }
- );
- }
-
- /**
- * Listen for file editor tab pane to receive an open definition source event.
- */
- private void initDefinitionListener() {
- getFileEditorPane().onOpenDefinitionFileProperty().addListener(
- (ObservableValue<? extends Path> definitionFile,
- final Path oldPath, final Path newPath) -> {
- openDefinition( newPath );
-
- // Indirectly refresh the resolved map.
- setProcessors( null );
-
- updateDefinitionPane();
-
- try {
- getSnitch().ignore( oldPath );
- getSnitch().listen( newPath );
- } catch( final IOException ex ) {
- error( ex );
- }
-
- // Will create new processors and therefore a new resolved map.
- refreshSelectedTab( getActiveFileEditor() );
- }
- );
- }
-
- /**
- * When tabs are added, hook the various change listeners onto the new tab so
- * that the preview pane refreshes as necessary.
- */
- private void initTabAddedListener() {
- final FileEditorTabPane editorPane = getFileEditorPane();
-
- // Make sure the text processor kicks off when new files are opened.
- final ObservableList<Tab> tabs = editorPane.getTabs();
-
- // Update the preview pane on tab changes.
- tabs.addListener(
- (final Change<? extends Tab> change) -> {
- while( change.next() ) {
- if( change.wasAdded() ) {
- // Multiple tabs can be added simultaneously.
- for( final Tab newTab : change.getAddedSubList() ) {
- final FileEditorTab tab = (FileEditorTab)newTab;
-
- initTextChangeListener( tab );
- initCaretParagraphListener( tab );
- initVariableNameInjector( tab );
-// initSyntaxListener( tab );
- }
- }
- }
- }
- );
- }
-
- /**
- * Reloads the preferences from the previous load.
- */
- private void initPreferences() {
- restoreDefinitionSource();
- getFileEditorPane().restorePreferences();
- updateDefinitionPane();
- }
-
- /**
- * Listen for new tab selection events.
- */
- private void initTabChangedListener() {
- final FileEditorTabPane editorPane = getFileEditorPane();
-
- // Update the preview pane changing tabs.
- editorPane.addTabSelectionListener(
- (ObservableValue<? extends Tab> tabPane,
- final Tab oldTab, final Tab newTab) -> {
-
- // If there was no old tab, then this is a first time load, which
- // can be ignored.
- if( oldTab != null ) {
- if( newTab == null ) {
- closeRemainingTab();
- }
- else {
- // Update the preview with the edited text.
- refreshSelectedTab( (FileEditorTab)newTab );
- }
- }
- }
- );
- }
-
- private void initTextChangeListener( final FileEditorTab tab ) {
- tab.addTextChangeListener(
- (ObservableValue<? extends String> editor,
- final String oldValue, final String newValue) -> {
- refreshSelectedTab( tab );
- }
- );
- }
-
- private void initCaretParagraphListener( final FileEditorTab tab ) {
- tab.addCaretParagraphListener(
- (ObservableValue<? extends Integer> editor,
- final Integer oldValue, final Integer newValue) -> {
- refreshSelectedTab( tab );
- }
- );
- }
-
- private void initVariableNameInjector( final FileEditorTab tab ) {
- VariableNameInjector.listen( tab, getDefinitionPane() );
- }
-
- /**
- * Called whenever the preview pane becomes out of sync with the file editor
- * tab. This can be called when the text changes, the caret paragraph changes,
- * or the file tab changes.
- *
- * @param tab The file editor tab that has been changed in some fashion.
- */
- private void refreshSelectedTab( final FileEditorTab tab ) {
- if( tab.isFileOpen() ) {
- getPreviewPane().setPath( tab.getPath() );
-
- // TODO: https://github.com/DaveJarvis/scrivenvar/issues/29
- final Position p = tab.getCaretOffset();
- getLineNumberText().setText(
- get( STATUS_BAR_LINE,
- p.getMajor() + 1,
- p.getMinor() + 1,
- tab.getCaretPosition() + 1
- )
- );
-
- Processor<String> processor = getProcessors().get( tab );
-
- if( processor == null ) {
- processor = createProcessor( tab );
- getProcessors().put( tab, processor );
- }
-
- try {
- getNotifier().clear();
- processor.processChain( tab.getEditorText() );
- } catch( final Exception ex ) {
- error( ex );
- }
- }
- }
-
- /**
- * Used to find text in the active file editor window.
- */
- private void find() {
- final TextField input = getFindTextField();
- getStatusBar().setGraphic( input );
- input.requestFocus();
- }
-
- public void findNext() {
- getActiveFileEditor().searchNext( getFindTextField().getText() );
- }
-
- /**
- * Returns the variable map of interpolated definitions.
- *
- * @return A map to help dereference variables.
- */
- private Map<String, String> getResolvedMap() {
- return getDefinitionSource().getResolvedMap();
- }
-
- /**
- * Returns the root node for the hierarchical definition source.
- *
- * @return Data to display in the definition pane.
- */
- private TreeView<String> getTreeView() {
- try {
- return getDefinitionSource().asTreeView();
- } catch( Exception e ) {
- error( e );
- }
-
- // Slightly redundant as getDefinitionSource() might have returned an
- // empty definition source.
- return (new EmptyDefinitionSource()).asTreeView();
- }
-
- /**
- * Called when a definition source is opened.
- *
- * @param path Path to the definition source that was opened.
- */
- private void openDefinition( final Path path ) {
- try {
- final DefinitionSource ds = createDefinitionSource( path.toString() );
- setDefinitionSource( ds );
- storeDefinitionSource();
- updateDefinitionPane();
- } catch( final Exception e ) {
- error( e );
- }
- }
-
- private void updateDefinitionPane() {
- getDefinitionPane().setRoot( getDefinitionSource().asTreeView() );
- }
-
- private void restoreDefinitionSource() {
- final Preferences preferences = getPreferences();
- final String source = preferences.get( PREFS_DEFINITION_SOURCE, null );
-
- // If there's no definition source set, don't try to load it.
- if( source != null ) {
- setDefinitionSource( createDefinitionSource( source ) );
- }
- }
-
- private void storeDefinitionSource() {
- final Preferences preferences = getPreferences();
- final DefinitionSource ds = getDefinitionSource();
-
- preferences.put( PREFS_DEFINITION_SOURCE, ds.toString() );
- }
-
- /**
- * Called when the last open tab is closed to clear the preview pane.
- */
- private void closeRemainingTab() {
- getPreviewPane().clear();
- }
-
- /**
- * Called when an exception occurs that warrants the user's attention.
- *
- * @param e The exception with a message that the user should know about.
- */
- private void error( final Exception e ) {
- getNotifier().notify( e );
- }
-
- //---- File actions -------------------------------------------------------
- /**
- * Called when an observable instance has changed. This is called by both the
- * snitch service and the notify service. The snitch service can be called for
- * different file types, including definition sources.
- *
- * @param observable The observed instance.
- * @param value The noteworthy item.
- */
- @Override
- public void update( final Observable observable, final Object value ) {
- if( value != null ) {
- if( observable instanceof Snitch && value instanceof Path ) {
- final Path path = (Path)value;
- final FileTypePredicate predicate
- = new FileTypePredicate( GLOB_DEFINITION_EXTENSIONS );
-
- // Reload definitions.
- if( predicate.test( path.toFile() ) ) {
- updateDefinitionSource( path );
- }
-
- updateSelectedTab();
- }
- else if( observable instanceof Notifier && value instanceof String ) {
- updateStatusBar( (String)value );
- }
- }
- }
-
- /**
- * Updates the status bar to show the given message.
- *
- * @param s The message to show in the status bar.
- */
- private void updateStatusBar( final String s ) {
- Platform.runLater(
- () -> {
- final int index = s.indexOf( '\n' );
- final String message = s.substring( 0, index > 0 ? index : s.length() );
-
- getStatusBar().setText( message );
- }
- );
- }
-
- /**
- * Called when a file has been modified.
- *
- * @param file Path to the modified file.
- */
- private void updateSelectedTab() {
- Platform.runLater(
- () -> {
- // Brute-force XSLT file reload by re-instantiating all processors.
- resetProcessors();
- refreshSelectedTab( getActiveFileEditor() );
- }
- );
- }
-
- /**
- * Reloads the definition source from the given path.
- *
- * @param path The path containing new definition information.
- */
- private void updateDefinitionSource( final Path path ) {
- Platform.runLater(
- () -> {
- openDefinition( path );
- }
- );
- }
-
- /**
- * After resetting the processors, they will refresh anew to be up-to-date
- * with the files (text and definition) currently loaded into the editor.
- */
- private void resetProcessors() {
- getProcessors().clear();
- }
-
- //---- File actions -------------------------------------------------------
- private void fileNew() {
- getFileEditorPane().newEditor();
- }
-
- private void fileOpen() {
- getFileEditorPane().openFileDialog();
- }
-
- private void fileClose() {
- getFileEditorPane().closeEditor( getActiveFileEditor(), true );
- }
-
- private void fileCloseAll() {
- getFileEditorPane().closeAllEditors();
- }
-
- private void fileSave() {
- getFileEditorPane().saveEditor( getActiveFileEditor() );
- }
-
- private void fileSaveAll() {
- getFileEditorPane().saveAllEditors();
- }
-
- private void fileExit() {
- final Window window = getWindow();
- fireEvent( window, new WindowEvent( window, WINDOW_CLOSE_REQUEST ) );
- }
-
- //---- Help actions -------------------------------------------------------
- private void helpAbout() {
- Alert alert = new Alert( AlertType.INFORMATION );
- alert.setTitle( get( "Dialog.about.title" ) );
- alert.setHeaderText( get( "Dialog.about.header" ) );
- alert.setContentText( get( "Dialog.about.content" ) );
- alert.setGraphic( new ImageView( new Image( FILE_LOGO_32 ) ) );
- alert.initOwner( getWindow() );
-
- alert.showAndWait();
- }
-
- //---- Convenience accessors ----------------------------------------------
- private float getFloat( final String key, final float defaultValue ) {
- return getPreferences().getFloat( key, defaultValue );
- }
-
- private Preferences getPreferences() {
- return getOptions().getState();
- }
-
- private TextField createFindTextField() {
- return new TextField();
- }
-
- private void toolsScript() {
- try {
- // Create a custom dialog.
- Dialog<String> dialog = new Dialog<>();
- dialog.setTitle( "R Startup Script" );
-
- final String script = getSettings().loadRStartupScript();
-
- final ButtonType saveButton = new ButtonType( "Save", ButtonData.OK_DONE );
- dialog.getDialogPane().getButtonTypes().addAll( saveButton, ButtonType.CANCEL );
-
- GridPane grid = new GridPane();
- grid.setHgap( 10 );
- grid.setVgap( 10 );
- grid.setPadding( new Insets( 20, 100, 10, 10 ) );
-
- final TextArea textArea = new TextArea( script );
- textArea.setEditable( true );
- textArea.setWrapText( true );
-
- grid.add( textArea, 0, 0 );
- dialog.getDialogPane().setContent( grid );
-
- Platform.runLater( () -> textArea.requestFocus() );
-
- dialog.setResultConverter( button -> {
- return (button == saveButton) ? textArea.getText() : "";
- } );
-
- final Optional<String> result = dialog.showAndWait();
-
- result.ifPresent( s -> {
- try {
- getSettings().saveRStartupScript( s );
- } catch( IOException ex ) {
- getNotifier().notify( ex );
- }
- } );
-
- } catch( final IOException ex ) {
- getNotifier().notify( ex );
- }
- }
-
- protected Scene getScene() {
- if( this.scene == null ) {
- this.scene = createScene();
- }
-
- return this.scene;
- }
-
- public Window getWindow() {
- return getScene().getWindow();
- }
-
- private MarkdownEditorPane getActiveEditor() {
- final EditorPane pane = getActiveFileEditor().getEditorPane();
-
- return pane instanceof MarkdownEditorPane ? (MarkdownEditorPane)pane : null;
- }
-
- private FileEditorTab getActiveFileEditor() {
- return getFileEditorPane().getActiveFileEditor();
- }
-
- //---- Member accessors ---------------------------------------------------
- private void setProcessors( final Map<FileEditorTab, Processor<String>> map ) {
- this.processors = map;
- }
-
- private Map<FileEditorTab, Processor<String>> getProcessors() {
- if( this.processors == null ) {
- setProcessors( new HashMap<>() );
- }
-
- return this.processors;
- }
-
- private FileEditorTabPane getFileEditorPane() {
- if( this.fileEditorPane == null ) {
- this.fileEditorPane = createFileEditorPane();
- }
-
- return this.fileEditorPane;
- }
-
- private HTMLPreviewPane getPreviewPane() {
- if( this.previewPane == null ) {
- this.previewPane = createPreviewPane();
- }
-
- return this.previewPane;
- }
-
- private void setDefinitionSource( final DefinitionSource definitionSource ) {
- this.definitionSource = definitionSource;
- }
-
- private DefinitionSource getDefinitionSource() {
- if( this.definitionSource == null ) {
- this.definitionSource = new EmptyDefinitionSource();
- }
-
- return this.definitionSource;
- }
-
- private DefinitionPane getDefinitionPane() {
- if( this.definitionPane == null ) {
- this.definitionPane = createDefinitionPane();
- }
-
- return this.definitionPane;
- }
-
- private Options getOptions() {
- return this.options;
- }
-
- private Snitch getSnitch() {
- return this.snitch;
- }
-
- private Notifier getNotifier() {
- return this.notifier;
- }
-
- public void setMenuBar( final MenuBar menuBar ) {
- this.menuBar = menuBar;
- }
-
- public MenuBar getMenuBar() {
- return this.menuBar;
- }
-
- private Text getLineNumberText() {
- if( this.lineNumberText == null ) {
- this.lineNumberText = createLineNumberText();
- }
-
- return this.lineNumberText;
- }
-
- private synchronized StatusBar getStatusBar() {
- if( this.statusBar == null ) {
- this.statusBar = createStatusBar();
- }
-
- return this.statusBar;
- }
-
- private TextField getFindTextField() {
- if( this.findTextField == null ) {
- this.findTextField = createFindTextField();
- }
-
- return this.findTextField;
- }
-
- //---- Member creators ----------------------------------------------------
- /**
- * Factory to create processors that are suited to different file types.
- *
- * @param tab The tab that is subjected to processing.
- *
- * @return A processor suited to the file type specified by the tab's path.
- */
- private Processor<String> createProcessor( final FileEditorTab tab ) {
- return createProcessorFactory().createProcessor( tab );
- }
-
- private ProcessorFactory createProcessorFactory() {
- return new ProcessorFactory( getPreviewPane(), getResolvedMap() );
- }
-
- private DefinitionSource createDefinitionSource( final String path ) {
- final DefinitionSource ds
- = createDefinitionFactory().createDefinitionSource( path );
-
- if( ds instanceof FileDefinitionSource ) {
- try {
- getSnitch().listen( ((FileDefinitionSource)ds).getPath() );
- } catch( final IOException ex ) {
- error( ex );
- }
- }
-
- return ds;
- }
-
- /**
- * Create an editor pane to hold file editor tabs.
- *
- * @return A new instance, never null.
- */
- private FileEditorTabPane createFileEditorPane() {
- return new FileEditorTabPane();
- }
-
- private HTMLPreviewPane createPreviewPane() {
- return new HTMLPreviewPane();
- }
-
- private DefinitionPane createDefinitionPane() {
- return new DefinitionPane( getTreeView() );
- }
-
- private DefinitionFactory createDefinitionFactory() {
- return new DefinitionFactory();
- }
-
- private StatusBar createStatusBar() {
- return new StatusBar();
- }
-
- private Scene createScene() {
- final SplitPane splitPane = new SplitPane(
- getDefinitionPane().getNode(),
- getFileEditorPane().getNode(),
- getPreviewPane().getNode() );
-
- splitPane.setDividerPositions(
- getFloat( K_PANE_SPLIT_DEFINITION, .10f ),
- getFloat( K_PANE_SPLIT_EDITOR, .45f ),
- getFloat( K_PANE_SPLIT_PREVIEW, .45f ) );
-
- // See: http://broadlyapplicable.blogspot.ca/2015/03/javafx-capture-restorePreferences-splitpane.html
- final BorderPane borderPane = new BorderPane();
- borderPane.setPrefSize( 1024, 800 );
- borderPane.setTop( createMenuBar() );
- borderPane.setBottom( getStatusBar() );
- borderPane.setCenter( splitPane );
-
- final VBox box = new VBox();
- box.setAlignment( Pos.BASELINE_CENTER );
- box.getChildren().add( getLineNumberText() );
- getStatusBar().getRightItems().add( box );
-
- return new Scene( borderPane );
- }
-
- private Text createLineNumberText() {
- return new Text( get( STATUS_BAR_LINE, 1, 1, 1 ) );
- }
-
- private Node createMenuBar() {
- final BooleanBinding activeFileEditorIsNull = getFileEditorPane().activeFileEditorProperty().isNull();
-
- // File actions
- final Action fileNewAction = new Action( get( "Main.menu.file.new" ), "Shortcut+N", FILE_ALT, e -> fileNew() );
- final Action fileOpenAction = new Action( get( "Main.menu.file.open" ), "Shortcut+O", FOLDER_OPEN_ALT, e -> fileOpen() );
- final Action fileCloseAction = new Action( get( "Main.menu.file.close" ), "Shortcut+W", null, e -> fileClose(), activeFileEditorIsNull );
- final Action fileCloseAllAction = new Action( get( "Main.menu.file.close_all" ), null, null, e -> fileCloseAll(), activeFileEditorIsNull );
- final Action fileSaveAction = new Action( get( "Main.menu.file.save" ), "Shortcut+S", FLOPPY_ALT, e -> fileSave(),
- createActiveBooleanProperty( FileEditorTab::modifiedProperty ).not() );
- final Action fileSaveAllAction = new Action( get( "Main.menu.file.save_all" ), "Shortcut+Shift+S", null, e -> fileSaveAll(),
- Bindings.not( getFileEditorPane().anyFileEditorModifiedProperty() ) );
- final Action fileExitAction = new Action( get( "Main.menu.file.exit" ), null, null, e -> fileExit() );
-
- // Edit actions
- final Action editUndoAction = new Action( get( "Main.menu.edit.undo" ), "Shortcut+Z", UNDO,
- e -> getActiveEditor().undo(),
- createActiveBooleanProperty( FileEditorTab::canUndoProperty ).not() );
- final Action editRedoAction = new Action( get( "Main.menu.edit.redo" ), "Shortcut+Y", REPEAT,
- e -> getActiveEditor().redo(),
- createActiveBooleanProperty( FileEditorTab::canRedoProperty ).not() );
- final Action editFindAction = new Action( Messages.get( "Main.menu.edit.find" ), "Ctrl+F", SEARCH,
- e -> find(),
- activeFileEditorIsNull );
- final Action editReplaceAction = new Action( Messages.get( "Main.menu.edit.find.replace" ), "Shortcut+H", RETWEET,
- e -> getActiveEditor().replace(),
- activeFileEditorIsNull );
- final Action editFindNextAction = new Action( Messages.get( "Main.menu.edit.find.next" ), "F3", null,
- e -> findNext(),
- activeFileEditorIsNull );
- final Action editFindPreviousAction = new Action( Messages.get( "Main.menu.edit.find.previous" ), "Shift+F3", null,
- e -> getActiveEditor().findPrevious(),
- activeFileEditorIsNull );
-
- // Insert actions
- final Action insertBoldAction = new Action( get( "Main.menu.insert.bold" ), "Shortcut+B", BOLD,
- e -> getActiveEditor().surroundSelection( "**", "**" ),
- activeFileEditorIsNull );
- final Action insertItalicAction = new Action( get( "Main.menu.insert.italic" ), "Shortcut+I", ITALIC,
- e -> getActiveEditor().surroundSelection( "*", "*" ),
- activeFileEditorIsNull );
- final Action insertSuperscriptAction = new Action( get( "Main.menu.insert.superscript" ), "Shortcut+[", SUPERSCRIPT,
- e -> getActiveEditor().surroundSelection( "^", "^" ),
- activeFileEditorIsNull );
- final Action insertSubscriptAction = new Action( get( "Main.menu.insert.subscript" ), "Shortcut+]", SUBSCRIPT,
- e -> getActiveEditor().surroundSelection( "~", "~" ),
- activeFileEditorIsNull );
- final Action insertStrikethroughAction = new Action( get( "Main.menu.insert.strikethrough" ), "Shortcut+T", STRIKETHROUGH,
- e -> getActiveEditor().surroundSelection( "~~", "~~" ),
- activeFileEditorIsNull );
- final Action insertBlockquoteAction = new Action( get( "Main.menu.insert.blockquote" ), "Ctrl+Q", QUOTE_LEFT, // not Shortcut+Q because of conflict on Mac
- e -> getActiveEditor().surroundSelection( "\n\n> ", "" ),
- activeFileEditorIsNull );
- final Action insertCodeAction = new Action( get( "Main.menu.insert.code" ), "Shortcut+K", CODE,
- e -> getActiveEditor().surroundSelection( "`", "`" ),
- activeFileEditorIsNull );
- final Action insertFencedCodeBlockAction = new Action( get( "Main.menu.insert.fenced_code_block" ), "Shortcut+Shift+K", FILE_CODE_ALT,
- e -> getActiveEditor().surroundSelection( "\n\n```\n", "\n```\n\n", get( "Main.menu.insert.fenced_code_block.prompt" ) ),
- activeFileEditorIsNull );
-
- final Action insertLinkAction = new Action( get( "Main.menu.insert.link" ), "Shortcut+L", LINK,
- e -> getActiveEditor().insertLink(),
- activeFileEditorIsNull );
- final Action insertImageAction = new Action( get( "Main.menu.insert.image" ), "Shortcut+G", PICTURE_ALT,
- e -> getActiveEditor().insertImage(),
- activeFileEditorIsNull );
-
- final Action[] headers = new Action[ 6 ];
-
- // Insert header actions (H1 ... H6)
- for( int i = 1; i <= 6; i++ ) {
- final String hashes = new String( new char[ i ] ).replace( "\0", "#" );
- final String markup = String.format( "%n%n%s ", hashes );
- final String text = get( "Main.menu.insert.header_" + i );
- final String accelerator = "Shortcut+" + i;
- final String prompt = get( "Main.menu.insert.header_" + i + ".prompt" );
-
- headers[ i - 1 ] = new Action( text, accelerator, HEADER,
- e -> getActiveEditor().surroundSelection( markup, "", prompt ),
- activeFileEditorIsNull );
- }
-
- final Action insertUnorderedListAction = new Action(
- get( "Main.menu.insert.unordered_list" ), "Shortcut+U", LIST_UL,
- e -> getActiveEditor().surroundSelection( "\n\n* ", "" ),
- activeFileEditorIsNull );
- final Action insertOrderedListAction = new Action(
- get( "Main.menu.insert.ordered_list" ), "Shortcut+Shift+O", LIST_OL,
- e -> getActiveEditor().surroundSelection( "\n\n1. ", "" ),
- activeFileEditorIsNull );
- final Action insertHorizontalRuleAction = new Action(
- get( "Main.menu.insert.horizontal_rule" ), "Shortcut+H", null,
- e -> getActiveEditor().surroundSelection( "\n\n---\n\n", "" ),
- activeFileEditorIsNull );
-
- // Tools actions
- final Action toolsScriptAction = new Action(
- get( "Main.menu.tools.script" ), null, null, e -> toolsScript() );
-
- // Help actions
- final Action helpAboutAction = new Action(
- get( "Main.menu.help.about" ), null, null, e -> helpAbout() );
-
- //---- MenuBar ----
- final Menu fileMenu = ActionUtils.createMenu( get( "Main.menu.file" ),
- fileNewAction,
- fileOpenAction,
- null,
- fileCloseAction,
- fileCloseAllAction,
- null,
- fileSaveAction,
- fileSaveAllAction,
- null,
- fileExitAction );
-
- final Menu editMenu = ActionUtils.createMenu( get( "Main.menu.edit" ),
- editUndoAction,
- editRedoAction,
- editFindAction,
- editReplaceAction,
- editFindNextAction,
- editFindPreviousAction );
-
- final Menu insertMenu = ActionUtils.createMenu( get( "Main.menu.insert" ),
- insertBoldAction,
- insertItalicAction,
- insertSuperscriptAction,
- insertSubscriptAction,
- insertStrikethroughAction,
- insertBlockquoteAction,
- insertCodeAction,
- insertFencedCodeBlockAction,
- null,
- insertLinkAction,
- insertImageAction,
- null,
- headers[ 0 ],
- headers[ 1 ],
- headers[ 2 ],
- headers[ 3 ],
- headers[ 4 ],
- headers[ 5 ],
- null,
- insertUnorderedListAction,
- insertOrderedListAction,
- insertHorizontalRuleAction );
-
- final Menu toolsMenu = ActionUtils.createMenu( get( "Main.menu.tools" ),
- toolsScriptAction );
-
- final Menu helpMenu = ActionUtils.createMenu( get( "Main.menu.help" ),
- helpAboutAction );
-
- menuBar = new MenuBar( fileMenu, editMenu, insertMenu, toolsMenu, helpMenu );
-
- //---- ToolBar ----
- ToolBar toolBar = ActionUtils.createToolBar(
- fileNewAction,
- fileOpenAction,
- fileSaveAction,
- null,
- editUndoAction,
- editRedoAction,
- null,
- insertBoldAction,
- insertItalicAction,
- insertSuperscriptAction,
- insertSubscriptAction,
- insertBlockquoteAction,
- insertCodeAction,
- insertFencedCodeBlockAction,
- null,
- insertLinkAction,
- insertImageAction,
- null,
- headers[ 0 ],
- null,
- insertUnorderedListAction,
- insertOrderedListAction );
-
- return new VBox( menuBar, toolBar );
- }
-
- /**
- * Creates a boolean property that is bound to another boolean value of the
- * active editor.
- */
- private BooleanProperty createActiveBooleanProperty(
- final Function<FileEditorTab, ObservableBooleanValue> func ) {
-
- final BooleanProperty b = new SimpleBooleanProperty();
- final FileEditorTab tab = getActiveFileEditor();
-
- if( tab != null ) {
- b.bind( func.apply( tab ) );
- }
-
- getFileEditorPane().activeFileEditorProperty().addListener(
- (observable, oldFileEditor, newFileEditor) -> {
- b.unbind();
-
- if( newFileEditor != null ) {
- b.bind( func.apply( newFileEditor ) );
- }
- else {
- b.set( false );
- }
- }
- );
-
- return b;
- }
-
- private void initLayout() {
- final Scene appScene = getScene();
-
- appScene.getStylesheets().add( STYLESHEET_SCENE );
-// appScene.getStylesheets().add( STYLESHEET_XML );
-
+import com.scrivenvar.dialogs.RScriptDialog;
+import com.scrivenvar.editors.EditorPane;
+import com.scrivenvar.editors.VariableNameInjector;
+import com.scrivenvar.editors.markdown.MarkdownEditorPane;
+import com.scrivenvar.predicates.files.FileTypePredicate;
+import com.scrivenvar.preview.HTMLPreviewPane;
+import com.scrivenvar.processors.Processor;
+import com.scrivenvar.processors.ProcessorFactory;
+import com.scrivenvar.service.Options;
+import com.scrivenvar.service.Snitch;
+import com.scrivenvar.service.events.Notifier;
+import com.scrivenvar.util.Action;
+import com.scrivenvar.util.ActionUtils;
+import static com.scrivenvar.util.StageState.*;
+import static de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon.*;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Observable;
+import java.util.Observer;
+import java.util.Optional;
+import java.util.function.Function;
+import java.util.prefs.Preferences;
+import javafx.application.Platform;
+import javafx.beans.binding.Bindings;
+import javafx.beans.binding.BooleanBinding;
+import javafx.beans.property.BooleanProperty;
+import javafx.beans.property.SimpleBooleanProperty;
+import javafx.beans.value.ObservableBooleanValue;
+import javafx.beans.value.ObservableValue;
+import javafx.collections.ListChangeListener.Change;
+import javafx.collections.ObservableList;
+import static javafx.event.Event.fireEvent;
+import javafx.geometry.Pos;
+import javafx.scene.Node;
+import javafx.scene.Scene;
+import javafx.scene.control.Alert;
+import javafx.scene.control.Alert.AlertType;
+import javafx.scene.control.Menu;
+import javafx.scene.control.MenuBar;
+import javafx.scene.control.SplitPane;
+import javafx.scene.control.Tab;
+import javafx.scene.control.TextField;
+import javafx.scene.control.ToolBar;
+import javafx.scene.control.TreeView;
+import javafx.scene.image.Image;
+import javafx.scene.image.ImageView;
+import static javafx.scene.input.KeyCode.ESCAPE;
+import javafx.scene.input.KeyEvent;
+import static javafx.scene.input.KeyEvent.CHAR_UNDEFINED;
+import static javafx.scene.input.KeyEvent.KEY_PRESSED;
+import javafx.scene.layout.BorderPane;
+import javafx.scene.layout.VBox;
+import javafx.scene.text.Text;
+import javafx.stage.Window;
+import javafx.stage.WindowEvent;
+import static javafx.stage.WindowEvent.WINDOW_CLOSE_REQUEST;
+import org.controlsfx.control.StatusBar;
+import org.fxmisc.richtext.model.TwoDimensional.Position;
+
+/**
+ * Main window containing a tab pane in the center for file editors.
+ *
+ * @author Karl Tauber and White Magic Software, Ltd.
+ */
+public class MainWindow implements Observer {
+
+ private final Options options = Services.load( Options.class );
+ private final Snitch snitch = Services.load( Snitch.class );
+ private final Notifier notifier = Services.load( Notifier.class );
+
+ private Scene scene;
+ private MenuBar menuBar;
+ private StatusBar statusBar;
+ private Text lineNumberText;
+ private TextField findTextField;
+
+ private DefinitionSource definitionSource;
+ private DefinitionPane definitionPane;
+ private FileEditorTabPane fileEditorPane;
+ private HTMLPreviewPane previewPane;
+
+ /**
+ * Prevents re-instantiation of processing classes.
+ */
+ private Map<FileEditorTab, Processor<String>> processors;
+
+ public MainWindow() {
+ initLayout();
+ initFindInput();
+ initSnitch();
+ initDefinitionListener();
+ initTabAddedListener();
+ initTabChangedListener();
+ initPreferences();
+ }
+
+ /**
+ * Watch for changes to external files. In particular, this awaits
+ * modifications to any XSL files associated with XML files being edited. When
+ * an XSL file is modified (external to the application), the snitch's ears
+ * perk up and the file is reloaded. This keeps the XSL transformation up to
+ * date with what's on the file system.
+ */
+ private void initSnitch() {
+ getSnitch().addObserver( this );
+ }
+
+ /**
+ * Initialize the find input text field to listen on F3, ENTER, and ESCAPE key
+ * presses.
+ */
+ private void initFindInput() {
+ final TextField input = getFindTextField();
+
+ input.setOnKeyPressed( (KeyEvent event) -> {
+ switch( event.getCode() ) {
+ case F3:
+ case ENTER:
+ findNext();
+ break;
+ case F:
+ if( !event.isControlDown() ) {
+ break;
+ }
+ case ESCAPE:
+ getStatusBar().setGraphic( null );
+ getActiveFileEditor().getEditorPane().requestFocus();
+ break;
+ }
+ } );
+
+ // Remove when the input field loses focus.
+ input.focusedProperty().addListener(
+ (
+ final ObservableValue<? extends Boolean> focused,
+ final Boolean oFocus,
+ final Boolean nFocus) -> {
+ if( !nFocus ) {
+ getStatusBar().setGraphic( null );
+ }
+ }
+ );
+ }
+
+ /**
+ * Listen for file editor tab pane to receive an open definition source event.
+ */
+ private void initDefinitionListener() {
+ getFileEditorPane().onOpenDefinitionFileProperty().addListener(
+ (ObservableValue<? extends Path> definitionFile,
+ final Path oldPath, final Path newPath) -> {
+ openDefinition( newPath );
+
+ // Indirectly refresh the resolved map.
+ setProcessors( null );
+ updateDefinitionPane();
+
+ try {
+ getSnitch().ignore( oldPath );
+ getSnitch().listen( newPath );
+ } catch( final IOException ex ) {
+ error( ex );
+ }
+
+ // Will create new processors and therefore a new resolved map.
+ refreshSelectedTab( getActiveFileEditor() );
+ }
+ );
+ }
+
+ /**
+ * When tabs are added, hook the various change listeners onto the new tab so
+ * that the preview pane refreshes as necessary.
+ */
+ private void initTabAddedListener() {
+ final FileEditorTabPane editorPane = getFileEditorPane();
+
+ // Make sure the text processor kicks off when new files are opened.
+ final ObservableList<Tab> tabs = editorPane.getTabs();
+
+ // Update the preview pane on tab changes.
+ tabs.addListener(
+ (final Change<? extends Tab> change) -> {
+ while( change.next() ) {
+ if( change.wasAdded() ) {
+ // Multiple tabs can be added simultaneously.
+ for( final Tab newTab : change.getAddedSubList() ) {
+ final FileEditorTab tab = (FileEditorTab)newTab;
+
+ initTextChangeListener( tab );
+ initCaretParagraphListener( tab );
+ initVariableNameInjector( tab );
+// initSyntaxListener( tab );
+ }
+ }
+ }
+ }
+ );
+ }
+
+ /**
+ * Reloads the preferences from the previous session.
+ */
+ private void initPreferences() {
+ restoreDefinitionSource();
+ getFileEditorPane().restorePreferences();
+ updateDefinitionPane();
+ }
+
+ /**
+ * Listen for new tab selection events.
+ */
+ private void initTabChangedListener() {
+ final FileEditorTabPane editorPane = getFileEditorPane();
+
+ // Update the preview pane changing tabs.
+ editorPane.addTabSelectionListener(
+ (ObservableValue<? extends Tab> tabPane,
+ final Tab oldTab, final Tab newTab) -> {
+
+ // If there was no old tab, then this is a first time load, which
+ // can be ignored.
+ if( oldTab != null ) {
+ if( newTab == null ) {
+ closeRemainingTab();
+ }
+ else {
+ // Update the preview with the edited text.
+ refreshSelectedTab( (FileEditorTab)newTab );
+ }
+ }
+ }
+ );
+ }
+
+ private void initTextChangeListener( final FileEditorTab tab ) {
+ tab.addTextChangeListener(
+ (ObservableValue<? extends String> editor,
+ final String oldValue, final String newValue) -> {
+ refreshSelectedTab( tab );
+ }
+ );
+ }
+
+ private void initCaretParagraphListener( final FileEditorTab tab ) {
+ tab.addCaretParagraphListener(
+ (ObservableValue<? extends Integer> editor,
+ final Integer oldValue, final Integer newValue) -> {
+ refreshSelectedTab( tab );
+ }
+ );
+ }
+
+ private void initVariableNameInjector( final FileEditorTab tab ) {
+ VariableNameInjector.listen( tab, getDefinitionPane() );
+ }
+
+ /**
+ * Called whenever the preview pane becomes out of sync with the file editor
+ * tab. This can be called when the text changes, the caret paragraph changes,
+ * or the file tab changes.
+ *
+ * @param tab The file editor tab that has been changed in some fashion.
+ */
+ private void refreshSelectedTab( final FileEditorTab tab ) {
+ if( tab.isFileOpen() ) {
+ getPreviewPane().setPath( tab.getPath() );
+
+ // TODO: https://github.com/DaveJarvis/scrivenvar/issues/29
+ final Position p = tab.getCaretOffset();
+ getLineNumberText().setText(
+ get( STATUS_BAR_LINE,
+ p.getMajor() + 1,
+ p.getMinor() + 1,
+ tab.getCaretPosition() + 1
+ )
+ );
+
+ Processor<String> processor = getProcessors().get( tab );
+
+ if( processor == null ) {
+ processor = createProcessor( tab );
+ getProcessors().put( tab, processor );
+ }
+
+ try {
+ getNotifier().clear();
+ processor.processChain( tab.getEditorText() );
+ } catch( final Exception ex ) {
+ error( ex );
+ }
+ }
+ }
+
+ /**
+ * Used to find text in the active file editor window.
+ */
+ private void find() {
+ final TextField input = getFindTextField();
+ getStatusBar().setGraphic( input );
+ input.requestFocus();
+ }
+
+ public void findNext() {
+ getActiveFileEditor().searchNext( getFindTextField().getText() );
+ }
+
+ /**
+ * Returns the variable map of interpolated definitions.
+ *
+ * @return A map to help dereference variables.
+ */
+ private Map<String, String> getResolvedMap() {
+ return getDefinitionSource().getResolvedMap();
+ }
+
+ /**
+ * Returns the root node for the hierarchical definition source.
+ *
+ * @return Data to display in the definition pane.
+ */
+ private TreeView<String> getTreeView() {
+ try {
+ return getDefinitionSource().asTreeView();
+ } catch( Exception e ) {
+ error( e );
+ }
+
+ // Slightly redundant as getDefinitionSource() might have returned an
+ // empty definition source.
+ return (new EmptyDefinitionSource()).asTreeView();
+ }
+
+ /**
+ * Called when a definition source is opened.
+ *
+ * @param path Path to the definition source that was opened.
+ */
+ private void openDefinition( final Path path ) {
+ try {
+ final DefinitionSource ds = createDefinitionSource( path.toString() );
+ setDefinitionSource( ds );
+ storeDefinitionSource();
+ updateDefinitionPane();
+ } catch( final Exception e ) {
+ error( e );
+ }
+ }
+
+ private void updateDefinitionPane() {
+ getDefinitionPane().setRoot( getDefinitionSource().asTreeView() );
+ }
+
+ private void restoreDefinitionSource() {
+ final Preferences preferences = getPreferences();
+ final String source = preferences.get( PERSIST_DEFINITION_SOURCE, null );
+
+ // If there's no definition source set, don't try to load it.
+ if( source != null ) {
+ setDefinitionSource( createDefinitionSource( source ) );
+ }
+ }
+
+ private void storeDefinitionSource() {
+ final Preferences preferences = getPreferences();
+ final DefinitionSource ds = getDefinitionSource();
+
+ preferences.put( PERSIST_DEFINITION_SOURCE, ds.toString() );
+ }
+
+ /**
+ * Called when the last open tab is closed to clear the preview pane.
+ */
+ private void closeRemainingTab() {
+ getPreviewPane().clear();
+ }
+
+ /**
+ * Called when an exception occurs that warrants the user's attention.
+ *
+ * @param e The exception with a message that the user should know about.
+ */
+ private void error( final Exception e ) {
+ getNotifier().notify( e );
+ }
+
+ //---- File actions -------------------------------------------------------
+ /**
+ * Called when an observable instance has changed. This is called by both the
+ * snitch service and the notify service. The snitch service can be called for
+ * different file types, including definition sources.
+ *
+ * @param observable The observed instance.
+ * @param value The noteworthy item.
+ */
+ @Override
+ public void update( final Observable observable, final Object value ) {
+ if( value != null ) {
+ if( observable instanceof Snitch && value instanceof Path ) {
+ final Path path = (Path)value;
+ final FileTypePredicate predicate
+ = new FileTypePredicate( GLOB_DEFINITION_EXTENSIONS );
+
+ // Reload definitions.
+ if( predicate.test( path.toFile() ) ) {
+ updateDefinitionSource( path );
+ }
+
+ updateSelectedTab();
+ }
+ else if( observable instanceof Notifier && value instanceof String ) {
+ updateStatusBar( (String)value );
+ }
+ }
+ }
+
+ /**
+ * Updates the status bar to show the given message.
+ *
+ * @param s The message to show in the status bar.
+ */
+ private void updateStatusBar( final String s ) {
+ Platform.runLater(
+ () -> {
+ final int index = s.indexOf( '\n' );
+ final String message = s.substring( 0, index > 0 ? index : s.length() );
+
+ getStatusBar().setText( message );
+ }
+ );
+ }
+
+ /**
+ * Called when a file has been modified.
+ *
+ * @param file Path to the modified file.
+ */
+ private void updateSelectedTab() {
+ Platform.runLater(
+ () -> {
+ // Brute-force XSLT file reload by re-instantiating all processors.
+ resetProcessors();
+ refreshSelectedTab( getActiveFileEditor() );
+ }
+ );
+ }
+
+ /**
+ * Reloads the definition source from the given path.
+ *
+ * @param path The path containing new definition information.
+ */
+ private void updateDefinitionSource( final Path path ) {
+ Platform.runLater(
+ () -> {
+ openDefinition( path );
+ }
+ );
+ }
+
+ /**
+ * After resetting the processors, they will refresh anew to be up-to-date
+ * with the files (text and definition) currently loaded into the editor.
+ */
+ private void resetProcessors() {
+ getProcessors().clear();
+ }
+
+ //---- File actions -------------------------------------------------------
+ private void fileNew() {
+ getFileEditorPane().newEditor();
+ }
+
+ private void fileOpen() {
+ getFileEditorPane().openFileDialog();
+ }
+
+ private void fileClose() {
+ getFileEditorPane().closeEditor( getActiveFileEditor(), true );
+ }
+
+ private void fileCloseAll() {
+ getFileEditorPane().closeAllEditors();
+ }
+
+ private void fileSave() {
+ getFileEditorPane().saveEditor( getActiveFileEditor() );
+ }
+
+ private void fileSaveAll() {
+ getFileEditorPane().saveAllEditors();
+ }
+
+ private void fileExit() {
+ final Window window = getWindow();
+ fireEvent( window, new WindowEvent( window, WINDOW_CLOSE_REQUEST ) );
+ }
+
+ //---- Tools actions
+ private void toolsScript() {
+ final String script = getStartupScript();
+
+ System.out.println( "script = '" + script + "'" );
+
+ final RScriptDialog dialog = new RScriptDialog(
+ getWindow(), "Dialog.rScript.title", script );
+ final Optional<String> result = dialog.showAndWait();
+
+ result.ifPresent( (String s) -> {
+ putStartupScript( s );
+ } );
+ }
+
+ /**
+ * Gets the R startup script from the user preferences.
+ */
+ private String getStartupScript() {
+ return getPreferences().get( PERSIST_R_STARTUP, "" );
+ }
+
+ /**
+ * Puts an R startup script into the user preferences.
+ */
+ private void putStartupScript( final String s ) {
+ try {
+ System.out.println( "put startup script = '" + s + "'" );
+ getPreferences().put( PERSIST_R_STARTUP, s );
+ getPreferences().sync();
+ } catch( final Exception ex ) {
+ getNotifier().notify( ex );
+ }
+ }
+
+ //---- Help actions -------------------------------------------------------
+ private void helpAbout() {
+ Alert alert = new Alert( AlertType.INFORMATION );
+ alert.setTitle( get( "Dialog.about.title" ) );
+ alert.setHeaderText( get( "Dialog.about.header" ) );
+ alert.setContentText( get( "Dialog.about.content" ) );
+ alert.setGraphic( new ImageView( new Image( FILE_LOGO_32 ) ) );
+ alert.initOwner( getWindow() );
+
+ alert.showAndWait();
+ }
+
+ //---- Convenience accessors ----------------------------------------------
+ private float getFloat( final String key, final float defaultValue ) {
+ return getPreferences().getFloat( key, defaultValue );
+ }
+
+ private Preferences getPreferences() {
+ return getOptions().getState();
+ }
+
+ protected Scene getScene() {
+ if( this.scene == null ) {
+ this.scene = createScene();
+ }
+
+ return this.scene;
+ }
+
+ public Window getWindow() {
+ return getScene().getWindow();
+ }
+
+ private MarkdownEditorPane getActiveEditor() {
+ final EditorPane pane = getActiveFileEditor().getEditorPane();
+
+ return pane instanceof MarkdownEditorPane ? (MarkdownEditorPane)pane : null;
+ }
+
+ private FileEditorTab getActiveFileEditor() {
+ return getFileEditorPane().getActiveFileEditor();
+ }
+
+ //---- Member accessors ---------------------------------------------------
+ private void setProcessors( final Map<FileEditorTab, Processor<String>> map ) {
+ this.processors = map;
+ }
+
+ private Map<FileEditorTab, Processor<String>> getProcessors() {
+ if( this.processors == null ) {
+ setProcessors( new HashMap<>() );
+ }
+
+ return this.processors;
+ }
+
+ private FileEditorTabPane getFileEditorPane() {
+ if( this.fileEditorPane == null ) {
+ this.fileEditorPane = createFileEditorPane();
+ }
+
+ return this.fileEditorPane;
+ }
+
+ private HTMLPreviewPane getPreviewPane() {
+ if( this.previewPane == null ) {
+ this.previewPane = createPreviewPane();
+ }
+
+ return this.previewPane;
+ }
+
+ private void setDefinitionSource( final DefinitionSource definitionSource ) {
+ this.definitionSource = definitionSource;
+ }
+
+ private DefinitionSource getDefinitionSource() {
+ if( this.definitionSource == null ) {
+ this.definitionSource = new EmptyDefinitionSource();
+ }
+
+ return this.definitionSource;
+ }
+
+ private DefinitionPane getDefinitionPane() {
+ if( this.definitionPane == null ) {
+ this.definitionPane = createDefinitionPane();
+ }
+
+ return this.definitionPane;
+ }
+
+ private Options getOptions() {
+ return this.options;
+ }
+
+ private Snitch getSnitch() {
+ return this.snitch;
+ }
+
+ private Notifier getNotifier() {
+ return this.notifier;
+ }
+
+ public void setMenuBar( final MenuBar menuBar ) {
+ this.menuBar = menuBar;
+ }
+
+ public MenuBar getMenuBar() {
+ return this.menuBar;
+ }
+
+ private Text getLineNumberText() {
+ if( this.lineNumberText == null ) {
+ this.lineNumberText = createLineNumberText();
+ }
+
+ return this.lineNumberText;
+ }
+
+ private synchronized StatusBar getStatusBar() {
+ if( this.statusBar == null ) {
+ this.statusBar = createStatusBar();
+ }
+
+ return this.statusBar;
+ }
+
+ private TextField getFindTextField() {
+ if( this.findTextField == null ) {
+ this.findTextField = createFindTextField();
+ }
+
+ return this.findTextField;
+ }
+
+ //---- Member creators ----------------------------------------------------
+ /**
+ * Factory to create processors that are suited to different file types.
+ *
+ * @param tab The tab that is subjected to processing.
+ *
+ * @return A processor suited to the file type specified by the tab's path.
+ */
+ private Processor<String> createProcessor( final FileEditorTab tab ) {
+ return createProcessorFactory().createProcessor( tab );
+ }
+
+ private ProcessorFactory createProcessorFactory() {
+ return new ProcessorFactory( getPreviewPane(), getResolvedMap() );
+ }
+
+ private DefinitionSource createDefinitionSource( final String path ) {
+ final DefinitionSource ds
+ = createDefinitionFactory().createDefinitionSource( path );
+
+ if( ds instanceof FileDefinitionSource ) {
+ try {
+ getSnitch().listen( ((FileDefinitionSource)ds).getPath() );
+ } catch( final IOException ex ) {
+ error( ex );
+ }
+ }
+
+ return ds;
+ }
+
+ private TextField createFindTextField() {
+ return new TextField();
+ }
+
+ /**
+ * Create an editor pane to hold file editor tabs.
+ *
+ * @return A new instance, never null.
+ */
+ private FileEditorTabPane createFileEditorPane() {
+ return new FileEditorTabPane();
+ }
+
+ private HTMLPreviewPane createPreviewPane() {
+ return new HTMLPreviewPane();
+ }
+
+ private DefinitionPane createDefinitionPane() {
+ return new DefinitionPane( getTreeView() );
+ }
+
+ private DefinitionFactory createDefinitionFactory() {
+ return new DefinitionFactory();
+ }
+
+ private StatusBar createStatusBar() {
+ return new StatusBar();
+ }
+
+ private Scene createScene() {
+ final SplitPane splitPane = new SplitPane(
+ getDefinitionPane().getNode(),
+ getFileEditorPane().getNode(),
+ getPreviewPane().getNode() );
+
+ splitPane.setDividerPositions(
+ getFloat( K_PANE_SPLIT_DEFINITION, .10f ),
+ getFloat( K_PANE_SPLIT_EDITOR, .45f ),
+ getFloat( K_PANE_SPLIT_PREVIEW, .45f ) );
+
+ // See: http://broadlyapplicable.blogspot.ca/2015/03/javafx-capture-restorePreferences-splitpane.html
+ final BorderPane borderPane = new BorderPane();
+ borderPane.setPrefSize( 1024, 800 );
+ borderPane.setTop( createMenuBar() );
+ borderPane.setBottom( getStatusBar() );
+ borderPane.setCenter( splitPane );
+
+ final VBox box = new VBox();
+ box.setAlignment( Pos.BASELINE_CENTER );
+ box.getChildren().add( getLineNumberText() );
+ getStatusBar().getRightItems().add( box );
+
+ return new Scene( borderPane );
+ }
+
+ private Text createLineNumberText() {
+ return new Text( get( STATUS_BAR_LINE, 1, 1, 1 ) );
+ }
+
+ private Node createMenuBar() {
+ final BooleanBinding activeFileEditorIsNull = getFileEditorPane().activeFileEditorProperty().isNull();
+
+ // File actions
+ final Action fileNewAction = new Action( get( "Main.menu.file.new" ), "Shortcut+N", FILE_ALT, e -> fileNew() );
+ final Action fileOpenAction = new Action( get( "Main.menu.file.open" ), "Shortcut+O", FOLDER_OPEN_ALT, e -> fileOpen() );
+ final Action fileCloseAction = new Action( get( "Main.menu.file.close" ), "Shortcut+W", null, e -> fileClose(), activeFileEditorIsNull );
+ final Action fileCloseAllAction = new Action( get( "Main.menu.file.close_all" ), null, null, e -> fileCloseAll(), activeFileEditorIsNull );
+ final Action fileSaveAction = new Action( get( "Main.menu.file.save" ), "Shortcut+S", FLOPPY_ALT, e -> fileSave(),
+ createActiveBooleanProperty( FileEditorTab::modifiedProperty ).not() );
+ final Action fileSaveAllAction = new Action( get( "Main.menu.file.save_all" ), "Shortcut+Shift+S", null, e -> fileSaveAll(),
+ Bindings.not( getFileEditorPane().anyFileEditorModifiedProperty() ) );
+ final Action fileExitAction = new Action( get( "Main.menu.file.exit" ), null, null, e -> fileExit() );
+
+ // Edit actions
+ final Action editUndoAction = new Action( get( "Main.menu.edit.undo" ), "Shortcut+Z", UNDO,
+ e -> getActiveEditor().undo(),
+ createActiveBooleanProperty( FileEditorTab::canUndoProperty ).not() );
+ final Action editRedoAction = new Action( get( "Main.menu.edit.redo" ), "Shortcut+Y", REPEAT,
+ e -> getActiveEditor().redo(),
+ createActiveBooleanProperty( FileEditorTab::canRedoProperty ).not() );
+ final Action editFindAction = new Action( Messages.get( "Main.menu.edit.find" ), "Ctrl+F", SEARCH,
+ e -> find(),
+ activeFileEditorIsNull );
+ final Action editReplaceAction = new Action( Messages.get( "Main.menu.edit.find.replace" ), "Shortcut+H", RETWEET,
+ e -> getActiveEditor().replace(),
+ activeFileEditorIsNull );
+ final Action editFindNextAction = new Action( Messages.get( "Main.menu.edit.find.next" ), "F3", null,
+ e -> findNext(),
+ activeFileEditorIsNull );
+ final Action editFindPreviousAction = new Action( Messages.get( "Main.menu.edit.find.previous" ), "Shift+F3", null,
+ e -> getActiveEditor().findPrevious(),
+ activeFileEditorIsNull );
+
+ // Insert actions
+ final Action insertBoldAction = new Action( get( "Main.menu.insert.bold" ), "Shortcut+B", BOLD,
+ e -> getActiveEditor().surroundSelection( "**", "**" ),
+ activeFileEditorIsNull );
+ final Action insertItalicAction = new Action( get( "Main.menu.insert.italic" ), "Shortcut+I", ITALIC,
+ e -> getActiveEditor().surroundSelection( "*", "*" ),
+ activeFileEditorIsNull );
+ final Action insertSuperscriptAction = new Action( get( "Main.menu.insert.superscript" ), "Shortcut+[", SUPERSCRIPT,
+ e -> getActiveEditor().surroundSelection( "^", "^" ),
+ activeFileEditorIsNull );
+ final Action insertSubscriptAction = new Action( get( "Main.menu.insert.subscript" ), "Shortcut+]", SUBSCRIPT,
+ e -> getActiveEditor().surroundSelection( "~", "~" ),
+ activeFileEditorIsNull );
+ final Action insertStrikethroughAction = new Action( get( "Main.menu.insert.strikethrough" ), "Shortcut+T", STRIKETHROUGH,
+ e -> getActiveEditor().surroundSelection( "~~", "~~" ),
+ activeFileEditorIsNull );
+ final Action insertBlockquoteAction = new Action( get( "Main.menu.insert.blockquote" ), "Ctrl+Q", QUOTE_LEFT, // not Shortcut+Q because of conflict on Mac
+ e -> getActiveEditor().surroundSelection( "\n\n> ", "" ),
+ activeFileEditorIsNull );
+ final Action insertCodeAction = new Action( get( "Main.menu.insert.code" ), "Shortcut+K", CODE,
+ e -> getActiveEditor().surroundSelection( "`", "`" ),
+ activeFileEditorIsNull );
+ final Action insertFencedCodeBlockAction = new Action( get( "Main.menu.insert.fenced_code_block" ), "Shortcut+Shift+K", FILE_CODE_ALT,
+ e -> getActiveEditor().surroundSelection( "\n\n```\n", "\n```\n\n", get( "Main.menu.insert.fenced_code_block.prompt" ) ),
+ activeFileEditorIsNull );
+
+ final Action insertLinkAction = new Action( get( "Main.menu.insert.link" ), "Shortcut+L", LINK,
+ e -> getActiveEditor().insertLink(),
+ activeFileEditorIsNull );
+ final Action insertImageAction = new Action( get( "Main.menu.insert.image" ), "Shortcut+G", PICTURE_ALT,
+ e -> getActiveEditor().insertImage(),
+ activeFileEditorIsNull );
+
+ final Action[] headers = new Action[ 6 ];
+
+ // Insert header actions (H1 ... H6)
+ for( int i = 1; i <= 6; i++ ) {
+ final String hashes = new String( new char[ i ] ).replace( "\0", "#" );
+ final String markup = String.format( "%n%n%s ", hashes );
+ final String text = get( "Main.menu.insert.header_" + i );
+ final String accelerator = "Shortcut+" + i;
+ final String prompt = get( "Main.menu.insert.header_" + i + ".prompt" );
+
+ headers[ i - 1 ] = new Action( text, accelerator, HEADER,
+ e -> getActiveEditor().surroundSelection( markup, "", prompt ),
+ activeFileEditorIsNull );
+ }
+
+ final Action insertUnorderedListAction = new Action(
+ get( "Main.menu.insert.unordered_list" ), "Shortcut+U", LIST_UL,
+ e -> getActiveEditor().surroundSelection( "\n\n* ", "" ),
+ activeFileEditorIsNull );
+ final Action insertOrderedListAction = new Action(
+ get( "Main.menu.insert.ordered_list" ), "Shortcut+Shift+O", LIST_OL,
+ e -> getActiveEditor().surroundSelection( "\n\n1. ", "" ),
+ activeFileEditorIsNull );
+ final Action insertHorizontalRuleAction = new Action(
+ get( "Main.menu.insert.horizontal_rule" ), "Shortcut+H", null,
+ e -> getActiveEditor().surroundSelection( "\n\n---\n\n", "" ),
+ activeFileEditorIsNull );
+
+ // Tools actions
+ final Action toolsScriptAction = new Action(
+ get( "Main.menu.tools.script" ), null, null, e -> toolsScript() );
+
+ // Help actions
+ final Action helpAboutAction = new Action(
+ get( "Main.menu.help.about" ), null, null, e -> helpAbout() );
+
+ //---- MenuBar ----
+ final Menu fileMenu = ActionUtils.createMenu( get( "Main.menu.file" ),
+ fileNewAction,
+ fileOpenAction,
+ null,
+ fileCloseAction,
+ fileCloseAllAction,
+ null,
+ fileSaveAction,
+ fileSaveAllAction,
+ null,
+ fileExitAction );
+
+ final Menu editMenu = ActionUtils.createMenu( get( "Main.menu.edit" ),
+ editUndoAction,
+ editRedoAction,
+ editFindAction,
+ editReplaceAction,
+ editFindNextAction,
+ editFindPreviousAction );
+
+ final Menu insertMenu = ActionUtils.createMenu( get( "Main.menu.insert" ),
+ insertBoldAction,
+ insertItalicAction,
+ insertSuperscriptAction,
+ insertSubscriptAction,
+ insertStrikethroughAction,
+ insertBlockquoteAction,
+ insertCodeAction,
+ insertFencedCodeBlockAction,
+ null,
+ insertLinkAction,
+ insertImageAction,
+ null,
+ headers[ 0 ],
+ headers[ 1 ],
+ headers[ 2 ],
+ headers[ 3 ],
+ headers[ 4 ],
+ headers[ 5 ],
+ null,
+ insertUnorderedListAction,
+ insertOrderedListAction,
+ insertHorizontalRuleAction );
+
+ final Menu toolsMenu = ActionUtils.createMenu( get( "Main.menu.tools" ),
+ toolsScriptAction );
+
+ final Menu helpMenu = ActionUtils.createMenu( get( "Main.menu.help" ),
+ helpAboutAction );
+
+ menuBar = new MenuBar( fileMenu, editMenu, insertMenu, toolsMenu, helpMenu );
+
+ //---- ToolBar ----
+ ToolBar toolBar = ActionUtils.createToolBar(
+ fileNewAction,
+ fileOpenAction,
+ fileSaveAction,
+ null,
+ editUndoAction,
+ editRedoAction,
+ null,
+ insertBoldAction,
+ insertItalicAction,
+ insertSuperscriptAction,
+ insertSubscriptAction,
+ insertBlockquoteAction,
+ insertCodeAction,
+ insertFencedCodeBlockAction,
+ null,
+ insertLinkAction,
+ insertImageAction,
+ null,
+ headers[ 0 ],
+ null,
+ insertUnorderedListAction,
+ insertOrderedListAction );
+
+ return new VBox( menuBar, toolBar );
+ }
+
+ /**
+ * Creates a boolean property that is bound to another boolean value of the
+ * active editor.
+ */
+ private BooleanProperty createActiveBooleanProperty(
+ final Function<FileEditorTab, ObservableBooleanValue> func ) {
+
+ final BooleanProperty b = new SimpleBooleanProperty();
+ final FileEditorTab tab = getActiveFileEditor();
+
+ if( tab != null ) {
+ b.bind( func.apply( tab ) );
+ }
+
+ getFileEditorPane().activeFileEditorProperty().addListener(
+ (observable, oldFileEditor, newFileEditor) -> {
+ b.unbind();
+
+ if( newFileEditor != null ) {
+ b.bind( func.apply( newFileEditor ) );
+ }
+ else {
+ b.set( false );
+ }
+ }
+ );
+
+ return b;
+ }
+
+ private void initLayout() {
+ final Scene appScene = getScene();
+
+ appScene.getStylesheets().add( STYLESHEET_SCENE );
+
+ // TODO: Apply an XML syntax highlighting for XML files.
+// appScene.getStylesheets().add( STYLESHEET_XML );
appScene.windowProperty().addListener(
(observable, oldWindow, newWindow) -> {
src/main/java/com/scrivenvar/dialogs/AbstractDialog.java
+/*
+ * Copyright 2017 White Magic Software, Ltd.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * o Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package com.scrivenvar.dialogs;
+
+import static com.scrivenvar.Messages.get;
+import com.scrivenvar.service.events.impl.ButtonOrderPane;
+import static javafx.scene.control.ButtonType.CANCEL;
+import static javafx.scene.control.ButtonType.OK;
+import javafx.scene.control.Dialog;
+import javafx.stage.Window;
+
+/**
+ * Superclass that abstracts common behaviours for all dialogs.
+ *
+ * @author White Magic Software, Ltd.
+ * @param <T> The type of dialog to create (usually String).
+ */
+public abstract class AbstractDialog<T> extends Dialog<T> {
+
+ /**
+ * Ensures that all dialogs can be closed.
+ *
+ * @param owner The parent window of this dialog.
+ * @param title The messages title to display in the title bar.
+ */
+ @SuppressWarnings( "OverridableMethodCallInConstructor" )
+ public AbstractDialog( final Window owner, final String title ) {
+ setTitle( get( title ) );
+ setResizable( true );
+
+ initOwner( owner );
+ initCloseAction();
+ initDialogPane();
+ initDialogButtons();
+ initComponents();
+ }
+
+ /**
+ * Initialize the component layout.
+ */
+ protected abstract void initComponents();
+
+ /**
+ * Set the dialog to use a button order pane with an OK and a CANCEL button.
+ */
+ protected void initDialogPane() {
+ setDialogPane( new ButtonOrderPane() );
+ }
+
+ /**
+ * Set an OK and CANCEL button on the dialog.
+ */
+ protected void initDialogButtons() {
+ getDialogPane().getButtonTypes().addAll( OK, CANCEL );
+ }
+
+ /**
+ * Attaches a setOnCloseRequest to the dialog's [X] button so that the user
+ * can always close the window, even if there's an error.
+ */
+ protected final void initCloseAction() {
+ final Window window = getDialogPane().getScene().getWindow();
+ window.setOnCloseRequest( event -> window.hide() );
+ }
+}
src/main/java/com/scrivenvar/dialogs/ImageDialog.java
package com.scrivenvar.dialogs;
-import com.scrivenvar.Messages;
+import static com.scrivenvar.Messages.get;
import com.scrivenvar.controls.BrowseFileButton;
import com.scrivenvar.controls.EscapeTextField;
-import com.scrivenvar.service.events.impl.ButtonOrderPane;
import java.nio.file.Path;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.ButtonBar.ButtonData;
-import javafx.scene.control.ButtonType;
-import javafx.scene.control.Dialog;
+import static javafx.scene.control.ButtonType.OK;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
* @author Karl Tauber
*/
-public class ImageDialog extends Dialog<String> {
+public class ImageDialog extends AbstractDialog<String> {
private final StringProperty image = new SimpleStringProperty();
-
- public ImageDialog( Window owner, Path basePath ) {
- setTitle( Messages.get( "ImageDialog.title" ) );
- initOwner( owner );
- setResizable( true );
- initComponents();
+ public ImageDialog( final Window owner, final Path basePath ) {
+ super(owner, "Dialog.image.title" );
+
+ final DialogPane dialogPane = getDialogPane();
+ dialogPane.setContent( pane );
linkBrowseFileButton.setBasePath( basePath );
- linkBrowseFileButton.addExtensionFilter( new ExtensionFilter( Messages.get( "ImageDialog.chooser.imagesFilter" ), "*.png", "*.gif", "*.jpg" ) );
+ linkBrowseFileButton.addExtensionFilter( new ExtensionFilter( get( "Dialog.image.chooser.imagesFilter" ), "*.png", "*.gif", "*.jpg" ) );
linkBrowseFileButton.urlProperty().bindBidirectional( urlField.escapedTextProperty() );
-
- setDialogPane( new ButtonOrderPane() );
- final DialogPane dialogPane = getDialogPane();
- dialogPane.setContent( pane );
- dialogPane.getButtonTypes().addAll( ButtonType.OK, ButtonType.CANCEL );
- dialogPane.lookupButton( ButtonType.OK ).disableProperty().bind(
+ dialogPane.lookupButton( OK ).disableProperty().bind(
urlField.escapedTextProperty().isEmpty()
.or( textField.escapedTextProperty().isEmpty() ) );
}
- private void initComponents() {
+ @Override
+ protected void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
pane = new MigPane();
//---- urlLabel ----
- urlLabel.setText( Messages.get( "ImageDialog.urlLabel.text" ) );
+ urlLabel.setText( get( "Dialog.image.urlLabel.text" ) );
pane.add( urlLabel, "cell 0 0" );
//---- textLabel ----
- textLabel.setText( Messages.get( "ImageDialog.textLabel.text" ) );
+ textLabel.setText( get( "Dialog.image.textLabel.text" ) );
pane.add( textLabel, "cell 0 1" );
//---- textField ----
textField.setEscapeCharacters( "[]" );
pane.add( textField, "cell 1 1 2 1" );
//---- titleLabel ----
- titleLabel.setText( Messages.get( "ImageDialog.titleLabel.text" ) );
+ titleLabel.setText( get( "Dialog.image.titleLabel.text" ) );
pane.add( titleLabel, "cell 0 2" );
pane.add( titleField, "cell 1 2 2 1" );
//---- previewLabel ----
- previewLabel.setText( Messages.get( "ImageDialog.previewLabel.text" ) );
+ previewLabel.setText( get( "Dialog.image.previewLabel.text" ) );
pane.add( previewLabel, "cell 0 3" );
pane.add( previewField, "cell 1 3 2 1" );
src/main/java/com/scrivenvar/dialogs/LinkDialog.java
package com.scrivenvar.dialogs;
-import com.scrivenvar.Messages;
+import static com.scrivenvar.Messages.get;
import com.scrivenvar.controls.EscapeTextField;
import com.scrivenvar.editors.markdown.HyperlinkModel;
-import com.scrivenvar.service.events.impl.ButtonOrderPane;
import java.nio.file.Path;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.ButtonBar.ButtonData;
-import javafx.scene.control.ButtonType;
-import javafx.scene.control.Dialog;
+import static javafx.scene.control.ButtonType.OK;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
* @author Karl Tauber
*/
-public class LinkDialog extends Dialog<String> {
+public class LinkDialog extends AbstractDialog<String> {
private final StringProperty link = new SimpleStringProperty();
-
- public LinkDialog( final Window owner, final HyperlinkModel hyperlink, final Path basePath ) {
- setTitle( Messages.get( "LinkDialog.title" ) );
- initOwner( owner );
- setResizable( true );
-
- initComponents();
- setDialogPane( new ButtonOrderPane() );
+ public LinkDialog(
+ final Window owner, final HyperlinkModel hyperlink, final Path basePath ) {
+ super( owner, "Dialog.link.title" );
- final DialogPane dialog = getDialogPane();
- dialog.setContent( pane );
- dialog.getButtonTypes().addAll( ButtonType.OK, ButtonType.CANCEL );
+ final DialogPane dialogPane = getDialogPane();
+ dialogPane.setContent( pane );
- dialog.lookupButton( ButtonType.OK ).disableProperty().bind(
+ dialogPane.lookupButton( OK ).disableProperty().bind(
urlField.escapedTextProperty().isEmpty() );
}
- private void initComponents() {
+ @Override
+ protected void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
pane = new MigPane();
//---- urlLabel ----
- urlLabel.setText( Messages.get( "LinkDialog.urlLabel.text" ) );
+ urlLabel.setText( get( "Dialog.link.urlLabel.text" ) );
pane.add( urlLabel, "cell 0 0" );
//---- urlField ----
urlField.setEscapeCharacters( "()" );
pane.add( urlField, "cell 1 0" );
//---- textLabel ----
- textLabel.setText( Messages.get( "LinkDialog.textLabel.text" ) );
+ textLabel.setText( get( "Dialog.link.textLabel.text" ) );
pane.add( textLabel, "cell 0 1" );
//---- textField ----
textField.setEscapeCharacters( "[]" );
pane.add( textField, "cell 1 1 3 1" );
//---- titleLabel ----
- titleLabel.setText( Messages.get( "LinkDialog.titleLabel.text" ) );
+ titleLabel.setText( get( "Dialog.link.titleLabel.text" ) );
pane.add( titleLabel, "cell 0 2" );
pane.add( titleField, "cell 1 2 3 1" );
src/main/java/com/scrivenvar/dialogs/RScriptDialog.java
+/*
+ * Copyright 2017 White Magic Software, Ltd.
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * o Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * o Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package com.scrivenvar.dialogs;
+
+import static com.scrivenvar.Messages.get;
+import javafx.application.Platform;
+import javafx.geometry.Insets;
+import static javafx.scene.control.ButtonType.OK;
+import javafx.scene.control.DialogPane;
+import javafx.scene.control.Label;
+import javafx.scene.control.TextArea;
+import javafx.scene.layout.GridPane;
+import javafx.stage.Window;
+
+/**
+ * Responsible for managing the R startup script that is run when an R source
+ * file is loaded.
+ *
+ * @author White Magic Software, Ltd.
+ */
+public class RScriptDialog extends AbstractDialog<String> {
+
+ private TextArea scriptArea;
+
+ public RScriptDialog(
+ final Window parent, final String title, final String script ) {
+ super( parent, title );
+ getScriptArea().setText( script );
+ }
+
+ @Override
+ protected void initComponents() {
+ final DialogPane pane = getDialogPane();
+
+ final GridPane grid = new GridPane();
+ grid.setHgap( 10 );
+ grid.setVgap( 10 );
+ grid.setPadding( new Insets( 10, 10, 10, 10 ) );
+
+ final Label label = new Label( get( "Dialog.rScript.content" ) );
+
+ final TextArea textArea = getScriptArea();
+ textArea.setEditable( true );
+ textArea.setWrapText( true );
+
+ grid.add( label, 0, 0 );
+ grid.add( textArea, 0, 1 );
+ pane.setContent( grid );
+
+ Platform.runLater( () -> textArea.requestFocus() );
+
+ setResultConverter( dialogButton -> {
+ return dialogButton == OK ? textArea.getText() : "";
+ } );
+ }
+
+ private TextArea getScriptArea() {
+ if( this.scriptArea == null ) {
+ this.scriptArea = new TextArea();
+ }
+
+ return this.scriptArea;
+ }
+}
src/main/java/com/scrivenvar/editors/markdown/MarkdownEditorPane.java
import org.fxmisc.richtext.StyleClassedTextArea;
import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed;
+import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed;
+import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed;
+import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed;
/**
src/main/java/com/scrivenvar/processors/InlineRProcessor.java
package com.scrivenvar.processors;
+import static com.scrivenvar.Constants.PERSIST_R_STARTUP;
import static com.scrivenvar.Constants.STATUS_PARSE_ERROR;
import static com.scrivenvar.Messages.get;
import com.scrivenvar.Services;
import static com.scrivenvar.decorators.RVariableDecorator.PREFIX;
import static com.scrivenvar.decorators.RVariableDecorator.SUFFIX;
import static com.scrivenvar.processors.text.TextReplacementFactory.replace;
-import com.scrivenvar.service.Settings;
+import com.scrivenvar.service.Options;
import com.scrivenvar.service.events.Notifier;
import java.io.IOException;
import static java.lang.Math.min;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.Map;
import javax.script.ScriptEngine;
private final Notifier notifier = Services.load( Notifier.class );
- private final Settings settings = Services.load( Settings.class );
+ private final Options options = Services.load( Options.class );
private ScriptEngine engine;
/**
- * @see https://github.com/DaveJarvis/scrivenvar/issues/30
+ *
* @param workingDirectory
*/
private void init( final Path workingDirectory ) {
try {
- final String dir = workingDirectory.toString().replace( '\\', '/' );
+ final Path wd = nullSafe( workingDirectory );
+ final String dir = wd.toString().replace( '\\', '/' );
final Map<String, String> definitions = getDefinitions();
definitions.put( "$application.r.working.directory$", dir );
final String initScript = getInitScript();
- final String rScript = replace( initScript, getDefinitions() );
+ System.out.println( "script = '" + initScript + "'" );
- eval( rScript );
+ if( !initScript.isEmpty() ) {
+ final String rScript = replace( initScript, getDefinitions() );
+ eval( rScript );
+ }
} catch( final IOException | ScriptException e ) {
throw new RuntimeException( e );
}
}
private String getInitScript() throws IOException {
- return getSettings().loadRStartupScript();
+ return getOptions().get( PERSIST_R_STARTUP, "" );
}
}
- private Settings getSettings() {
- return this.settings;
+ private Options getOptions() {
+ return this.options;
+ }
+
+ /**
+ * This will return the given path if not null, otherwise it will return
+ * Paths.get( System.getProperty( "user.dir" ) ).
+ *
+ * @param path The path to make null safe.
+ *
+ * @return A non-null path.
+ */
+ private Path nullSafe( final Path path ) {
+ return path == null ? Paths.get( System.getProperty( "user.dir" ) ) : path;
}
}
src/main/java/com/scrivenvar/service/Options.java
package com.scrivenvar.service;
+import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public Preferences getState();
-
+
/**
* Stores the key and value into the user preferences to be loaded the next
* time the application is launched.
*
* @param key Name of the key to persist along with its value.
* @param value Value to associate with the key.
+ *
+ * @throws BackingStoreException Could not persist the change.
*/
- public void put( String key, String value );
+ public void put( String key, String value ) throws BackingStoreException;
/**
*/
public String get( String key, String defaultValue );
+
+ /**
+ * Retrieves the value for a key in the user preferences. This will return
+ * the empty string if the value cannot be found.
+ *
+ * @param key The key to find in the preferences.
+ * @return A non-null, possibly empty value for the key.
+ */
+ public String get( String key );
}
src/main/java/com/scrivenvar/service/Settings.java
package com.scrivenvar.service;
-import java.io.IOException;
import java.util.Iterator;
import java.util.List;
public List<String> getStringSettingList( String property );
- /**
- * Reads the R startup script into a string, or the empty string if the file
- * could not be read (or found). The R startup file must be UTF-8.
- *
- * @return The string content for the R startup script, or empty if not found.
- *
- * @throws IOException Could not read the R startup script.
- */
- public String loadRStartupScript() throws IOException;
/**
- * Writes the R startup script into its predefined location.
+ * Changes key's value. This will clear the old value before setting the
+ * new value so that the old value is erased, not changed into a list.
*
- * @param script The string content for the R startup script.
- * @throws IOException Could not read the R startup script.
+ * @param key The property key name to obtain its value.
+ * @param value The new value to set.
*/
- public void saveRStartupScript( final String script ) throws IOException;
+ public void putSetting( String key, String value );
}
src/main/java/com/scrivenvar/service/impl/DefaultOptions.java
import static com.scrivenvar.Constants.PREFS_STATE;
import com.scrivenvar.service.Options;
+import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import static java.util.prefs.Preferences.userRoot;
}
+ /**
+ * This will throw IllegalArgumentException if the value exceeds the maximum
+ * preferences value length.
+ *
+ * @param key The name of the key to associate with the value.
+ * @param value The value to persist.
+ *
+ * @throws BackingStoreException New value not persisted.
+ */
@Override
- public void put( final String key, final String value ) {
- getPreferences().put( key, value );
+ public void put( final String key, final String value )
+ throws BackingStoreException {
+ getState().put( key, value );
+ getState().flush();
}
@Override
- public String get( final String key, final String defalutValue ) {
- return getPreferences().get( key, defalutValue );
+ public String get( final String key, final String value ) {
+ return getState().get( key, value );
+ }
+
+ @Override
+ public String get( final String key ) {
+ return get( key, "" );
}
src/main/java/com/scrivenvar/service/impl/DefaultSettings.java
package com.scrivenvar.service.impl;
-import static com.scrivenvar.Constants.FILE_R_STARTUP;
import static com.scrivenvar.Constants.SETTINGS_NAME;
-import com.scrivenvar.processors.InlineRProcessor;
import com.scrivenvar.service.Settings;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
-import static java.nio.charset.StandardCharsets.UTF_8;
import java.util.Iterator;
import java.util.List;
*/
public class DefaultSettings implements Settings {
+
private static final char VALUE_SEPARATOR = ',';
public int getSetting( final String property, final int defaultValue ) {
return getSettings().getInt( property, defaultValue );
+ }
+
+ /**
+ * Changes key's value. This will clear the old value before setting the new
+ * value so that the old value is erased, not changed into a list.
+ *
+ * @param key The property key name to obtain its value.
+ * @param value The new value to set.
+ */
+ @Override
+ public void putSetting( final String key, final String value ) {
+ System.out.println( "PUT: " + key + " = " + value );
+ getSettings().clearProperty( key );
+ getSettings().addProperty( key, value );
}
return configuration;
}
-
+
protected Charset getDefaultEncoding() {
return Charset.defaultCharset();
}
-
+
protected ListDelimiterHandler createListDelimiterHandler() {
return new DefaultListDelimiterHandler( VALUE_SEPARATOR );
private PropertiesConfiguration getSettings() {
return this.properties;
- }
-
- /**
- *
- * @param script Script to write file back to the settings.
- * @throws IOException Couldn't write the string back to the file.
- */
- @Override
- public void saveRStartupScript( final String script ) throws IOException {
- assert script != null;
-
- System.out.println( "Save resource: " + script );
- }
-
- /**
- * Reads the R startup script into a string, or the empty string if the file
- * could not be read (or found). The R startup file must be UTF-8.
- *
- * @return The string content for the R startup script, or empty if not found.
- * @throws IOException Could not read the R startup script.
- */
- @Override
- public String loadRStartupScript() throws IOException {
- try( final InputStream in = openResource( FILE_R_STARTUP ) ) {
- return readFully( in );
- }
- }
-
- /**
- * Opens a resource such that it can be closed using a try/finally block.
- *
- * @param path Path to the resource to open.
- *
- * @return An open input stream ready to be read.
- */
- private InputStream openResource( final String path ) {
- return InlineRProcessor.class.getResourceAsStream( path );
- }
-
- private String readFully( final InputStream inputStream ) throws IOException {
- final byte[] buffer = new byte[ 8192 ];
- final ByteArrayOutputStream result = new ByteArrayOutputStream();
-
- int length;
-
- while( (length = inputStream.read( buffer )) != -1 ) {
- result.write( buffer, 0, length );
- }
-
- return result.toString( UTF_8.name() );
}
-
}
src/main/resources/com/scrivenvar/messages.properties
#
-# Copyright 2016 Karl Tauber and White Magic Software, Ltd.
+# Copyright 2017 Karl Tauber and White Magic Software, Ltd.
#
# All rights reserved.
Definition.menu.add=Add
Definition.menu.remove=Delete
-
-# ########################################################################
-#
-# About Dialog
-#
-# ########################################################################
-
-Dialog.about.title=About
-Dialog.about.header=${Main.title}
-Dialog.about.content=Copyright 2016 White Magic Software, Ltd.\n\nBased on Markdown Writer FX by Karl Tauber
# ########################################################################
# ########################################################################
-ImageDialog.title=Image
-ImageDialog.chooser.imagesFilter=Images
-ImageDialog.previewLabel.text=Markdown Preview\:
-ImageDialog.textLabel.text=Alternate Text\:
-ImageDialog.titleLabel.text=Title (tooltip)\:
-ImageDialog.urlLabel.text=Image URL\:
+Dialog.image.title=Image
+Dialog.image.chooser.imagesFilter=Images
+Dialog.image.previewLabel.text=Markdown Preview\:
+Dialog.image.textLabel.text=Alternate Text\:
+Dialog.image.titleLabel.text=Title (tooltip)\:
+Dialog.image.urlLabel.text=Image URL\:
# ########################################################################
#
# Hyperlink
#
# ########################################################################
-LinkDialog.title=Link
-LinkDialog.previewLabel.text=Markdown Preview\:
-LinkDialog.textLabel.text=Link Text\:
-LinkDialog.titleLabel.text=Title (tooltip)\:
-LinkDialog.urlLabel.text=Link URL\:
+Dialog.link.title=Link
+Dialog.link.previewLabel.text=Markdown Preview\:
+Dialog.link.textLabel.text=Link Text\:
+Dialog.link.titleLabel.text=Title (tooltip)\:
+Dialog.link.urlLabel.text=Link URL\:
+
+# ########################################################################
+#
+# About
+#
+# ########################################################################
+
+Dialog.about.title=About
+Dialog.about.header=${Main.title}
+Dialog.about.content=Copyright 2017 White Magic Software, Ltd.\n\nBased on Markdown Writer FX by Karl Tauber
+
+# ########################################################################
+#
+# R Script
+#
+# ########################################################################
+
+Dialog.rScript.title=R Startup Script
+Dialog.rScript.content=Provide R statements to run prior to interpreting R statements embedded in the document.
# Options ################################################################
src/main/resources/com/scrivenvar/startup.R
Delta1336 lines added, 1162 lines removed, 174-line increase