| 12 | 12 | import com.keenwrite.editors.markdown.MarkdownEditor; |
| 13 | 13 | import com.keenwrite.events.*; |
| 14 | | import com.keenwrite.io.MediaType; |
| 15 | | import com.keenwrite.preferences.Workspace; |
| 16 | | import com.keenwrite.preview.HtmlPreview; |
| 17 | | import com.keenwrite.processors.HtmlPreviewProcessor; |
| 18 | | import com.keenwrite.processors.Processor; |
| 19 | | import com.keenwrite.processors.ProcessorContext; |
| 20 | | import com.keenwrite.processors.ProcessorFactory; |
| 21 | | import com.keenwrite.processors.r.Engine; |
| 22 | | import com.keenwrite.processors.r.RBootstrapController; |
| 23 | | import com.keenwrite.service.events.Notifier; |
| 24 | | import com.keenwrite.ui.explorer.FilePickerFactory; |
| 25 | | import com.keenwrite.ui.heuristics.DocumentStatistics; |
| 26 | | import com.keenwrite.ui.outline.DocumentOutline; |
| 27 | | import com.keenwrite.util.GenericBuilder; |
| 28 | | import com.panemu.tiwulfx.control.dock.DetachableTab; |
| 29 | | import com.panemu.tiwulfx.control.dock.DetachableTabPane; |
| 30 | | import javafx.application.Platform; |
| 31 | | import javafx.beans.property.*; |
| 32 | | import javafx.collections.ListChangeListener; |
| 33 | | import javafx.concurrent.Task; |
| 34 | | import javafx.event.ActionEvent; |
| 35 | | import javafx.event.Event; |
| 36 | | import javafx.event.EventHandler; |
| 37 | | import javafx.scene.Node; |
| 38 | | import javafx.scene.Scene; |
| 39 | | import javafx.scene.control.*; |
| 40 | | import javafx.scene.control.TreeItem.TreeModificationEvent; |
| 41 | | import javafx.scene.input.KeyEvent; |
| 42 | | import javafx.scene.layout.FlowPane; |
| 43 | | import javafx.stage.Stage; |
| 44 | | import javafx.stage.Window; |
| 45 | | import org.greenrobot.eventbus.Subscribe; |
| 46 | | |
| 47 | | import java.io.File; |
| 48 | | import java.io.FileNotFoundException; |
| 49 | | import java.nio.file.Path; |
| 50 | | import java.util.*; |
| 51 | | import java.util.concurrent.ExecutorService; |
| 52 | | import java.util.concurrent.ScheduledExecutorService; |
| 53 | | import java.util.concurrent.ScheduledFuture; |
| 54 | | import java.util.concurrent.atomic.AtomicBoolean; |
| 55 | | import java.util.concurrent.atomic.AtomicReference; |
| 56 | | import java.util.function.Function; |
| 57 | | import java.util.stream.Collectors; |
| 58 | | |
| 59 | | import static com.keenwrite.ExportFormat.NONE; |
| 60 | | import static com.keenwrite.Launcher.terminate; |
| 61 | | import static com.keenwrite.Messages.get; |
| 62 | | import static com.keenwrite.constants.Constants.*; |
| 63 | | import static com.keenwrite.constants.GraphicsConstants.ICON_DIALOG_NODE; |
| 64 | | import static com.keenwrite.events.Bus.register; |
| 65 | | import static com.keenwrite.events.StatusEvent.clue; |
| 66 | | import static com.keenwrite.io.MediaType.*; |
| 67 | | import static com.keenwrite.preferences.AppKeys.*; |
| 68 | | import static com.keenwrite.processors.IdentityProcessor.IDENTITY; |
| 69 | | import static com.keenwrite.processors.ProcessorContext.Mutator; |
| 70 | | import static com.keenwrite.processors.ProcessorContext.builder; |
| 71 | | import static com.keenwrite.processors.ProcessorFactory.createProcessors; |
| 72 | | import static java.lang.String.format; |
| 73 | | import static java.lang.System.getProperty; |
| 74 | | import static java.util.concurrent.Executors.newFixedThreadPool; |
| 75 | | import static java.util.concurrent.Executors.newScheduledThreadPool; |
| 76 | | import static java.util.concurrent.TimeUnit.SECONDS; |
| 77 | | import static java.util.stream.Collectors.groupingBy; |
| 78 | | import static javafx.application.Platform.runLater; |
| 79 | | import static javafx.scene.control.Alert.AlertType.ERROR; |
| 80 | | import static javafx.scene.control.ButtonType.*; |
| 81 | | import static javafx.scene.control.TabPane.TabClosingPolicy.ALL_TABS; |
| 82 | | import static javafx.scene.input.KeyCode.SPACE; |
| 83 | | import static javafx.scene.input.KeyCombination.CONTROL_DOWN; |
| 84 | | import static javafx.util.Duration.millis; |
| 85 | | import static javax.swing.SwingUtilities.invokeLater; |
| 86 | | import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed; |
| 87 | | |
| 88 | | /** |
| 89 | | * Responsible for wiring together the main application components for a |
| 90 | | * particular {@link Workspace} (project). These include the definition views, |
| 91 | | * text editors, and preview pane along with any corresponding controllers. |
| 92 | | */ |
| 93 | | public final class MainPane extends SplitPane { |
| 94 | | |
| 95 | | private static final ExecutorService sExecutor = newFixedThreadPool( 1 ); |
| 96 | | private static final Notifier sNotifier = Services.load( Notifier.class ); |
| 97 | | |
| 98 | | /** |
| 99 | | * Used when opening files to determine how each file should be binned and |
| 100 | | * therefore what tab pane to be opened within. |
| 101 | | */ |
| 102 | | private static final Set<MediaType> PLAIN_TEXT_FORMAT = Set.of( |
| 103 | | TEXT_MARKDOWN, TEXT_R_MARKDOWN, UNDEFINED |
| 104 | | ); |
| 105 | | |
| 106 | | private final ScheduledExecutorService mSaver = newScheduledThreadPool( 1 ); |
| 107 | | private final AtomicReference<ScheduledFuture<?>> mSaveTask = |
| 108 | | new AtomicReference<>(); |
| 109 | | |
| 110 | | /** |
| 111 | | * Prevents re-instantiation of processing classes. |
| 112 | | */ |
| 113 | | private final Map<TextResource, Processor<String>> mProcessors = |
| 114 | | new HashMap<>(); |
| 115 | | |
| 116 | | private final Workspace mWorkspace; |
| 117 | | |
| 118 | | /** |
| 119 | | * Groups similar file type tabs together. |
| 120 | | */ |
| 121 | | private final List<TabPane> mTabPanes = new ArrayList<>(); |
| 122 | | |
| 123 | | /** |
| 124 | | * Renders the actively selected plain text editor tab. |
| 125 | | */ |
| 126 | | private final HtmlPreview mPreview; |
| 127 | | |
| 128 | | /** |
| 129 | | * Provides an interactive document outline. |
| 130 | | */ |
| 131 | | private final DocumentOutline mOutline = new DocumentOutline(); |
| 132 | | |
| 133 | | /** |
| 134 | | * Changing the active editor fires the value changed event. This allows |
| 135 | | * refreshes to happen when external definitions are modified and need to |
| 136 | | * trigger the processing chain. |
| 137 | | */ |
| 138 | | private final ObjectProperty<TextEditor> mTextEditor = |
| 139 | | createActiveTextEditor(); |
| 140 | | |
| 141 | | /** |
| 142 | | * Changing the active definition editor fires the value changed event. This |
| 143 | | * allows refreshes to happen when external definitions are modified and need |
| 144 | | * to trigger the processing chain. |
| 145 | | */ |
| 146 | | private final ObjectProperty<TextDefinition> mDefinitionEditor; |
| 147 | | |
| 148 | | /** |
| 149 | | * Called when the definition data is changed. |
| 150 | | */ |
| 151 | | private final EventHandler<TreeModificationEvent<Event>> mTreeHandler = |
| 152 | | event -> { |
| 153 | | process( getTextEditor() ); |
| 154 | | save( getTextDefinition() ); |
| 155 | | }; |
| 156 | | |
| 157 | | /** |
| 158 | | * Tracks the number of detached tab panels opened into their own windows, |
| 159 | | * which allows unique identification of subordinate windows by their title. |
| 160 | | * It is doubtful more than 128 windows, much less 256, will be created. |
| 161 | | */ |
| 162 | | private byte mWindowCount; |
| 163 | | |
| 164 | | private final VariableNameInjector mVariableNameInjector; |
| 165 | | |
| 166 | | private final RBootstrapController mRBootstrapController; |
| 167 | | |
| 168 | | private final DocumentStatistics mStatistics; |
| 169 | | |
| 170 | | /** |
| 171 | | * Adds all content panels to the main user interface. This will load the |
| 172 | | * configuration settings from the workspace to reproduce the settings from |
| 173 | | * a previous session. |
| 174 | | */ |
| 175 | | public MainPane( final Workspace workspace ) { |
| 176 | | mWorkspace = workspace; |
| 177 | | mPreview = new HtmlPreview( workspace ); |
| 178 | | mStatistics = new DocumentStatistics( workspace ); |
| 179 | | mTextEditor.set( new MarkdownEditor( workspace ) ); |
| 180 | | mDefinitionEditor = createActiveDefinitionEditor( mTextEditor ); |
| 181 | | mVariableNameInjector = new VariableNameInjector( mWorkspace ); |
| 182 | | mRBootstrapController = new RBootstrapController( |
| 183 | | mWorkspace, this::getDefinitions ); |
| 184 | | |
| 185 | | open( collect( getRecentFiles() ) ); |
| 186 | | viewPreview(); |
| 187 | | setDividerPositions( calculateDividerPositions() ); |
| 188 | | |
| 189 | | // Once the main scene's window regains focus, update the active definition |
| 190 | | // editor to the currently selected tab. |
| 191 | | runLater( () -> getWindow().setOnCloseRequest( event -> { |
| 192 | | // Order matters: Open file names must be persisted before closing all. |
| 193 | | mWorkspace.save(); |
| 194 | | |
| 195 | | if( closeAll() ) { |
| 196 | | Platform.exit(); |
| 197 | | terminate( 0 ); |
| 198 | | } |
| 199 | | |
| 200 | | event.consume(); |
| 201 | | } ) ); |
| 202 | | |
| 203 | | register( this ); |
| 204 | | initAutosave( workspace ); |
| 205 | | |
| 206 | | restoreSession(); |
| 207 | | runLater( this::restoreFocus ); |
| 208 | | } |
| 209 | | |
| 210 | | @Subscribe |
| 211 | | public void handle( final TextEditorFocusEvent event ) { |
| 212 | | mTextEditor.set( event.get() ); |
| 213 | | } |
| 214 | | |
| 215 | | @Subscribe |
| 216 | | public void handle( final TextDefinitionFocusEvent event ) { |
| 217 | | mDefinitionEditor.set( event.get() ); |
| 218 | | } |
| 219 | | |
| 220 | | /** |
| 221 | | * Typically called when a file name is clicked in the preview panel. |
| 222 | | * |
| 223 | | * @param event The event to process, must contain a valid file reference. |
| 224 | | */ |
| 225 | | @Subscribe |
| 226 | | public void handle( final FileOpenEvent event ) { |
| 227 | | final File eventFile; |
| 228 | | final var eventUri = event.getUri(); |
| 229 | | |
| 230 | | if( eventUri.isAbsolute() ) { |
| 231 | | eventFile = new File( eventUri.getPath() ); |
| 232 | | } |
| 233 | | else { |
| 234 | | final var activeFile = getTextEditor().getFile(); |
| 235 | | final var parent = activeFile.getParentFile(); |
| 236 | | |
| 237 | | if( parent == null ) { |
| 238 | | clue( new FileNotFoundException( eventUri.getPath() ) ); |
| 239 | | return; |
| 240 | | } |
| 241 | | else { |
| 242 | | final var parentPath = parent.getAbsolutePath(); |
| 243 | | eventFile = Path.of( parentPath, eventUri.getPath() ).toFile(); |
| 244 | | } |
| 245 | | } |
| 246 | | |
| 247 | | runLater( () -> open( eventFile ) ); |
| 248 | | } |
| 249 | | |
| 250 | | @Subscribe |
| 251 | | public void handle( final CaretNavigationEvent event ) { |
| 252 | | runLater( () -> { |
| 253 | | final var textArea = getTextEditor(); |
| 254 | | textArea.moveTo( event.getOffset() ); |
| 255 | | textArea.requestFocus(); |
| 256 | | } ); |
| 257 | | } |
| 258 | | |
| 259 | | @Subscribe |
| 260 | | @SuppressWarnings( "unused" ) |
| 261 | | public void handle( final ExportFailedEvent event ) { |
| 262 | | final var os = getProperty( "os.name" ); |
| 263 | | final var arch = getProperty( "os.arch" ).toLowerCase(); |
| 264 | | final var bits = getProperty( "sun.arch.data.model" ); |
| 265 | | |
| 266 | | final var title = Messages.get( "Alert.typesetter.missing.title" ); |
| 267 | | final var header = Messages.get( "Alert.typesetter.missing.header" ); |
| 268 | | final var version = Messages.get( |
| 269 | | "Alert.typesetter.missing.version", |
| 270 | | os, |
| 271 | | arch |
| 272 | | .replaceAll( "amd.*|i.*|x86.*", "X86" ) |
| 273 | | .replaceAll( "mips.*", "MIPS" ) |
| 274 | | .replaceAll( "armv.*", "ARM" ), |
| 275 | | bits ); |
| 276 | | final var text = Messages.get( "Alert.typesetter.missing.installer.text" ); |
| 277 | | |
| 278 | | // Download and install ConTeXt for {0} {1} {2}-bit |
| 279 | | final var content = format( "%s %s", text, version ); |
| 280 | | final var flowPane = new FlowPane(); |
| 281 | | final var link = new Hyperlink( text ); |
| 282 | | final var label = new Label( version ); |
| 283 | | flowPane.getChildren().addAll( link, label ); |
| 284 | | |
| 285 | | final var alert = new Alert( ERROR, content, OK ); |
| 286 | | alert.setTitle( title ); |
| 287 | | alert.setHeaderText( header ); |
| 288 | | alert.getDialogPane().contentProperty().set( flowPane ); |
| 289 | | alert.setGraphic( ICON_DIALOG_NODE ); |
| 290 | | |
| 291 | | link.setOnAction( e -> { |
| 292 | | alert.close(); |
| 293 | | final var url = Messages.get( "Alert.typesetter.missing.installer.url" ); |
| 294 | | runLater( () -> HyperlinkOpenEvent.fire( url ) ); |
| 295 | | } ); |
| 296 | | |
| 297 | | alert.showAndWait(); |
| 298 | | } |
| 299 | | |
| 300 | | @Subscribe |
| 301 | | public void handle( final InsertDefinitionEvent<String> event ) { |
| 302 | | final var leaf = event.getLeaf(); |
| 303 | | final var editor = mTextEditor.get(); |
| 304 | | |
| 305 | | mVariableNameInjector.insert( editor, leaf ); |
| 306 | | } |
| 307 | | |
| 308 | | private void initAutosave( final Workspace workspace ) { |
| 309 | | final var rate = workspace.integerProperty( KEY_EDITOR_AUTOSAVE ); |
| 310 | | |
| 311 | | rate.addListener( |
| 312 | | ( c, o, n ) -> { |
| 313 | | final var taskRef = mSaveTask.get(); |
| 314 | | |
| 315 | | // Prevent multiple autosaves from running. |
| 316 | | if( taskRef != null ) { |
| 317 | | taskRef.cancel( false ); |
| 318 | | } |
| 319 | | |
| 320 | | initAutosave( rate ); |
| 321 | | } |
| 322 | | ); |
| 323 | | |
| 324 | | // Start the save listener (avoids duplicating some code). |
| 325 | | initAutosave( rate ); |
| 326 | | } |
| 327 | | |
| 328 | | private void initAutosave( final IntegerProperty rate ) { |
| 329 | | mSaveTask.set( |
| 330 | | mSaver.scheduleAtFixedRate( |
| 331 | | () -> { |
| 332 | | if( getTextEditor().isModified() ) { |
| 333 | | // Ensure the modified indicator is cleared by running on EDT. |
| 334 | | runLater( this::save ); |
| 335 | | } |
| 336 | | }, 0, rate.intValue(), SECONDS |
| 337 | | ) |
| 338 | | ); |
| 339 | | } |
| 340 | | |
| 341 | | /** |
| 342 | | * TODO: Load divider positions from exported settings, see |
| 343 | | * {@link #collect(SetProperty)} comment. |
| 344 | | */ |
| 345 | | private double[] calculateDividerPositions() { |
| 346 | | final var ratio = 100f / getItems().size() / 100; |
| 347 | | final var positions = getDividerPositions(); |
| 348 | | |
| 349 | | for( int i = 0; i < positions.length; i++ ) { |
| 350 | | positions[ i ] = ratio * i; |
| 351 | | } |
| 352 | | |
| 353 | | return positions; |
| 354 | | } |
| 355 | | |
| 356 | | /** |
| 357 | | * Opens all the files into the application, provided the paths are unique. |
| 358 | | * This may only be called for any type of files that a user can edit |
| 359 | | * (i.e., update and persist), such as definitions and text files. |
| 360 | | * |
| 361 | | * @param files The list of files to open. |
| 362 | | */ |
| 363 | | public void open( final List<File> files ) { |
| 364 | | files.forEach( this::open ); |
| 365 | | } |
| 366 | | |
| 367 | | /** |
| 368 | | * This opens the given file. Since the preview pane is not a file that |
| 369 | | * can be opened, it is safe to add a listener to the detachable pane. |
| 370 | | * This will exit early if the given file is not a regular file (i.e., a |
| 371 | | * directory). |
| 372 | | * |
| 373 | | * @param inputFile The file to open. |
| 374 | | */ |
| 375 | | private void open( final File inputFile ) { |
| 376 | | // Prevent opening directories (a non-existent "untitled.md" is fine). |
| 377 | | if( !inputFile.isFile() && inputFile.exists() ) { |
| 378 | | return; |
| 379 | | } |
| 380 | | |
| 381 | | final var tab = createTab( inputFile ); |
| 382 | | final var node = tab.getContent(); |
| 383 | | final var mediaType = MediaType.valueFrom( inputFile ); |
| 384 | | final var tabPane = obtainTabPane( mediaType ); |
| 385 | | |
| 386 | | tab.setTooltip( createTooltip( inputFile ) ); |
| 387 | | tabPane.setFocusTraversable( false ); |
| 388 | | tabPane.setTabClosingPolicy( ALL_TABS ); |
| 389 | | tabPane.getTabs().add( tab ); |
| 390 | | |
| 391 | | // Attach the tab scene factory for new tab panes. |
| 392 | | if( !getItems().contains( tabPane ) ) { |
| 393 | | addTabPane( |
| 394 | | node instanceof TextDefinition ? 0 : getItems().size(), tabPane |
| 395 | | ); |
| 396 | | } |
| 397 | | |
| 398 | | if( inputFile.isFile() ) { |
| 399 | | getRecentFiles().add( inputFile.getAbsolutePath() ); |
| 400 | | } |
| 401 | | } |
| 402 | | |
| 403 | | /** |
| 404 | | * Gives focus to the most recently edited document and attempts to move |
| 405 | | * the caret to the most recently known offset into said document. |
| 406 | | */ |
| 407 | | private void restoreSession() { |
| 408 | | final var workspace = getWorkspace(); |
| 409 | | final var file = workspace.fileProperty( KEY_UI_RECENT_DOCUMENT ); |
| 410 | | final var offset = workspace.integerProperty( KEY_UI_RECENT_OFFSET ); |
| 411 | | |
| 412 | | for( final var pane : mTabPanes ) { |
| 413 | | for( final var tab : pane.getTabs() ) { |
| 414 | | final var tooltip = tab.getTooltip(); |
| 415 | | |
| 416 | | if( tooltip != null ) { |
| 417 | | final var tabName = tooltip.getText(); |
| 418 | | final var fileName = file.getValue().toString(); |
| 419 | | |
| 420 | | if( tabName.equalsIgnoreCase( fileName ) ) { |
| 421 | | final var node = tab.getContent(); |
| 422 | | |
| 423 | | pane.getSelectionModel().select( tab ); |
| 424 | | node.requestFocus(); |
| 425 | | |
| 426 | | if( node instanceof TextEditor editor ) { |
| 427 | | editor.moveTo( offset.getValue() ); |
| 428 | | } |
| 429 | | |
| 430 | | break; |
| 431 | | } |
| 432 | | } |
| 433 | | } |
| 434 | | } |
| 435 | | } |
| 436 | | |
| 437 | | /** |
| 438 | | * Sets the focus to the middle pane, which contains the text editor tabs. |
| 439 | | */ |
| 440 | | private void restoreFocus() { |
| 441 | | // Work around a bug where focusing directly on the middle pane results |
| 442 | | // in the R engine not loading variables properly. |
| 443 | | mTabPanes.get( 0 ).requestFocus(); |
| 444 | | |
| 445 | | // This is the only line that should be required. |
| 446 | | mTabPanes.get( 1 ).requestFocus(); |
| 447 | | } |
| 448 | | |
| 449 | | /** |
| 450 | | * Opens a new text editor document using the default document file name. |
| 451 | | */ |
| 452 | | public void newTextEditor() { |
| 453 | | open( DOCUMENT_DEFAULT ); |
| 454 | | } |
| 455 | | |
| 456 | | /** |
| 457 | | * Opens a new definition editor document using the default definition |
| 458 | | * file name. |
| 459 | | */ |
| 460 | | public void newDefinitionEditor() { |
| 461 | | open( DEFINITION_DEFAULT ); |
| 462 | | } |
| 463 | | |
| 464 | | /** |
| 465 | | * Iterates over all tab panes to find all {@link TextEditor}s and request |
| 466 | | * that they save themselves. |
| 467 | | */ |
| 468 | | public void saveAll() { |
| 469 | | mTabPanes.forEach( |
| 470 | | tp -> tp.getTabs().forEach( tab -> { |
| 471 | | final var node = tab.getContent(); |
| 472 | | |
| 473 | | if( node instanceof final TextEditor editor ) { |
| 474 | | save( editor ); |
| 475 | | } |
| 476 | | } ) |
| 477 | | ); |
| 478 | | } |
| 479 | | |
| 480 | | /** |
| 481 | | * Requests that the active {@link TextEditor} saves itself. Don't bother |
| 482 | | * checking if modified first because if the user swaps external media from |
| 483 | | * an external source (e.g., USB thumb drive), save should not second-guess |
| 484 | | * the user: save always re-saves. Also, it's less code. |
| 485 | | */ |
| 486 | | public void save() { |
| 487 | | save( getTextEditor() ); |
| 488 | | } |
| 489 | | |
| 490 | | /** |
| 491 | | * Saves the active {@link TextEditor} under a new name. |
| 492 | | * |
| 493 | | * @param files The new active editor {@link File} reference, must contain |
| 494 | | * at least one element. |
| 495 | | */ |
| 496 | | public void saveAs( final List<File> files ) { |
| 497 | | assert files != null; |
| 498 | | assert !files.isEmpty(); |
| 499 | | final var editor = getTextEditor(); |
| 500 | | final var tab = getTab( editor ); |
| 501 | | final var file = files.get( 0 ); |
| 502 | | |
| 503 | | editor.rename( file ); |
| 504 | | tab.ifPresent( t -> { |
| 505 | | t.setText( editor.getFilename() ); |
| 506 | | t.setTooltip( createTooltip( file ) ); |
| 507 | | } ); |
| 508 | | |
| 509 | | save(); |
| 510 | | } |
| 511 | | |
| 512 | | /** |
| 513 | | * Saves the given {@link TextResource} to a file. This is typically used |
| 514 | | * to save either an instance of {@link TextEditor} or {@link TextDefinition}. |
| 515 | | * |
| 516 | | * @param resource The resource to export. |
| 517 | | */ |
| 518 | | private void save( final TextResource resource ) { |
| 519 | | try { |
| 520 | | resource.save(); |
| 521 | | } catch( final Exception ex ) { |
| 522 | | clue( ex ); |
| 523 | | sNotifier.alert( |
| 524 | | getWindow(), resource.getPath(), "TextResource.saveFailed", ex |
| 525 | | ); |
| 526 | | } |
| 527 | | } |
| 528 | | |
| 529 | | /** |
| 530 | | * Closes all open {@link TextEditor}s; all {@link TextDefinition}s stay open. |
| 531 | | * |
| 532 | | * @return {@code true} when all editors, modified or otherwise, were |
| 533 | | * permitted to close; {@code false} when one or more editors were modified |
| 534 | | * and the user requested no closing. |
| 535 | | */ |
| 536 | | public boolean closeAll() { |
| 537 | | var closable = true; |
| 538 | | |
| 539 | | for( final var tabPane : mTabPanes ) { |
| 540 | | final var tabIterator = tabPane.getTabs().iterator(); |
| 541 | | |
| 542 | | while( tabIterator.hasNext() ) { |
| 543 | | final var tab = tabIterator.next(); |
| 544 | | final var resource = tab.getContent(); |
| 545 | | |
| 546 | | // The definition panes auto-save, so being specific here prevents |
| 547 | | // closing the definitions in the situation where the user wants to |
| 548 | | // continue editing (i.e., possibly save unsaved work). |
| 549 | | if( !(resource instanceof TextEditor) ) { |
| 550 | | continue; |
| 551 | | } |
| 552 | | |
| 553 | | if( canClose( (TextEditor) resource ) ) { |
| 554 | | tabIterator.remove(); |
| 555 | | close( tab ); |
| 556 | | } |
| 557 | | else { |
| 558 | | closable = false; |
| 559 | | } |
| 560 | | } |
| 561 | | } |
| 562 | | |
| 563 | | return closable; |
| 564 | | } |
| 565 | | |
| 566 | | /** |
| 567 | | * Calls the tab's {@link Tab#getOnClosed()} handler to carry out a close |
| 568 | | * event. |
| 569 | | * |
| 570 | | * @param tab The {@link Tab} that was closed. |
| 571 | | */ |
| 572 | | private void close( final Tab tab ) { |
| 573 | | assert tab != null; |
| 574 | | |
| 575 | | final var handler = tab.getOnClosed(); |
| 576 | | |
| 577 | | if( handler != null ) { |
| 578 | | handler.handle( new ActionEvent() ); |
| 579 | | } |
| 580 | | } |
| 581 | | |
| 582 | | /** |
| 583 | | * Closes the active tab; delegates to {@link #canClose(TextResource)}. |
| 584 | | */ |
| 585 | | public void close() { |
| 586 | | final var editor = getTextEditor(); |
| 587 | | |
| 588 | | if( canClose( editor ) ) { |
| 589 | | close( editor ); |
| 590 | | } |
| 591 | | } |
| 592 | | |
| 593 | | /** |
| 594 | | * Closes the given {@link TextResource}. This must not be called from within |
| 595 | | * a loop that iterates over the tab panes using {@code forEach}, lest a |
| 596 | | * concurrent modification exception be thrown. |
| 597 | | * |
| 598 | | * @param resource The {@link TextResource} to close, without confirming with |
| 599 | | * the user. |
| 600 | | */ |
| 601 | | private void close( final TextResource resource ) { |
| 602 | | getTab( resource ).ifPresent( |
| 603 | | tab -> { |
| 604 | | close( tab ); |
| 605 | | tab.getTabPane().getTabs().remove( tab ); |
| 606 | | } |
| 607 | | ); |
| 608 | | } |
| 609 | | |
| 610 | | /** |
| 611 | | * Answers whether the given {@link TextResource} may be closed. |
| 612 | | * |
| 613 | | * @param editor The {@link TextResource} to try closing. |
| 614 | | * @return {@code true} when the editor may be closed; {@code false} when |
| 615 | | * the user has requested to keep the editor open. |
| 616 | | */ |
| 617 | | private boolean canClose( final TextResource editor ) { |
| 618 | | final var editorTab = getTab( editor ); |
| 619 | | final var canClose = new AtomicBoolean( true ); |
| 620 | | |
| 621 | | if( editor.isModified() ) { |
| 622 | | final var filename = new StringBuilder(); |
| 623 | | editorTab.ifPresent( tab -> filename.append( tab.getText() ) ); |
| 624 | | |
| 625 | | final var message = sNotifier.createNotification( |
| 626 | | Messages.get( "Alert.file.close.title" ), |
| 627 | | Messages.get( "Alert.file.close.text" ), |
| 628 | | filename.toString() |
| 629 | | ); |
| 630 | | |
| 631 | | final var dialog = sNotifier.createConfirmation( getWindow(), message ); |
| 632 | | |
| 633 | | dialog.showAndWait().ifPresent( |
| 634 | | save -> canClose.set( save == YES ? editor.save() : save == NO ) |
| 635 | | ); |
| 636 | | } |
| 637 | | |
| 638 | | return canClose.get(); |
| 639 | | } |
| 640 | | |
| 641 | | private ObjectProperty<TextEditor> createActiveTextEditor() { |
| 642 | | final var editor = new SimpleObjectProperty<TextEditor>(); |
| 643 | | |
| 644 | | editor.addListener( ( c, o, n ) -> { |
| 645 | | if( n != null ) { |
| 646 | | mPreview.setBaseUri( n.getPath() ); |
| 647 | | process( n ); |
| 648 | | } |
| 649 | | } ); |
| 650 | | |
| 651 | | return editor; |
| 652 | | } |
| 653 | | |
| 654 | | /** |
| 655 | | * Adds the HTML preview tab to its own, singular tab pane. |
| 656 | | */ |
| 657 | | public void viewPreview() { |
| 658 | | viewTab( mPreview, TEXT_HTML, "Pane.preview.title" ); |
| 659 | | } |
| 660 | | |
| 661 | | /** |
| 662 | | * Adds the document outline tab to its own, singular tab pane. |
| 663 | | */ |
| 664 | | public void viewOutline() { |
| 665 | | viewTab( mOutline, APP_DOCUMENT_OUTLINE, "Pane.outline.title" ); |
| 666 | | } |
| 667 | | |
| 668 | | public void viewStatistics() { |
| 669 | | viewTab( mStatistics, APP_DOCUMENT_STATISTICS, "Pane.statistics.title" ); |
| 670 | | } |
| 671 | | |
| 672 | | public void viewFiles() { |
| 673 | | try { |
| 674 | | final var factory = new FilePickerFactory( getWorkspace() ); |
| 675 | | final var fileManager = factory.createModeless(); |
| 676 | | viewTab( fileManager, APP_FILE_MANAGER, "Pane.files.title" ); |
| 677 | | } catch( final Exception ex ) { |
| 678 | | clue( ex ); |
| 679 | | } |
| 680 | | } |
| 681 | | |
| 682 | | private void viewTab( |
| 683 | | final Node node, final MediaType mediaType, final String key ) { |
| 684 | | final var tabPane = obtainTabPane( mediaType ); |
| 685 | | |
| 686 | | for( final var tab : tabPane.getTabs() ) { |
| 687 | | if( tab.getContent() == node ) { |
| 688 | | return; |
| 689 | | } |
| 690 | | } |
| 691 | | |
| 692 | | tabPane.getTabs().add( createTab( get( key ), node ) ); |
| 693 | | addTabPane( tabPane ); |
| 694 | | } |
| 695 | | |
| 696 | | public void viewRefresh() { |
| 697 | | mPreview.refresh(); |
| 698 | | Engine.clear(); |
| 699 | | mRBootstrapController.update(); |
| 700 | | } |
| 701 | | |
| 702 | | /** |
| 703 | | * Returns the tab that contains the given {@link TextEditor}. |
| 704 | | * |
| 705 | | * @param editor The {@link TextEditor} instance to find amongst the tabs. |
| 706 | | * @return The first tab having content that matches the given tab. |
| 707 | | */ |
| 708 | | private Optional<Tab> getTab( final TextResource editor ) { |
| 709 | | return mTabPanes.stream() |
| 710 | | .flatMap( pane -> pane.getTabs().stream() ) |
| 711 | | .filter( tab -> editor.equals( tab.getContent() ) ) |
| 712 | | .findFirst(); |
| 713 | | } |
| 714 | | |
| 715 | | /** |
| 716 | | * Creates a new {@link DefinitionEditor} wrapped in a listener that |
| 717 | | * is used to detect when the active {@link DefinitionEditor} has changed. |
| 718 | | * Upon changing, the variables are interpolated and the active text editor |
| 719 | | * is refreshed. |
| 720 | | * |
| 721 | | * @param textEditor Text editor to update with the revised resolved map. |
| 722 | | * @return A newly configured property that represents the active |
| 723 | | * {@link DefinitionEditor}, never null. |
| 724 | | */ |
| 725 | | private ObjectProperty<TextDefinition> createActiveDefinitionEditor( |
| 726 | | final ObjectProperty<TextEditor> textEditor ) { |
| 727 | | final var defEditor = new SimpleObjectProperty<>( |
| 728 | | createDefinitionEditor() |
| 729 | | ); |
| 730 | | |
| 731 | | defEditor.addListener( ( c, o, n ) -> { |
| 732 | | final var editor = textEditor.get(); |
| 733 | | |
| 734 | | if( editor.isMediaType( TEXT_R_MARKDOWN ) ) { |
| 735 | | // Initialize R before the editor is added. |
| 736 | | mRBootstrapController.update(); |
| 737 | | } |
| 738 | | |
| 739 | | process( editor ); |
| 740 | | } ); |
| 741 | | |
| 742 | | return defEditor; |
| 743 | | } |
| 744 | | |
| 745 | | private Tab createTab( final String filename, final Node node ) { |
| 746 | | return new DetachableTab( filename, node ); |
| 747 | | } |
| 748 | | |
| 749 | | private Tab createTab( final File file ) { |
| 750 | | final var r = createTextResource( file ); |
| 751 | | final var tab = createTab( r.getFilename(), r.getNode() ); |
| 752 | | |
| 753 | | r.modifiedProperty().addListener( |
| 754 | | ( c, o, n ) -> tab.setText( r.getFilename() + (n ? "*" : "") ) |
| 755 | | ); |
| 756 | | |
| 757 | | // This is called when either the tab is closed by the user clicking on |
| 758 | | // the tab's close icon or when closing (all) from the file menu. |
| 759 | | tab.setOnClosed( |
| 760 | | __ -> getRecentFiles().remove( file.getAbsolutePath() ) |
| 761 | | ); |
| 762 | | |
| 763 | | // When closing a tab, give focus to the newly revealed tab. |
| 764 | | tab.selectedProperty().addListener( ( c, o, n ) -> { |
| 765 | | if( n != null && n ) { |
| 766 | | final var pane = tab.getTabPane(); |
| 767 | | |
| 768 | | if( pane != null ) { |
| 769 | | pane.requestFocus(); |
| 770 | | } |
| 771 | | } |
| 772 | | } ); |
| 773 | | |
| 774 | | tab.tabPaneProperty().addListener( ( cPane, oPane, nPane ) -> { |
| 775 | | if( nPane != null ) { |
| 776 | | nPane.focusedProperty().addListener( ( c, o, n ) -> { |
| 777 | | if( n != null && n ) { |
| 778 | | final var selected = nPane.getSelectionModel().getSelectedItem(); |
| 779 | | final var node = selected.getContent(); |
| 780 | | node.requestFocus(); |
| 781 | | } |
| 782 | | } ); |
| 783 | | } |
| 784 | | } ); |
| 785 | | |
| 786 | | return tab; |
| 787 | | } |
| 788 | | |
| 789 | | /** |
| 790 | | * Creates bins for the different {@link MediaType}s, which eventually are |
| 791 | | * added to the UI as separate tab panes. If ever a general-purpose scene |
| 792 | | * exporter is developed to serialize a scene to an FXML file, this could |
| 793 | | * be replaced by such a class. |
| 794 | | * <p> |
| 795 | | * When binning the files, this makes sure that at least one file exists |
| 796 | | * for every type. If the user has opted to close a particular type (such |
| 797 | | * as the definition pane), the view will suppressed elsewhere. |
| 798 | | * </p> |
| 799 | | * <p> |
| 800 | | * The order that the binned files are returned will be reflected in the |
| 801 | | * order that the corresponding panes are rendered in the UI. |
| 802 | | * </p> |
| 803 | | * |
| 804 | | * @param paths The file paths to bin according to their type. |
| 805 | | * @return An in-order list of files, first by structured definition files, |
| 806 | | * then by plain text documents. |
| 807 | | */ |
| 808 | | private List<File> collect( final SetProperty<String> paths ) { |
| 809 | | // Treat all files destined for the text editor as plain text documents |
| 810 | | // so that they are added to the same pane. Grouping by TEXT_PLAIN is a |
| 811 | | // bit arbitrary, but means explicitly capturing TEXT_PLAIN isn't needed. |
| 812 | | final Function<MediaType, MediaType> bin = |
| 813 | | m -> PLAIN_TEXT_FORMAT.contains( m ) ? TEXT_PLAIN : m; |
| 814 | | |
| 815 | | // Create two groups: YAML files and plain text files. The order that |
| 816 | | // the elements are listed in the enumeration for media types determines |
| 817 | | // what files are loaded first. Variable definitions come before all other |
| 818 | | // plain text documents. |
| 819 | | final var bins = paths |
| 820 | | .stream() |
| 821 | | .collect( |
| 822 | | groupingBy( |
| 823 | | path -> bin.apply( MediaType.fromFilename( path ) ), |
| 824 | | () -> new TreeMap<>( Enum::compareTo ), |
| 825 | | Collectors.toList() |
| 826 | | ) |
| 827 | | ); |
| 828 | | |
| 829 | | bins.putIfAbsent( TEXT_YAML, List.of( DEFINITION_DEFAULT.toString() ) ); |
| 830 | | bins.putIfAbsent( TEXT_PLAIN, List.of( DOCUMENT_DEFAULT.toString() ) ); |
| 831 | | |
| 832 | | final var result = new LinkedList<File>(); |
| 833 | | |
| 834 | | // Ensure that the same types are listed together (keep insertion order). |
| 835 | | bins.forEach( ( mediaType, files ) -> result.addAll( |
| 836 | | files.stream().map( File::new ).toList() ) |
| 837 | | ); |
| 838 | | |
| 839 | | return result; |
| 840 | | } |
| 841 | | |
| 842 | | /** |
| 843 | | * Force the active editor to update, which will cause the processor |
| 844 | | * to re-evaluate the interpolated definition map thereby updating the |
| 845 | | * preview pane. |
| 846 | | * |
| 847 | | * @param editor Contains the source document to update in the preview pane. |
| 848 | | */ |
| 849 | | private void process( final TextEditor editor ) { |
| 850 | | // Ensure processing does not run on the JavaFX thread, which frees the |
| 851 | | // text editor immediately for caret movement. The preview will have a |
| 852 | | // slight delay when catching up to the caret position. |
| 853 | | final var task = new Task<Void>() { |
| 854 | | @Override |
| 855 | | public Void call() { |
| 856 | | try { |
| 857 | | final var p = mProcessors.getOrDefault( editor, IDENTITY ); |
| 858 | | p.apply( editor == null ? "" : editor.getText() ); |
| 859 | | } catch( final Exception ex ) { |
| 860 | | clue( ex ); |
| 861 | | } |
| 862 | | |
| 863 | | return null; |
| 864 | | } |
| 865 | | }; |
| 866 | | |
| 867 | | // TODO: Each time the editor successfully runs the processor the task is |
| 868 | | // considered successful. Due to the rapid-fire nature of processing |
| 869 | | // (e.g., keyboard navigation, fast typing), it isn't necessary to |
| 870 | | // scroll each time. |
| 871 | | // The algorithm: |
| 872 | | // 1. Peek at the oldest time. |
| 873 | | // 2. If the difference between the oldest time and current time exceeds |
| 874 | | // 250 milliseconds, then invoke the scrolling. |
| 875 | | // 3. Insert the current time into the circular queue. |
| 876 | | task.setOnSucceeded( |
| 877 | | e -> invokeLater( () -> mPreview.scrollTo( CARET_ID ) ) |
| 878 | | ); |
| 879 | | |
| 880 | | // Prevents multiple process requests from executing simultaneously (due |
| 881 | | // to having a restricted queue size). |
| 882 | | sExecutor.execute( task ); |
| 883 | | } |
| 884 | | |
| 885 | | /** |
| 886 | | * Lazily creates a {@link TabPane} configured to listen for tab select |
| 887 | | * events. The tab pane is associated with a given media type so that |
| 888 | | * similar files can be grouped together. |
| 889 | | * |
| 890 | | * @param mediaType The media type to associate with the tab pane. |
| 891 | | * @return An instance of {@link TabPane} that will handle tab docking. |
| 892 | | */ |
| 893 | | private TabPane obtainTabPane( final MediaType mediaType ) { |
| 894 | | for( final var pane : mTabPanes ) { |
| 895 | | for( final var tab : pane.getTabs() ) { |
| 896 | | final var node = tab.getContent(); |
| 897 | | |
| 898 | | if( node instanceof TextResource r && r.supports( mediaType ) ) { |
| 899 | | return pane; |
| 900 | | } |
| 901 | | } |
| 902 | | } |
| 903 | | |
| 904 | | final var pane = createTabPane(); |
| 905 | | mTabPanes.add( pane ); |
| 906 | | return pane; |
| 907 | | } |
| 908 | | |
| 909 | | /** |
| 910 | | * Creates an initialized {@link TabPane} instance. |
| 911 | | * |
| 912 | | * @return A new {@link TabPane} with all listeners configured. |
| 913 | | */ |
| 914 | | private TabPane createTabPane() { |
| 915 | | final var tabPane = new DetachableTabPane(); |
| 916 | | |
| 917 | | initStageOwnerFactory( tabPane ); |
| 918 | | initTabListener( tabPane ); |
| 919 | | |
| 920 | | return tabPane; |
| 921 | | } |
| 922 | | |
| 923 | | /** |
| 924 | | * When any {@link DetachableTabPane} is detached from the main window, |
| 925 | | * the stage owner factory must be given its parent window, which will |
| 926 | | * own the child window. The parent window is the {@link MainPane}'s |
| 927 | | * {@link Scene}'s {@link Window} instance. |
| 928 | | * |
| 929 | | * <p> |
| 930 | | * This will derives the new title from the main window title, incrementing |
| 931 | | * the window count to help uniquely identify the child windows. |
| 932 | | * </p> |
| 933 | | * |
| 934 | | * @param tabPane A new {@link DetachableTabPane} to configure. |
| 935 | | */ |
| 936 | | private void initStageOwnerFactory( final DetachableTabPane tabPane ) { |
| 937 | | tabPane.setStageOwnerFactory( stage -> { |
| 938 | | final var title = get( |
| 939 | | "Detach.tab.title", |
| 940 | | ((Stage) getWindow()).getTitle(), ++mWindowCount |
| 941 | | ); |
| 942 | | stage.setTitle( title ); |
| 943 | | |
| 944 | | return getScene().getWindow(); |
| 945 | | } ); |
| 946 | | } |
| 947 | | |
| 948 | | /** |
| 949 | | * Responsible for configuring the content of each {@link DetachableTab} when |
| 950 | | * it is added to the given {@link DetachableTabPane} instance. |
| 951 | | * <p> |
| 952 | | * For {@link TextEditor} contents, an instance of {@link ScrollEventHandler} |
| 953 | | * is initialized to perform synchronized scrolling between the editor and |
| 954 | | * its preview window. Additionally, the last tab in the tab pane's list of |
| 955 | | * tabs is given focus. |
| 956 | | * </p> |
| 957 | | * <p> |
| 958 | | * Note that multiple tabs can be added simultaneously. |
| 959 | | * </p> |
| 960 | | * |
| 961 | | * @param tabPane A new {@link TabPane} to configure. |
| 962 | | */ |
| 963 | | private void initTabListener( final TabPane tabPane ) { |
| 964 | | tabPane.getTabs().addListener( |
| 965 | | ( final ListChangeListener.Change<? extends Tab> listener ) -> { |
| 966 | | while( listener.next() ) { |
| 967 | | if( listener.wasAdded() ) { |
| 968 | | final var tabs = listener.getAddedSubList(); |
| 969 | | |
| 970 | | tabs.forEach( tab -> { |
| 971 | | final var node = tab.getContent(); |
| 972 | | |
| 973 | | if( node instanceof TextEditor ) { |
| 974 | | initScrollEventListener( tab ); |
| 975 | | } |
| 976 | | } ); |
| 977 | | |
| 978 | | // Select and give focus to the last tab opened. |
| 979 | | final var index = tabs.size() - 1; |
| 980 | | if( index >= 0 ) { |
| 981 | | final var tab = tabs.get( index ); |
| 982 | | tabPane.getSelectionModel().select( tab ); |
| 983 | | tab.getContent().requestFocus(); |
| 984 | | } |
| 985 | | } |
| 986 | | } |
| 987 | | } |
| 988 | | ); |
| 989 | | } |
| 990 | | |
| 991 | | /** |
| 992 | | * Synchronizes scrollbar positions between the given {@link Tab} that |
| 993 | | * contains an instance of {@link TextEditor} and {@link HtmlPreview} pane. |
| 994 | | * |
| 995 | | * @param tab The container for an instance of {@link TextEditor}. |
| 996 | | */ |
| 997 | | private void initScrollEventListener( final Tab tab ) { |
| 998 | | final var editor = (TextEditor) tab.getContent(); |
| 999 | | final var scrollPane = editor.getScrollPane(); |
| 1000 | | final var scrollBar = mPreview.getVerticalScrollBar(); |
| 1001 | | final var handler = new ScrollEventHandler( scrollPane, scrollBar ); |
| 1002 | | |
| 1003 | | handler.enabledProperty().bind( tab.selectedProperty() ); |
| 1004 | | } |
| 1005 | | |
| 1006 | | private void addTabPane( final int index, final TabPane tabPane ) { |
| 1007 | | final var items = getItems(); |
| 1008 | | |
| 1009 | | if( !items.contains( tabPane ) ) { |
| 1010 | | items.add( index, tabPane ); |
| 1011 | | } |
| 1012 | | } |
| 1013 | | |
| 1014 | | private void addTabPane( final TabPane tabPane ) { |
| 1015 | | addTabPane( getItems().size(), tabPane ); |
| 1016 | | } |
| 1017 | | |
| 1018 | | private GenericBuilder<Mutator, ProcessorContext> processorContextBuilder() { |
| 1019 | | final var w = getWorkspace(); |
| 1020 | | |
| 1021 | | return builder() |
| 1022 | | .with( Mutator::setDefinitions, this::getDefinitions ) |
| 1023 | | .with( Mutator::setLocale, w::getLocale ) |
| 1024 | | .with( Mutator::setMetadata, w::getMetadata ) |
| 1025 | | .with( Mutator::setThemePath, w::getThemePath ) |
| 1026 | | .with( Mutator::setCaret, |
| 1027 | | () -> getTextEditor().getCaret() ) |
| 1028 | | .with( Mutator::setImageDir, |
| 1029 | | () -> w.getFile( KEY_IMAGES_DIR ) ) |
| 1030 | | .with( Mutator::setImageOrder, |
| 1031 | | () -> w.getString( KEY_IMAGES_ORDER ) ) |
| 1032 | | .with( Mutator::setImageServer, |
| 1033 | | () -> w.getString( KEY_IMAGES_SERVER ) ) |
| 1034 | | .with( Mutator::setSigilBegan, |
| 1035 | | () -> w.getString( KEY_DEF_DELIM_BEGAN ) ) |
| 1036 | | .with( Mutator::setSigilEnded, |
| 1037 | | () -> w.getString( KEY_DEF_DELIM_ENDED ) ) |
| 1038 | | .with( Mutator::setRScript, |
| 1039 | | () -> w.getString( KEY_R_SCRIPT ) ) |
| 1040 | | .with( Mutator::setRWorkingDir, |
| 1041 | | () -> w.getFile( KEY_R_DIR ).toPath() ) |
| 1042 | | .with( Mutator::setCurlQuotes, |
| 1043 | | () -> w.getBoolean( KEY_TYPESET_TYPOGRAPHY_QUOTES ) ) |
| 1044 | | .with( Mutator::setAutoClean, |
| 1045 | | () -> w.getBoolean( KEY_TYPESET_CONTEXT_CLEAN ) ); |
| 1046 | | } |
| 1047 | | |
| 1048 | | public ProcessorContext createProcessorContext() { |
| 1049 | | return createProcessorContext( null, NONE ); |
| 1050 | | } |
| 1051 | | |
| 1052 | | /** |
| 1053 | | * @param outputPath Used when exporting to a PDF file (binary). |
| 1054 | | * @param format Used when processors export to a new text format. |
| 1055 | | * @return A new {@link ProcessorContext} to use when creating an instance of |
| 1056 | | * {@link Processor}. |
| 1057 | | */ |
| 1058 | | public ProcessorContext createProcessorContext( |
| 1059 | | final Path outputPath, final ExportFormat format ) { |
| 1060 | | final var textEditor = getTextEditor(); |
| 1061 | | final var inputPath = textEditor.getPath(); |
| 1062 | | |
| 1063 | | return processorContextBuilder() |
| 1064 | | .with( Mutator::setInputPath, inputPath ) |
| 1065 | | .with( Mutator::setOutputPath, outputPath ) |
| 1066 | | .with( Mutator::setExportFormat, format ) |
| 1067 | | .build(); |
| 1068 | | } |
| 1069 | | |
| 1070 | | /** |
| 1071 | | * @param inputPath Used by {@link ProcessorFactory} to determine |
| 1072 | | * {@link Processor} type to create based on file type. |
| 1073 | | * @return A new {@link ProcessorContext} to use when creating an instance of |
| 1074 | | * {@link Processor}. |
| 1075 | | */ |
| 1076 | | private ProcessorContext createProcessorContext( final Path inputPath ) { |
| 1077 | | return processorContextBuilder() |
| 1078 | | .with( Mutator::setInputPath, inputPath ) |
| 1079 | | .with( Mutator::setExportFormat, NONE ) |
| 1080 | | .build(); |
| 1081 | | } |
| 1082 | | |
| 1083 | | private TextResource createTextResource( final File file ) { |
| 1084 | | // TODO: Create PlainTextEditor that's returned by default. |
| 1085 | | return MediaType.valueFrom( file ) == TEXT_YAML |
| 1086 | | ? createDefinitionEditor( file ) |
| 1087 | | : createMarkdownEditor( file ); |
| 1088 | | } |
| 1089 | | |
| 1090 | | /** |
| 1091 | | * Creates an instance of {@link MarkdownEditor} that listens for both |
| 1092 | | * caret change events and text change events. Text change events must |
| 1093 | | * take priority over caret change events because it's possible to change |
| 1094 | | * the text without moving the caret (e.g., delete selected text). |
| 1095 | | * |
| 1096 | | * @param inputFile The file containing contents for the text editor. |
| 1097 | | * @return A non-null text editor. |
| 1098 | | */ |
| 1099 | | private TextResource createMarkdownEditor( final File inputFile ) { |
| 1100 | | final var editor = new MarkdownEditor( inputFile, getWorkspace() ); |
| 1101 | | |
| 1102 | | mProcessors.computeIfAbsent( |
| 1103 | | editor, p -> createProcessors( |
| 1104 | | createProcessorContext( inputFile.toPath() ), |
| 1105 | | createHtmlPreviewProcessor() |
| 1106 | | ) |
| 1107 | | ); |
| 1108 | | |
| 1109 | | // Listener for editor modifications or caret position changes. |
| 1110 | | editor.addDirtyListener( ( c, o, n ) -> { |
| 1111 | | if( n ) { |
| 1112 | | // Reset the status bar after changing the text. |
| 1113 | | clue(); |
| 1114 | | |
| 1115 | | // Processing the text may update the status bar. |
| 1116 | | process( getTextEditor() ); |
| 1117 | | |
| 1118 | | // Update the caret position in the status bar. |
| 1119 | | CaretMovedEvent.fire( editor.getCaret() ); |
| 1120 | | } |
| 1121 | | } ); |
| 1122 | | |
| 1123 | | editor.addEventListener( |
| 1124 | | keyPressed( SPACE, CONTROL_DOWN ), this::autoinsert |
| 1125 | | ); |
| 1126 | | |
| 1127 | | // Track the caret to restore its position later. |
| 1128 | | editor.getTextArea().caretPositionProperty().addListener( ( c, o, n ) -> { |
| 1129 | | getWorkspace().integerProperty( KEY_UI_RECENT_OFFSET ).setValue( n ); |
| 1130 | | } ); |
| 1131 | | |
| 1132 | | // Set the active editor, which refreshes the preview panel. |
| 1133 | | mTextEditor.set( editor ); |
| 1134 | | |
| 1135 | | return editor; |
| 1136 | | } |
| 1137 | | |
| 1138 | | /** |
| 1139 | | * Creates a {@link Processor} capable of rendering an HTML document onto |
| 1140 | | * a GUI widget. |
| 1141 | | * |
| 1142 | | * @return The {@link Processor} for rendering an HTML document. |
| 1143 | | */ |
| 1144 | | private Processor<String> createHtmlPreviewProcessor() { |
| 1145 | | return new HtmlPreviewProcessor( getPreview() ); |
| 14 | import com.keenwrite.events.spelling.LexiconLoadedEvent; |
| 15 | import com.keenwrite.io.MediaType; |
| 16 | import com.keenwrite.preferences.Workspace; |
| 17 | import com.keenwrite.preview.HtmlPreview; |
| 18 | import com.keenwrite.processors.HtmlPreviewProcessor; |
| 19 | import com.keenwrite.processors.Processor; |
| 20 | import com.keenwrite.processors.ProcessorContext; |
| 21 | import com.keenwrite.processors.ProcessorFactory; |
| 22 | import com.keenwrite.processors.r.Engine; |
| 23 | import com.keenwrite.processors.r.RBootstrapController; |
| 24 | import com.keenwrite.service.events.Notifier; |
| 25 | import com.keenwrite.spelling.api.SpellChecker; |
| 26 | import com.keenwrite.spelling.impl.PermissiveSpeller; |
| 27 | import com.keenwrite.spelling.impl.SymSpellSpeller; |
| 28 | import com.keenwrite.ui.explorer.FilePickerFactory; |
| 29 | import com.keenwrite.ui.heuristics.DocumentStatistics; |
| 30 | import com.keenwrite.ui.outline.DocumentOutline; |
| 31 | import com.keenwrite.ui.spelling.TextEditorSpellChecker; |
| 32 | import com.keenwrite.util.GenericBuilder; |
| 33 | import com.panemu.tiwulfx.control.dock.DetachableTab; |
| 34 | import com.panemu.tiwulfx.control.dock.DetachableTabPane; |
| 35 | import javafx.application.Platform; |
| 36 | import javafx.beans.property.*; |
| 37 | import javafx.collections.ListChangeListener; |
| 38 | import javafx.concurrent.Task; |
| 39 | import javafx.event.ActionEvent; |
| 40 | import javafx.event.Event; |
| 41 | import javafx.event.EventHandler; |
| 42 | import javafx.scene.Node; |
| 43 | import javafx.scene.Scene; |
| 44 | import javafx.scene.control.*; |
| 45 | import javafx.scene.control.TreeItem.TreeModificationEvent; |
| 46 | import javafx.scene.input.KeyEvent; |
| 47 | import javafx.scene.layout.FlowPane; |
| 48 | import javafx.stage.Stage; |
| 49 | import javafx.stage.Window; |
| 50 | import org.greenrobot.eventbus.Subscribe; |
| 51 | |
| 52 | import java.io.File; |
| 53 | import java.io.FileNotFoundException; |
| 54 | import java.nio.file.Path; |
| 55 | import java.util.*; |
| 56 | import java.util.concurrent.ExecutorService; |
| 57 | import java.util.concurrent.ScheduledExecutorService; |
| 58 | import java.util.concurrent.ScheduledFuture; |
| 59 | import java.util.concurrent.atomic.AtomicBoolean; |
| 60 | import java.util.concurrent.atomic.AtomicReference; |
| 61 | import java.util.function.Consumer; |
| 62 | import java.util.function.Function; |
| 63 | import java.util.stream.Collectors; |
| 64 | |
| 65 | import static com.keenwrite.ExportFormat.NONE; |
| 66 | import static com.keenwrite.Launcher.terminate; |
| 67 | import static com.keenwrite.Messages.get; |
| 68 | import static com.keenwrite.constants.Constants.*; |
| 69 | import static com.keenwrite.constants.GraphicsConstants.ICON_DIALOG_NODE; |
| 70 | import static com.keenwrite.events.Bus.register; |
| 71 | import static com.keenwrite.events.StatusEvent.clue; |
| 72 | import static com.keenwrite.io.MediaType.*; |
| 73 | import static com.keenwrite.preferences.AppKeys.*; |
| 74 | import static com.keenwrite.processors.IdentityProcessor.IDENTITY; |
| 75 | import static com.keenwrite.processors.ProcessorContext.Mutator; |
| 76 | import static com.keenwrite.processors.ProcessorContext.builder; |
| 77 | import static com.keenwrite.processors.ProcessorFactory.createProcessors; |
| 78 | import static java.lang.String.format; |
| 79 | import static java.lang.System.getProperty; |
| 80 | import static java.util.concurrent.Executors.newFixedThreadPool; |
| 81 | import static java.util.concurrent.Executors.newScheduledThreadPool; |
| 82 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 83 | import static java.util.stream.Collectors.groupingBy; |
| 84 | import static javafx.application.Platform.runLater; |
| 85 | import static javafx.scene.control.Alert.AlertType.ERROR; |
| 86 | import static javafx.scene.control.ButtonType.*; |
| 87 | import static javafx.scene.control.TabPane.TabClosingPolicy.ALL_TABS; |
| 88 | import static javafx.scene.input.KeyCode.ENTER; |
| 89 | import static javafx.scene.input.KeyCode.SPACE; |
| 90 | import static javafx.scene.input.KeyCombination.ALT_DOWN; |
| 91 | import static javafx.scene.input.KeyCombination.CONTROL_DOWN; |
| 92 | import static javafx.util.Duration.millis; |
| 93 | import static javax.swing.SwingUtilities.invokeLater; |
| 94 | import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed; |
| 95 | |
| 96 | /** |
| 97 | * Responsible for wiring together the main application components for a |
| 98 | * particular {@link Workspace} (project). These include the definition views, |
| 99 | * text editors, and preview pane along with any corresponding controllers. |
| 100 | */ |
| 101 | public final class MainPane extends SplitPane { |
| 102 | |
| 103 | private static final ExecutorService sExecutor = newFixedThreadPool( 1 ); |
| 104 | private static final Notifier sNotifier = Services.load( Notifier.class ); |
| 105 | |
| 106 | /** |
| 107 | * Used when opening files to determine how each file should be binned and |
| 108 | * therefore what tab pane to be opened within. |
| 109 | */ |
| 110 | private static final Set<MediaType> PLAIN_TEXT_FORMAT = Set.of( |
| 111 | TEXT_MARKDOWN, TEXT_R_MARKDOWN, UNDEFINED |
| 112 | ); |
| 113 | |
| 114 | private final ScheduledExecutorService mSaver = newScheduledThreadPool( 1 ); |
| 115 | private final AtomicReference<ScheduledFuture<?>> mSaveTask = |
| 116 | new AtomicReference<>(); |
| 117 | |
| 118 | /** |
| 119 | * Prevents re-instantiation of processing classes. |
| 120 | */ |
| 121 | private final Map<TextResource, Processor<String>> mProcessors = |
| 122 | new HashMap<>(); |
| 123 | |
| 124 | private final Workspace mWorkspace; |
| 125 | |
| 126 | /** |
| 127 | * Groups similar file type tabs together. |
| 128 | */ |
| 129 | private final List<TabPane> mTabPanes = new ArrayList<>(); |
| 130 | |
| 131 | /** |
| 132 | * Renders the actively selected plain text editor tab. |
| 133 | */ |
| 134 | private final HtmlPreview mPreview; |
| 135 | |
| 136 | /** |
| 137 | * Provides an interactive document outline. |
| 138 | */ |
| 139 | private final DocumentOutline mOutline = new DocumentOutline(); |
| 140 | |
| 141 | /** |
| 142 | * Changing the active editor fires the value changed event. This allows |
| 143 | * refreshes to happen when external definitions are modified and need to |
| 144 | * trigger the processing chain. |
| 145 | */ |
| 146 | private final ObjectProperty<TextEditor> mTextEditor = |
| 147 | createActiveTextEditor(); |
| 148 | |
| 149 | /** |
| 150 | * Changing the active definition editor fires the value changed event. This |
| 151 | * allows refreshes to happen when external definitions are modified and need |
| 152 | * to trigger the processing chain. |
| 153 | */ |
| 154 | private final ObjectProperty<TextDefinition> mDefinitionEditor; |
| 155 | |
| 156 | private final ObjectProperty<SpellChecker> mSpellChecker; |
| 157 | |
| 158 | private final TextEditorSpellChecker mEditorSpeller; |
| 159 | |
| 160 | /** |
| 161 | * Called when the definition data is changed. |
| 162 | */ |
| 163 | private final EventHandler<TreeModificationEvent<Event>> mTreeHandler = |
| 164 | event -> { |
| 165 | process( getTextEditor() ); |
| 166 | save( getTextDefinition() ); |
| 167 | }; |
| 168 | |
| 169 | /** |
| 170 | * Tracks the number of detached tab panels opened into their own windows, |
| 171 | * which allows unique identification of subordinate windows by their title. |
| 172 | * It is doubtful more than 128 windows, much less 256, will be created. |
| 173 | */ |
| 174 | private byte mWindowCount; |
| 175 | |
| 176 | private final VariableNameInjector mVariableNameInjector; |
| 177 | |
| 178 | private final RBootstrapController mRBootstrapController; |
| 179 | |
| 180 | private final DocumentStatistics mStatistics; |
| 181 | |
| 182 | /** |
| 183 | * Adds all content panels to the main user interface. This will load the |
| 184 | * configuration settings from the workspace to reproduce the settings from |
| 185 | * a previous session. |
| 186 | */ |
| 187 | public MainPane( final Workspace workspace ) { |
| 188 | mWorkspace = workspace; |
| 189 | mSpellChecker = createSpellChecker(); |
| 190 | mEditorSpeller = createTextEditorSpellChecker( mSpellChecker ); |
| 191 | mPreview = new HtmlPreview( workspace ); |
| 192 | mStatistics = new DocumentStatistics( workspace ); |
| 193 | mTextEditor.set( createMarkdownEditor( DOCUMENT_DEFAULT ) ); |
| 194 | mDefinitionEditor = createActiveDefinitionEditor( mTextEditor ); |
| 195 | mVariableNameInjector = new VariableNameInjector( mWorkspace ); |
| 196 | mRBootstrapController = new RBootstrapController( |
| 197 | mWorkspace, this::getDefinitions ); |
| 198 | |
| 199 | open( collect( getRecentFiles() ) ); |
| 200 | viewPreview(); |
| 201 | setDividerPositions( calculateDividerPositions() ); |
| 202 | |
| 203 | // Once the main scene's window regains focus, update the active definition |
| 204 | // editor to the currently selected tab. |
| 205 | runLater( () -> getWindow().setOnCloseRequest( event -> { |
| 206 | // Order matters: Open file names must be persisted before closing all. |
| 207 | mWorkspace.save(); |
| 208 | |
| 209 | if( closeAll() ) { |
| 210 | Platform.exit(); |
| 211 | terminate( 0 ); |
| 212 | } |
| 213 | |
| 214 | event.consume(); |
| 215 | } ) ); |
| 216 | |
| 217 | register( this ); |
| 218 | initAutosave( workspace ); |
| 219 | |
| 220 | restoreSession(); |
| 221 | runLater( this::restoreFocus ); |
| 222 | } |
| 223 | |
| 224 | /** |
| 225 | * Called when spellchecking can be run. This will reload the dictionary |
| 226 | * into memory once, and then re-use it for all the existing text editors. |
| 227 | * |
| 228 | * @param event The event to process, having a populated word-frequency map. |
| 229 | */ |
| 230 | @Subscribe |
| 231 | public void handle( final LexiconLoadedEvent event ) { |
| 232 | final var lexicon = event.getLexicon(); |
| 233 | |
| 234 | try { |
| 235 | final var checker = SymSpellSpeller.forLexicon( lexicon ); |
| 236 | mSpellChecker.set( checker ); |
| 237 | } catch( final Exception ex ) { |
| 238 | clue( ex ); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | @Subscribe |
| 243 | public void handle( final TextEditorFocusEvent event ) { |
| 244 | mTextEditor.set( event.get() ); |
| 245 | } |
| 246 | |
| 247 | @Subscribe |
| 248 | public void handle( final TextDefinitionFocusEvent event ) { |
| 249 | mDefinitionEditor.set( event.get() ); |
| 250 | } |
| 251 | |
| 252 | /** |
| 253 | * Typically called when a file name is clicked in the preview panel. |
| 254 | * |
| 255 | * @param event The event to process, must contain a valid file reference. |
| 256 | */ |
| 257 | @Subscribe |
| 258 | public void handle( final FileOpenEvent event ) { |
| 259 | final File eventFile; |
| 260 | final var eventUri = event.getUri(); |
| 261 | |
| 262 | if( eventUri.isAbsolute() ) { |
| 263 | eventFile = new File( eventUri.getPath() ); |
| 264 | } |
| 265 | else { |
| 266 | final var activeFile = getTextEditor().getFile(); |
| 267 | final var parent = activeFile.getParentFile(); |
| 268 | |
| 269 | if( parent == null ) { |
| 270 | clue( new FileNotFoundException( eventUri.getPath() ) ); |
| 271 | return; |
| 272 | } |
| 273 | else { |
| 274 | final var parentPath = parent.getAbsolutePath(); |
| 275 | eventFile = Path.of( parentPath, eventUri.getPath() ).toFile(); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | runLater( () -> open( eventFile ) ); |
| 280 | } |
| 281 | |
| 282 | @Subscribe |
| 283 | public void handle( final CaretNavigationEvent event ) { |
| 284 | runLater( () -> { |
| 285 | final var textArea = getTextEditor(); |
| 286 | textArea.moveTo( event.getOffset() ); |
| 287 | textArea.requestFocus(); |
| 288 | } ); |
| 289 | } |
| 290 | |
| 291 | @Subscribe |
| 292 | @SuppressWarnings( "unused" ) |
| 293 | public void handle( final ExportFailedEvent event ) { |
| 294 | final var os = getProperty( "os.name" ); |
| 295 | final var arch = getProperty( "os.arch" ).toLowerCase(); |
| 296 | final var bits = getProperty( "sun.arch.data.model" ); |
| 297 | |
| 298 | final var title = Messages.get( "Alert.typesetter.missing.title" ); |
| 299 | final var header = Messages.get( "Alert.typesetter.missing.header" ); |
| 300 | final var version = Messages.get( |
| 301 | "Alert.typesetter.missing.version", |
| 302 | os, |
| 303 | arch |
| 304 | .replaceAll( "amd.*|i.*|x86.*", "X86" ) |
| 305 | .replaceAll( "mips.*", "MIPS" ) |
| 306 | .replaceAll( "armv.*", "ARM" ), |
| 307 | bits ); |
| 308 | final var text = Messages.get( "Alert.typesetter.missing.installer.text" ); |
| 309 | |
| 310 | // Download and install ConTeXt for {0} {1} {2}-bit |
| 311 | final var content = format( "%s %s", text, version ); |
| 312 | final var flowPane = new FlowPane(); |
| 313 | final var link = new Hyperlink( text ); |
| 314 | final var label = new Label( version ); |
| 315 | flowPane.getChildren().addAll( link, label ); |
| 316 | |
| 317 | final var alert = new Alert( ERROR, content, OK ); |
| 318 | alert.setTitle( title ); |
| 319 | alert.setHeaderText( header ); |
| 320 | alert.getDialogPane().contentProperty().set( flowPane ); |
| 321 | alert.setGraphic( ICON_DIALOG_NODE ); |
| 322 | |
| 323 | link.setOnAction( e -> { |
| 324 | alert.close(); |
| 325 | final var url = Messages.get( "Alert.typesetter.missing.installer.url" ); |
| 326 | runLater( () -> HyperlinkOpenEvent.fire( url ) ); |
| 327 | } ); |
| 328 | |
| 329 | alert.showAndWait(); |
| 330 | } |
| 331 | |
| 332 | @Subscribe |
| 333 | public void handle( final InsertDefinitionEvent<String> event ) { |
| 334 | final var leaf = event.getLeaf(); |
| 335 | final var editor = mTextEditor.get(); |
| 336 | |
| 337 | mVariableNameInjector.insert( editor, leaf ); |
| 338 | } |
| 339 | |
| 340 | private void initAutosave( final Workspace workspace ) { |
| 341 | final var rate = workspace.integerProperty( KEY_EDITOR_AUTOSAVE ); |
| 342 | |
| 343 | rate.addListener( |
| 344 | ( c, o, n ) -> { |
| 345 | final var taskRef = mSaveTask.get(); |
| 346 | |
| 347 | // Prevent multiple autosaves from running. |
| 348 | if( taskRef != null ) { |
| 349 | taskRef.cancel( false ); |
| 350 | } |
| 351 | |
| 352 | initAutosave( rate ); |
| 353 | } |
| 354 | ); |
| 355 | |
| 356 | // Start the save listener (avoids duplicating some code). |
| 357 | initAutosave( rate ); |
| 358 | } |
| 359 | |
| 360 | private void initAutosave( final IntegerProperty rate ) { |
| 361 | mSaveTask.set( |
| 362 | mSaver.scheduleAtFixedRate( |
| 363 | () -> { |
| 364 | if( getTextEditor().isModified() ) { |
| 365 | // Ensure the modified indicator is cleared by running on EDT. |
| 366 | runLater( this::save ); |
| 367 | } |
| 368 | }, 0, rate.intValue(), SECONDS |
| 369 | ) |
| 370 | ); |
| 371 | } |
| 372 | |
| 373 | /** |
| 374 | * TODO: Load divider positions from exported settings, see |
| 375 | * {@link #collect(SetProperty)} comment. |
| 376 | */ |
| 377 | private double[] calculateDividerPositions() { |
| 378 | final var ratio = 100f / getItems().size() / 100; |
| 379 | final var positions = getDividerPositions(); |
| 380 | |
| 381 | for( int i = 0; i < positions.length; i++ ) { |
| 382 | positions[ i ] = ratio * i; |
| 383 | } |
| 384 | |
| 385 | return positions; |
| 386 | } |
| 387 | |
| 388 | /** |
| 389 | * Opens all the files into the application, provided the paths are unique. |
| 390 | * This may only be called for any type of files that a user can edit |
| 391 | * (i.e., update and persist), such as definitions and text files. |
| 392 | * |
| 393 | * @param files The list of files to open. |
| 394 | */ |
| 395 | public void open( final List<File> files ) { |
| 396 | files.forEach( this::open ); |
| 397 | } |
| 398 | |
| 399 | /** |
| 400 | * This opens the given file. Since the preview pane is not a file that |
| 401 | * can be opened, it is safe to add a listener to the detachable pane. |
| 402 | * This will exit early if the given file is not a regular file (i.e., a |
| 403 | * directory). |
| 404 | * |
| 405 | * @param inputFile The file to open. |
| 406 | */ |
| 407 | private void open( final File inputFile ) { |
| 408 | // Prevent opening directories (a non-existent "untitled.md" is fine). |
| 409 | if( !inputFile.isFile() && inputFile.exists() ) { |
| 410 | return; |
| 411 | } |
| 412 | |
| 413 | final var tab = createTab( inputFile ); |
| 414 | final var node = tab.getContent(); |
| 415 | final var mediaType = MediaType.valueFrom( inputFile ); |
| 416 | final var tabPane = obtainTabPane( mediaType ); |
| 417 | |
| 418 | tab.setTooltip( createTooltip( inputFile ) ); |
| 419 | tabPane.setFocusTraversable( false ); |
| 420 | tabPane.setTabClosingPolicy( ALL_TABS ); |
| 421 | tabPane.getTabs().add( tab ); |
| 422 | |
| 423 | // Attach the tab scene factory for new tab panes. |
| 424 | if( !getItems().contains( tabPane ) ) { |
| 425 | addTabPane( |
| 426 | node instanceof TextDefinition ? 0 : getItems().size(), tabPane |
| 427 | ); |
| 428 | } |
| 429 | |
| 430 | if( inputFile.isFile() ) { |
| 431 | getRecentFiles().add( inputFile.getAbsolutePath() ); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | /** |
| 436 | * Gives focus to the most recently edited document and attempts to move |
| 437 | * the caret to the most recently known offset into said document. |
| 438 | */ |
| 439 | private void restoreSession() { |
| 440 | final var workspace = getWorkspace(); |
| 441 | final var file = workspace.fileProperty( KEY_UI_RECENT_DOCUMENT ); |
| 442 | final var offset = workspace.integerProperty( KEY_UI_RECENT_OFFSET ); |
| 443 | |
| 444 | for( final var pane : mTabPanes ) { |
| 445 | for( final var tab : pane.getTabs() ) { |
| 446 | final var tooltip = tab.getTooltip(); |
| 447 | |
| 448 | if( tooltip != null ) { |
| 449 | final var tabName = tooltip.getText(); |
| 450 | final var fileName = file.getValue().toString(); |
| 451 | |
| 452 | if( tabName.equalsIgnoreCase( fileName ) ) { |
| 453 | final var node = tab.getContent(); |
| 454 | |
| 455 | pane.getSelectionModel().select( tab ); |
| 456 | node.requestFocus(); |
| 457 | |
| 458 | if( node instanceof TextEditor editor ) { |
| 459 | editor.moveTo( offset.getValue() ); |
| 460 | } |
| 461 | |
| 462 | break; |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | /** |
| 470 | * Sets the focus to the middle pane, which contains the text editor tabs. |
| 471 | */ |
| 472 | private void restoreFocus() { |
| 473 | // Work around a bug where focusing directly on the middle pane results |
| 474 | // in the R engine not loading variables properly. |
| 475 | mTabPanes.get( 0 ).requestFocus(); |
| 476 | |
| 477 | // This is the only line that should be required. |
| 478 | mTabPanes.get( 1 ).requestFocus(); |
| 479 | } |
| 480 | |
| 481 | /** |
| 482 | * Opens a new text editor document using the default document file name. |
| 483 | */ |
| 484 | public void newTextEditor() { |
| 485 | open( DOCUMENT_DEFAULT ); |
| 486 | } |
| 487 | |
| 488 | /** |
| 489 | * Opens a new definition editor document using the default definition |
| 490 | * file name. |
| 491 | */ |
| 492 | public void newDefinitionEditor() { |
| 493 | open( DEFINITION_DEFAULT ); |
| 494 | } |
| 495 | |
| 496 | /** |
| 497 | * Iterates over all tab panes to find all {@link TextEditor}s and request |
| 498 | * that they save themselves. |
| 499 | */ |
| 500 | public void saveAll() { |
| 501 | iterateEditors( this::save ); |
| 502 | } |
| 503 | |
| 504 | /** |
| 505 | * Requests that the active {@link TextEditor} saves itself. Don't bother |
| 506 | * checking if modified first because if the user swaps external media from |
| 507 | * an external source (e.g., USB thumb drive), save should not second-guess |
| 508 | * the user: save always re-saves. Also, it's less code. |
| 509 | */ |
| 510 | public void save() { |
| 511 | save( getTextEditor() ); |
| 512 | } |
| 513 | |
| 514 | /** |
| 515 | * Saves the active {@link TextEditor} under a new name. |
| 516 | * |
| 517 | * @param files The new active editor {@link File} reference, must contain |
| 518 | * at least one element. |
| 519 | */ |
| 520 | public void saveAs( final List<File> files ) { |
| 521 | assert files != null; |
| 522 | assert !files.isEmpty(); |
| 523 | final var editor = getTextEditor(); |
| 524 | final var tab = getTab( editor ); |
| 525 | final var file = files.get( 0 ); |
| 526 | |
| 527 | editor.rename( file ); |
| 528 | tab.ifPresent( t -> { |
| 529 | t.setText( editor.getFilename() ); |
| 530 | t.setTooltip( createTooltip( file ) ); |
| 531 | } ); |
| 532 | |
| 533 | save(); |
| 534 | } |
| 535 | |
| 536 | /** |
| 537 | * Saves the given {@link TextResource} to a file. This is typically used |
| 538 | * to save either an instance of {@link TextEditor} or {@link TextDefinition}. |
| 539 | * |
| 540 | * @param resource The resource to export. |
| 541 | */ |
| 542 | private void save( final TextResource resource ) { |
| 543 | try { |
| 544 | resource.save(); |
| 545 | } catch( final Exception ex ) { |
| 546 | clue( ex ); |
| 547 | sNotifier.alert( |
| 548 | getWindow(), resource.getPath(), "TextResource.saveFailed", ex |
| 549 | ); |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | /** |
| 554 | * Closes all open {@link TextEditor}s; all {@link TextDefinition}s stay open. |
| 555 | * |
| 556 | * @return {@code true} when all editors, modified or otherwise, were |
| 557 | * permitted to close; {@code false} when one or more editors were modified |
| 558 | * and the user requested no closing. |
| 559 | */ |
| 560 | public boolean closeAll() { |
| 561 | var closable = true; |
| 562 | |
| 563 | for( final var tabPane : mTabPanes ) { |
| 564 | final var tabIterator = tabPane.getTabs().iterator(); |
| 565 | |
| 566 | while( tabIterator.hasNext() ) { |
| 567 | final var tab = tabIterator.next(); |
| 568 | final var resource = tab.getContent(); |
| 569 | |
| 570 | // The definition panes auto-save, so being specific here prevents |
| 571 | // closing the definitions in the situation where the user wants to |
| 572 | // continue editing (i.e., possibly save unsaved work). |
| 573 | if( !(resource instanceof TextEditor) ) { |
| 574 | continue; |
| 575 | } |
| 576 | |
| 577 | if( canClose( (TextEditor) resource ) ) { |
| 578 | tabIterator.remove(); |
| 579 | close( tab ); |
| 580 | } |
| 581 | else { |
| 582 | closable = false; |
| 583 | } |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | return closable; |
| 588 | } |
| 589 | |
| 590 | /** |
| 591 | * Calls the tab's {@link Tab#getOnClosed()} handler to carry out a close |
| 592 | * event. |
| 593 | * |
| 594 | * @param tab The {@link Tab} that was closed. |
| 595 | */ |
| 596 | private void close( final Tab tab ) { |
| 597 | assert tab != null; |
| 598 | |
| 599 | final var handler = tab.getOnClosed(); |
| 600 | |
| 601 | if( handler != null ) { |
| 602 | handler.handle( new ActionEvent() ); |
| 603 | } |
| 604 | } |
| 605 | |
| 606 | /** |
| 607 | * Closes the active tab; delegates to {@link #canClose(TextResource)}. |
| 608 | */ |
| 609 | public void close() { |
| 610 | final var editor = getTextEditor(); |
| 611 | |
| 612 | if( canClose( editor ) ) { |
| 613 | close( editor ); |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | /** |
| 618 | * Closes the given {@link TextResource}. This must not be called from within |
| 619 | * a loop that iterates over the tab panes using {@code forEach}, lest a |
| 620 | * concurrent modification exception be thrown. |
| 621 | * |
| 622 | * @param resource The {@link TextResource} to close, without confirming with |
| 623 | * the user. |
| 624 | */ |
| 625 | private void close( final TextResource resource ) { |
| 626 | getTab( resource ).ifPresent( |
| 627 | tab -> { |
| 628 | close( tab ); |
| 629 | tab.getTabPane().getTabs().remove( tab ); |
| 630 | } |
| 631 | ); |
| 632 | } |
| 633 | |
| 634 | /** |
| 635 | * Answers whether the given {@link TextResource} may be closed. |
| 636 | * |
| 637 | * @param editor The {@link TextResource} to try closing. |
| 638 | * @return {@code true} when the editor may be closed; {@code false} when |
| 639 | * the user has requested to keep the editor open. |
| 640 | */ |
| 641 | private boolean canClose( final TextResource editor ) { |
| 642 | final var editorTab = getTab( editor ); |
| 643 | final var canClose = new AtomicBoolean( true ); |
| 644 | |
| 645 | if( editor.isModified() ) { |
| 646 | final var filename = new StringBuilder(); |
| 647 | editorTab.ifPresent( tab -> filename.append( tab.getText() ) ); |
| 648 | |
| 649 | final var message = sNotifier.createNotification( |
| 650 | Messages.get( "Alert.file.close.title" ), |
| 651 | Messages.get( "Alert.file.close.text" ), |
| 652 | filename.toString() |
| 653 | ); |
| 654 | |
| 655 | final var dialog = sNotifier.createConfirmation( getWindow(), message ); |
| 656 | |
| 657 | dialog.showAndWait().ifPresent( |
| 658 | save -> canClose.set( save == YES ? editor.save() : save == NO ) |
| 659 | ); |
| 660 | } |
| 661 | |
| 662 | return canClose.get(); |
| 663 | } |
| 664 | |
| 665 | private void iterateEditors( final Consumer<TextEditor> consumer ) { |
| 666 | mTabPanes.forEach( |
| 667 | tp -> tp.getTabs().forEach( tab -> { |
| 668 | final var node = tab.getContent(); |
| 669 | |
| 670 | if( node instanceof final TextEditor editor ) { |
| 671 | consumer.accept( editor ); |
| 672 | } |
| 673 | } ) |
| 674 | ); |
| 675 | } |
| 676 | |
| 677 | private ObjectProperty<TextEditor> createActiveTextEditor() { |
| 678 | final var editor = new SimpleObjectProperty<TextEditor>(); |
| 679 | |
| 680 | editor.addListener( ( c, o, n ) -> { |
| 681 | if( n != null ) { |
| 682 | mPreview.setBaseUri( n.getPath() ); |
| 683 | process( n ); |
| 684 | } |
| 685 | } ); |
| 686 | |
| 687 | return editor; |
| 688 | } |
| 689 | |
| 690 | /** |
| 691 | * Adds the HTML preview tab to its own, singular tab pane. |
| 692 | */ |
| 693 | public void viewPreview() { |
| 694 | viewTab( mPreview, TEXT_HTML, "Pane.preview.title" ); |
| 695 | } |
| 696 | |
| 697 | /** |
| 698 | * Adds the document outline tab to its own, singular tab pane. |
| 699 | */ |
| 700 | public void viewOutline() { |
| 701 | viewTab( mOutline, APP_DOCUMENT_OUTLINE, "Pane.outline.title" ); |
| 702 | } |
| 703 | |
| 704 | public void viewStatistics() { |
| 705 | viewTab( mStatistics, APP_DOCUMENT_STATISTICS, "Pane.statistics.title" ); |
| 706 | } |
| 707 | |
| 708 | public void viewFiles() { |
| 709 | try { |
| 710 | final var factory = new FilePickerFactory( getWorkspace() ); |
| 711 | final var fileManager = factory.createModeless(); |
| 712 | viewTab( fileManager, APP_FILE_MANAGER, "Pane.files.title" ); |
| 713 | } catch( final Exception ex ) { |
| 714 | clue( ex ); |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | private void viewTab( |
| 719 | final Node node, final MediaType mediaType, final String key ) { |
| 720 | final var tabPane = obtainTabPane( mediaType ); |
| 721 | |
| 722 | for( final var tab : tabPane.getTabs() ) { |
| 723 | if( tab.getContent() == node ) { |
| 724 | return; |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | tabPane.getTabs().add( createTab( get( key ), node ) ); |
| 729 | addTabPane( tabPane ); |
| 730 | } |
| 731 | |
| 732 | public void viewRefresh() { |
| 733 | mPreview.refresh(); |
| 734 | Engine.clear(); |
| 735 | mRBootstrapController.update(); |
| 736 | } |
| 737 | |
| 738 | /** |
| 739 | * Returns the tab that contains the given {@link TextEditor}. |
| 740 | * |
| 741 | * @param editor The {@link TextEditor} instance to find amongst the tabs. |
| 742 | * @return The first tab having content that matches the given tab. |
| 743 | */ |
| 744 | private Optional<Tab> getTab( final TextResource editor ) { |
| 745 | return mTabPanes.stream() |
| 746 | .flatMap( pane -> pane.getTabs().stream() ) |
| 747 | .filter( tab -> editor.equals( tab.getContent() ) ) |
| 748 | .findFirst(); |
| 749 | } |
| 750 | |
| 751 | /** |
| 752 | * Creates a new {@link DefinitionEditor} wrapped in a listener that |
| 753 | * is used to detect when the active {@link DefinitionEditor} has changed. |
| 754 | * Upon changing, the variables are interpolated and the active text editor |
| 755 | * is refreshed. |
| 756 | * |
| 757 | * @param textEditor Text editor to update with the revised resolved map. |
| 758 | * @return A newly configured property that represents the active |
| 759 | * {@link DefinitionEditor}, never null. |
| 760 | */ |
| 761 | private ObjectProperty<TextDefinition> createActiveDefinitionEditor( |
| 762 | final ObjectProperty<TextEditor> textEditor ) { |
| 763 | final var defEditor = new SimpleObjectProperty<>( |
| 764 | createDefinitionEditor() |
| 765 | ); |
| 766 | |
| 767 | defEditor.addListener( ( c, o, n ) -> { |
| 768 | final var editor = textEditor.get(); |
| 769 | |
| 770 | if( editor.isMediaType( TEXT_R_MARKDOWN ) ) { |
| 771 | // Initialize R before the editor is added. |
| 772 | mRBootstrapController.update(); |
| 773 | } |
| 774 | |
| 775 | process( editor ); |
| 776 | } ); |
| 777 | |
| 778 | return defEditor; |
| 779 | } |
| 780 | |
| 781 | private Tab createTab( final String filename, final Node node ) { |
| 782 | return new DetachableTab( filename, node ); |
| 783 | } |
| 784 | |
| 785 | private Tab createTab( final File file ) { |
| 786 | final var r = createTextResource( file ); |
| 787 | final var tab = createTab( r.getFilename(), r.getNode() ); |
| 788 | |
| 789 | r.modifiedProperty().addListener( |
| 790 | ( c, o, n ) -> tab.setText( r.getFilename() + (n ? "*" : "") ) |
| 791 | ); |
| 792 | |
| 793 | // This is called when either the tab is closed by the user clicking on |
| 794 | // the tab's close icon or when closing (all) from the file menu. |
| 795 | tab.setOnClosed( |
| 796 | __ -> getRecentFiles().remove( file.getAbsolutePath() ) |
| 797 | ); |
| 798 | |
| 799 | // When closing a tab, give focus to the newly revealed tab. |
| 800 | tab.selectedProperty().addListener( ( c, o, n ) -> { |
| 801 | if( n != null && n ) { |
| 802 | final var pane = tab.getTabPane(); |
| 803 | |
| 804 | if( pane != null ) { |
| 805 | pane.requestFocus(); |
| 806 | } |
| 807 | } |
| 808 | } ); |
| 809 | |
| 810 | tab.tabPaneProperty().addListener( ( cPane, oPane, nPane ) -> { |
| 811 | if( nPane != null ) { |
| 812 | nPane.focusedProperty().addListener( ( c, o, n ) -> { |
| 813 | if( n != null && n ) { |
| 814 | final var selected = nPane.getSelectionModel().getSelectedItem(); |
| 815 | final var node = selected.getContent(); |
| 816 | node.requestFocus(); |
| 817 | } |
| 818 | } ); |
| 819 | } |
| 820 | } ); |
| 821 | |
| 822 | return tab; |
| 823 | } |
| 824 | |
| 825 | /** |
| 826 | * Creates bins for the different {@link MediaType}s, which eventually are |
| 827 | * added to the UI as separate tab panes. If ever a general-purpose scene |
| 828 | * exporter is developed to serialize a scene to an FXML file, this could |
| 829 | * be replaced by such a class. |
| 830 | * <p> |
| 831 | * When binning the files, this makes sure that at least one file exists |
| 832 | * for every type. If the user has opted to close a particular type (such |
| 833 | * as the definition pane), the view will suppressed elsewhere. |
| 834 | * </p> |
| 835 | * <p> |
| 836 | * The order that the binned files are returned will be reflected in the |
| 837 | * order that the corresponding panes are rendered in the UI. |
| 838 | * </p> |
| 839 | * |
| 840 | * @param paths The file paths to bin according to their type. |
| 841 | * @return An in-order list of files, first by structured definition files, |
| 842 | * then by plain text documents. |
| 843 | */ |
| 844 | private List<File> collect( final SetProperty<String> paths ) { |
| 845 | // Treat all files destined for the text editor as plain text documents |
| 846 | // so that they are added to the same pane. Grouping by TEXT_PLAIN is a |
| 847 | // bit arbitrary, but means explicitly capturing TEXT_PLAIN isn't needed. |
| 848 | final Function<MediaType, MediaType> bin = |
| 849 | m -> PLAIN_TEXT_FORMAT.contains( m ) ? TEXT_PLAIN : m; |
| 850 | |
| 851 | // Create two groups: YAML files and plain text files. The order that |
| 852 | // the elements are listed in the enumeration for media types determines |
| 853 | // what files are loaded first. Variable definitions come before all other |
| 854 | // plain text documents. |
| 855 | final var bins = paths |
| 856 | .stream() |
| 857 | .collect( |
| 858 | groupingBy( |
| 859 | path -> bin.apply( MediaType.fromFilename( path ) ), |
| 860 | () -> new TreeMap<>( Enum::compareTo ), |
| 861 | Collectors.toList() |
| 862 | ) |
| 863 | ); |
| 864 | |
| 865 | bins.putIfAbsent( TEXT_YAML, List.of( DEFINITION_DEFAULT.toString() ) ); |
| 866 | bins.putIfAbsent( TEXT_PLAIN, List.of( DOCUMENT_DEFAULT.toString() ) ); |
| 867 | |
| 868 | final var result = new LinkedList<File>(); |
| 869 | |
| 870 | // Ensure that the same types are listed together (keep insertion order). |
| 871 | bins.forEach( ( mediaType, files ) -> result.addAll( |
| 872 | files.stream().map( File::new ).toList() ) |
| 873 | ); |
| 874 | |
| 875 | return result; |
| 876 | } |
| 877 | |
| 878 | /** |
| 879 | * Force the active editor to update, which will cause the processor |
| 880 | * to re-evaluate the interpolated definition map thereby updating the |
| 881 | * preview pane. |
| 882 | * |
| 883 | * @param editor Contains the source document to update in the preview pane. |
| 884 | */ |
| 885 | private void process( final TextEditor editor ) { |
| 886 | // Ensure processing does not run on the JavaFX thread, which frees the |
| 887 | // text editor immediately for caret movement. The preview will have a |
| 888 | // slight delay when catching up to the caret position. |
| 889 | final var task = new Task<Void>() { |
| 890 | @Override |
| 891 | public Void call() { |
| 892 | try { |
| 893 | final var p = mProcessors.getOrDefault( editor, IDENTITY ); |
| 894 | p.apply( editor == null ? "" : editor.getText() ); |
| 895 | } catch( final Exception ex ) { |
| 896 | clue( ex ); |
| 897 | } |
| 898 | |
| 899 | return null; |
| 900 | } |
| 901 | }; |
| 902 | |
| 903 | // TODO: Each time the editor successfully runs the processor the task is |
| 904 | // considered successful. Due to the rapid-fire nature of processing |
| 905 | // (e.g., keyboard navigation, fast typing), it isn't necessary to |
| 906 | // scroll each time. |
| 907 | // The algorithm: |
| 908 | // 1. Peek at the oldest time. |
| 909 | // 2. If the difference between the oldest time and current time exceeds |
| 910 | // 250 milliseconds, then invoke the scrolling. |
| 911 | // 3. Insert the current time into the circular queue. |
| 912 | task.setOnSucceeded( |
| 913 | e -> invokeLater( () -> mPreview.scrollTo( CARET_ID ) ) |
| 914 | ); |
| 915 | |
| 916 | // Prevents multiple process requests from executing simultaneously (due |
| 917 | // to having a restricted queue size). |
| 918 | sExecutor.execute( task ); |
| 919 | } |
| 920 | |
| 921 | /** |
| 922 | * Lazily creates a {@link TabPane} configured to listen for tab select |
| 923 | * events. The tab pane is associated with a given media type so that |
| 924 | * similar files can be grouped together. |
| 925 | * |
| 926 | * @param mediaType The media type to associate with the tab pane. |
| 927 | * @return An instance of {@link TabPane} that will handle tab docking. |
| 928 | */ |
| 929 | private TabPane obtainTabPane( final MediaType mediaType ) { |
| 930 | for( final var pane : mTabPanes ) { |
| 931 | for( final var tab : pane.getTabs() ) { |
| 932 | final var node = tab.getContent(); |
| 933 | |
| 934 | if( node instanceof TextResource r && r.supports( mediaType ) ) { |
| 935 | return pane; |
| 936 | } |
| 937 | } |
| 938 | } |
| 939 | |
| 940 | final var pane = createTabPane(); |
| 941 | mTabPanes.add( pane ); |
| 942 | return pane; |
| 943 | } |
| 944 | |
| 945 | /** |
| 946 | * Creates an initialized {@link TabPane} instance. |
| 947 | * |
| 948 | * @return A new {@link TabPane} with all listeners configured. |
| 949 | */ |
| 950 | private TabPane createTabPane() { |
| 951 | final var tabPane = new DetachableTabPane(); |
| 952 | |
| 953 | initStageOwnerFactory( tabPane ); |
| 954 | initTabListener( tabPane ); |
| 955 | |
| 956 | return tabPane; |
| 957 | } |
| 958 | |
| 959 | /** |
| 960 | * When any {@link DetachableTabPane} is detached from the main window, |
| 961 | * the stage owner factory must be given its parent window, which will |
| 962 | * own the child window. The parent window is the {@link MainPane}'s |
| 963 | * {@link Scene}'s {@link Window} instance. |
| 964 | * |
| 965 | * <p> |
| 966 | * This will derives the new title from the main window title, incrementing |
| 967 | * the window count to help uniquely identify the child windows. |
| 968 | * </p> |
| 969 | * |
| 970 | * @param tabPane A new {@link DetachableTabPane} to configure. |
| 971 | */ |
| 972 | private void initStageOwnerFactory( final DetachableTabPane tabPane ) { |
| 973 | tabPane.setStageOwnerFactory( stage -> { |
| 974 | final var title = get( |
| 975 | "Detach.tab.title", |
| 976 | ((Stage) getWindow()).getTitle(), ++mWindowCount |
| 977 | ); |
| 978 | stage.setTitle( title ); |
| 979 | |
| 980 | return getScene().getWindow(); |
| 981 | } ); |
| 982 | } |
| 983 | |
| 984 | /** |
| 985 | * Responsible for configuring the content of each {@link DetachableTab} when |
| 986 | * it is added to the given {@link DetachableTabPane} instance. |
| 987 | * <p> |
| 988 | * For {@link TextEditor} contents, an instance of {@link ScrollEventHandler} |
| 989 | * is initialized to perform synchronized scrolling between the editor and |
| 990 | * its preview window. Additionally, the last tab in the tab pane's list of |
| 991 | * tabs is given focus. |
| 992 | * </p> |
| 993 | * <p> |
| 994 | * Note that multiple tabs can be added simultaneously. |
| 995 | * </p> |
| 996 | * |
| 997 | * @param tabPane A new {@link TabPane} to configure. |
| 998 | */ |
| 999 | private void initTabListener( final TabPane tabPane ) { |
| 1000 | tabPane.getTabs().addListener( |
| 1001 | ( final ListChangeListener.Change<? extends Tab> listener ) -> { |
| 1002 | while( listener.next() ) { |
| 1003 | if( listener.wasAdded() ) { |
| 1004 | final var tabs = listener.getAddedSubList(); |
| 1005 | |
| 1006 | tabs.forEach( tab -> { |
| 1007 | final var node = tab.getContent(); |
| 1008 | |
| 1009 | if( node instanceof TextEditor ) { |
| 1010 | initScrollEventListener( tab ); |
| 1011 | } |
| 1012 | } ); |
| 1013 | |
| 1014 | // Select and give focus to the last tab opened. |
| 1015 | final var index = tabs.size() - 1; |
| 1016 | if( index >= 0 ) { |
| 1017 | final var tab = tabs.get( index ); |
| 1018 | tabPane.getSelectionModel().select( tab ); |
| 1019 | tab.getContent().requestFocus(); |
| 1020 | } |
| 1021 | } |
| 1022 | } |
| 1023 | } |
| 1024 | ); |
| 1025 | } |
| 1026 | |
| 1027 | /** |
| 1028 | * Synchronizes scrollbar positions between the given {@link Tab} that |
| 1029 | * contains an instance of {@link TextEditor} and {@link HtmlPreview} pane. |
| 1030 | * |
| 1031 | * @param tab The container for an instance of {@link TextEditor}. |
| 1032 | */ |
| 1033 | private void initScrollEventListener( final Tab tab ) { |
| 1034 | final var editor = (TextEditor) tab.getContent(); |
| 1035 | final var scrollPane = editor.getScrollPane(); |
| 1036 | final var scrollBar = mPreview.getVerticalScrollBar(); |
| 1037 | final var handler = new ScrollEventHandler( scrollPane, scrollBar ); |
| 1038 | |
| 1039 | handler.enabledProperty().bind( tab.selectedProperty() ); |
| 1040 | } |
| 1041 | |
| 1042 | private void addTabPane( final int index, final TabPane tabPane ) { |
| 1043 | final var items = getItems(); |
| 1044 | |
| 1045 | if( !items.contains( tabPane ) ) { |
| 1046 | items.add( index, tabPane ); |
| 1047 | } |
| 1048 | } |
| 1049 | |
| 1050 | private void addTabPane( final TabPane tabPane ) { |
| 1051 | addTabPane( getItems().size(), tabPane ); |
| 1052 | } |
| 1053 | |
| 1054 | private GenericBuilder<Mutator, ProcessorContext> processorContextBuilder() { |
| 1055 | final var w = getWorkspace(); |
| 1056 | |
| 1057 | return builder() |
| 1058 | .with( Mutator::setDefinitions, this::getDefinitions ) |
| 1059 | .with( Mutator::setLocale, w::getLocale ) |
| 1060 | .with( Mutator::setMetadata, w::getMetadata ) |
| 1061 | .with( Mutator::setThemePath, w::getThemePath ) |
| 1062 | .with( Mutator::setCaret, |
| 1063 | () -> getTextEditor().getCaret() ) |
| 1064 | .with( Mutator::setImageDir, |
| 1065 | () -> w.getFile( KEY_IMAGES_DIR ) ) |
| 1066 | .with( Mutator::setImageOrder, |
| 1067 | () -> w.getString( KEY_IMAGES_ORDER ) ) |
| 1068 | .with( Mutator::setImageServer, |
| 1069 | () -> w.getString( KEY_IMAGES_SERVER ) ) |
| 1070 | .with( Mutator::setSigilBegan, |
| 1071 | () -> w.getString( KEY_DEF_DELIM_BEGAN ) ) |
| 1072 | .with( Mutator::setSigilEnded, |
| 1073 | () -> w.getString( KEY_DEF_DELIM_ENDED ) ) |
| 1074 | .with( Mutator::setRScript, |
| 1075 | () -> w.getString( KEY_R_SCRIPT ) ) |
| 1076 | .with( Mutator::setRWorkingDir, |
| 1077 | () -> w.getFile( KEY_R_DIR ).toPath() ) |
| 1078 | .with( Mutator::setCurlQuotes, |
| 1079 | () -> w.getBoolean( KEY_TYPESET_TYPOGRAPHY_QUOTES ) ) |
| 1080 | .with( Mutator::setAutoClean, |
| 1081 | () -> w.getBoolean( KEY_TYPESET_CONTEXT_CLEAN ) ); |
| 1082 | } |
| 1083 | |
| 1084 | public ProcessorContext createProcessorContext() { |
| 1085 | return createProcessorContext( null, NONE ); |
| 1086 | } |
| 1087 | |
| 1088 | /** |
| 1089 | * @param outputPath Used when exporting to a PDF file (binary). |
| 1090 | * @param format Used when processors export to a new text format. |
| 1091 | * @return A new {@link ProcessorContext} to use when creating an instance of |
| 1092 | * {@link Processor}. |
| 1093 | */ |
| 1094 | public ProcessorContext createProcessorContext( |
| 1095 | final Path outputPath, final ExportFormat format ) { |
| 1096 | final var textEditor = getTextEditor(); |
| 1097 | final var inputPath = textEditor.getPath(); |
| 1098 | |
| 1099 | return processorContextBuilder() |
| 1100 | .with( Mutator::setInputPath, inputPath ) |
| 1101 | .with( Mutator::setOutputPath, outputPath ) |
| 1102 | .with( Mutator::setExportFormat, format ) |
| 1103 | .build(); |
| 1104 | } |
| 1105 | |
| 1106 | /** |
| 1107 | * @param inputPath Used by {@link ProcessorFactory} to determine |
| 1108 | * {@link Processor} type to create based on file type. |
| 1109 | * @return A new {@link ProcessorContext} to use when creating an instance of |
| 1110 | * {@link Processor}. |
| 1111 | */ |
| 1112 | private ProcessorContext createProcessorContext( final Path inputPath ) { |
| 1113 | return processorContextBuilder() |
| 1114 | .with( Mutator::setInputPath, inputPath ) |
| 1115 | .with( Mutator::setExportFormat, NONE ) |
| 1116 | .build(); |
| 1117 | } |
| 1118 | |
| 1119 | private TextResource createTextResource( final File file ) { |
| 1120 | // TODO: Create PlainTextEditor that's returned by default. |
| 1121 | return MediaType.valueFrom( file ) == TEXT_YAML |
| 1122 | ? createDefinitionEditor( file ) |
| 1123 | : createMarkdownEditor( file ); |
| 1124 | } |
| 1125 | |
| 1126 | /** |
| 1127 | * Creates an instance of {@link MarkdownEditor} that listens for both |
| 1128 | * caret change events and text change events. Text change events must |
| 1129 | * take priority over caret change events because it's possible to change |
| 1130 | * the text without moving the caret (e.g., delete selected text). |
| 1131 | * |
| 1132 | * @param inputFile The file containing contents for the text editor. |
| 1133 | * @return A non-null text editor. |
| 1134 | */ |
| 1135 | private MarkdownEditor createMarkdownEditor( final File inputFile ) { |
| 1136 | final var editor = new MarkdownEditor( inputFile, getWorkspace() ); |
| 1137 | |
| 1138 | mProcessors.computeIfAbsent( |
| 1139 | editor, p -> createProcessors( |
| 1140 | createProcessorContext( inputFile.toPath() ), |
| 1141 | createHtmlPreviewProcessor() |
| 1142 | ) |
| 1143 | ); |
| 1144 | |
| 1145 | // Listener for editor modifications or caret position changes. |
| 1146 | editor.addDirtyListener( ( c, o, n ) -> { |
| 1147 | if( n ) { |
| 1148 | // Reset the status bar after changing the text. |
| 1149 | clue(); |
| 1150 | |
| 1151 | // Processing the text may update the status bar. |
| 1152 | process( getTextEditor() ); |
| 1153 | |
| 1154 | // Update the caret position in the status bar. |
| 1155 | CaretMovedEvent.fire( editor.getCaret() ); |
| 1156 | } |
| 1157 | } ); |
| 1158 | |
| 1159 | editor.addEventListener( |
| 1160 | keyPressed( SPACE, CONTROL_DOWN ), this::autoinsert |
| 1161 | ); |
| 1162 | |
| 1163 | editor.addEventListener( |
| 1164 | keyPressed( ENTER, ALT_DOWN ), event -> mEditorSpeller.autofix( editor ) |
| 1165 | ); |
| 1166 | |
| 1167 | final var textArea = editor.getTextArea(); |
| 1168 | |
| 1169 | // Spell check when the paragraph changes. |
| 1170 | textArea |
| 1171 | .plainTextChanges() |
| 1172 | .filter( p -> !p.isIdentity() ) |
| 1173 | .subscribe( change -> mEditorSpeller.checkParagraph( textArea, change ) ); |
| 1174 | |
| 1175 | // Store the caret position to restore it after restarting the application. |
| 1176 | textArea.caretPositionProperty().addListener( |
| 1177 | ( c, o, n ) -> |
| 1178 | getWorkspace().integerProperty( KEY_UI_RECENT_OFFSET ).setValue( n ) |
| 1179 | ); |
| 1180 | |
| 1181 | // Set the active editor, which refreshes the preview panel. |
| 1182 | mTextEditor.set( editor ); |
| 1183 | |
| 1184 | // Check the entire document after the spellchecker is initialized (with |
| 1185 | // a valid lexicon) so that only the current paragraph need be scanned |
| 1186 | // while editing. (Technically, only the most recently modified word must |
| 1187 | // be scanned.) |
| 1188 | mSpellChecker.addListener( |
| 1189 | ( c, o, n ) -> runLater( |
| 1190 | () -> iterateEditors( mEditorSpeller::checkDocument ) |
| 1191 | ) |
| 1192 | ); |
| 1193 | |
| 1194 | // Check the entire document after it has been loaded. |
| 1195 | mEditorSpeller.checkDocument( mTextEditor.get() ); |
| 1196 | |
| 1197 | return editor; |
| 1198 | } |
| 1199 | |
| 1200 | /** |
| 1201 | * Creates a {@link Processor} capable of rendering an HTML document onto |
| 1202 | * a GUI widget. |
| 1203 | * |
| 1204 | * @return The {@link Processor} for rendering an HTML document. |
| 1205 | */ |
| 1206 | private Processor<String> createHtmlPreviewProcessor() { |
| 1207 | return new HtmlPreviewProcessor( getPreview() ); |
| 1208 | } |
| 1209 | |
| 1210 | /** |
| 1211 | * Creates a spellchecker that accepts all words as correct. This allows |
| 1212 | * the spellchecker property to be initialized to a known valid value. |
| 1213 | * |
| 1214 | * @return A wrapped {@link PermissiveSpeller}. |
| 1215 | */ |
| 1216 | private ObjectProperty<SpellChecker> createSpellChecker() { |
| 1217 | return new SimpleObjectProperty<>( new PermissiveSpeller() ); |
| 1218 | } |
| 1219 | |
| 1220 | private TextEditorSpellChecker createTextEditorSpellChecker( |
| 1221 | final ObjectProperty<SpellChecker> spellChecker ) { |
| 1222 | return new TextEditorSpellChecker( spellChecker ); |
| 1146 | 1223 | } |
| 1147 | 1224 | |