-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathController.java
More file actions
531 lines (464 loc) · 16.2 KB
/
Copy pathController.java
File metadata and controls
531 lines (464 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/*
* File: proj6BayyurtWenZhang.Controller.java
* Names: Izge Bayyurt, Muqing Wen, Chloe Zhang
* Class: CS361
* Project 6
* Date: 3/17/2022
*/
package proj6BayyurtWenZhang;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.*;
import org.fxmisc.richtext.CodeArea;
import org.fxmisc.richtext.Selection;
import org.fxmisc.richtext.StyleClassedTextArea;
import org.fxmisc.richtext.model.Paragraph;
import org.fxmisc.richtext.model.TwoDimensional;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Optional;
/**
* Controller handles ActionEvents for the Application.
*
*/
public class Controller {
@FXML
private TabPane tabPane;
@FXML
private MenuItem close;
@FXML
private MenuItem save;
@FXML
private MenuItem saveAs;
@FXML
private Menu edit;
@FXML
private Button compile;
@FXML
private Button compileAndRun;
@FXML
private Button stop;
@FXML
private StyleClassedTextArea console;
/** Stores the File contained by each tab.*/
private final HashMap<Tab, File> tabFileMap = new HashMap<>();
/** Stores whether the contents of each tab have changed since last save.*/
private final HashMap<Tab, Boolean> textHasChangedMap = new HashMap<>();
/** Helper objects for the Controller to use */
private TabHelper tabHelper;
private FileController fileController;
private DialogHelper dialogHelper;
private AlertHandler alertHandler;
/** records new tabs for untitled tab naming. */
private int numNewTabs = 1;
/** Thread to run compile and run in */
private Thread currentThread;
/** Objects to control output and input of the console */
public static OutputStream outputStream;
private String outputString = "";
/**
*
* Loads initial content on launch.
*/
@FXML
public void initialize() {
tabHelper = new TabHelper(tabPane, textHasChangedMap);
fileController = new FileController(tabHelper);
dialogHelper = new DialogHelper(tabPane, tabHelper, fileController, tabFileMap,
textHasChangedMap);
alertHandler = new AlertHandler();
tabHelper.createCodeAreaForTab(tabHelper.getCurrentTab());
tabHelper.getCurrentTab().setTooltip(new Tooltip("Untitled"));
stop.setDisable(true);
console.setOnKeyPressed(event -> {
handleInput(event);
});
}
/**
* Displays about dialog.
*
*/
@FXML
private void handleAbout(){
dialogHelper.aboutDialog();
}
/**
* Handles saving under a specified filepath.
*
*
*/
@FXML
private boolean handleSaveAs(){
return dialogHelper.saveAsDialog();
}
/**
* Saves a file if saved previously, else prompts to save as.
*/
@FXML
private void handleSave(){
Tab currentTab = tabHelper.getCurrentTab();
if(!tabFileMap.containsKey(currentTab)){
handleSaveAs();
}else{
boolean saved = fileController.saveCurrentFile(tabFileMap.get(currentTab));
if(saved){textHasChangedMap.put(currentTab, false);}
}
}
/**
* Opens a new Tab with a CodeArea.
*
*
*/
@FXML
private void handleNew(){
Tab newTab = new Tab("Untitled Tab " + numNewTabs++);
newTab.setOnCloseRequest(e -> handleClose());
newTab.setTooltip(new Tooltip(newTab.getText()));
tabPane.getTabs().add(newTab);
tabPane.getSelectionModel().select(newTab);
tabHelper.createCodeAreaForTab(newTab);
if(tabPane.getTabs().size() != 0){
close.setDisable(false);
save.setDisable(false);
saveAs.setDisable(false);
compile.setDisable(false);
compileAndRun.setDisable(false);
for (MenuItem item : edit.getItems())
{
item.setDisable(false);
}
}
}
/**
* Closes a tab if all changes have been saved, or prompts the
* user to save progress before closing.
* @return whether to continue with closing
*/
@FXML
private boolean handleClose(){
Tab currentTab = tabHelper.getCurrentTab();
if (currentTab == null){
return false;
}
if(!textHasChangedMap.get(currentTab)){
tabPane.getTabs().remove(currentTab);
}else{
Optional<ButtonType> result = dialogHelper.closeDialog();
if (result.get().getText().equals("Yes")){
handleSave();
return handleClose(); // remove tab if saved, else repeat
} else if (result.get().getText().equals("No")){
tabPane.getTabs().remove(currentTab);
} else {
return false; // user pressed cancel
}
}
if(tabPane.getTabs().size() == 0){
close.setDisable(true);
save.setDisable(true);
saveAs.setDisable(true);
compile.setDisable(true);
compileAndRun.setDisable(true);
for (MenuItem item : edit.getItems())
{
item.setDisable(true);
}
}
return true;
}
/**
* Opens a file into a new Tab and CodeArea.
*
*
*/
@FXML
private void handleOpen(){
dialogHelper.openDialog();
if(tabPane.getTabs().size() != 0){
close.setDisable(false);
save.setDisable(false);
saveAs.setDisable(false);
compile.setDisable(false);
compileAndRun.setDisable(false);
for (MenuItem item : edit.getItems())
{
item.setDisable(false);
}
}
}
/**
* Closes each tab and the Application after checking whether unsaved changes exist.
*/
@FXML
public void handleExit(){
boolean closing = true;
while (closing){
closing = handleClose();
}
if (tabHelper.getCurrentTab() == null) {
System.exit(0);
}
}
@FXML
/** Handles undo menu item */
private void handleUndo(){ tabHelper.getCurrentCodeArea().undo(); }
@FXML
/** Handles redo menu item */
private void handleRedo(){
tabHelper.getCurrentCodeArea().redo();
}
@FXML
/** Handles cut menu item */
private void handleCut(){
tabHelper.getCurrentCodeArea().cut();
}
@FXML
/** Handles copy menu item */
private void handleCopy(){
tabHelper.getCurrentCodeArea().copy();
}
@FXML
/** Handles paste menu item */
private void handlePaste(){
tabHelper.getCurrentCodeArea().paste();
}
@FXML
/** Handles selectAll menu item */
private void handleSelectAll(){
tabHelper.getCurrentCodeArea().selectAll();
}
/**
* handleJavaHelp that opens a link to java tutorials.
*
*/
@FXML
private void handleJavaHelp(){
try {
java.awt.Desktop.getDesktop().browse(new URI("https://docs.oracle.com/javase/tutorial/"));
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
/**
*
*Handles What's New
*/
@FXML
private void handleWhatsNew(){
dialogHelper.whatsnewDialog();
}
@FXML
/** Handles stop button */
private void stop(){
if(currentThread != null){
currentThread.interrupt();
}
}
@FXML
/** Handles commenting and uncommenting
* This method is implemented as such that the selected lines will be individually
* commented or uncommented, meaning that if some lines are commented and some are
* uncommented, it will toggle each individual line- not comment the whole block.
*/
private void handleComment(){
CodeArea codeArea = tabHelper.getCurrentCodeArea();
IndexRange selectionRange = tabHelper.getCurrentCodeArea().getSelection();
if (selectionRange.getLength() > 0){
Selection<?, ?, ?> selection = codeArea.getCaretSelectionBind();
int startVisibleParIdx = codeArea.
allParToVisibleParIndex(selection.getStartParagraphIndex()).get();
int endVisibleParIdx = Math.min(startVisibleParIdx + selection.getParagraphSpan(),
codeArea.getVisibleParagraphs().size());
// if we selected multiple blocks of paragraphs
if (endVisibleParIdx - startVisibleParIdx > 1) {
for (int i = startVisibleParIdx; i < endVisibleParIdx; i++) {
String line = codeArea.getText(i);
if (line.trim().startsWith("//")) {
String uncommentedLine = line.replaceFirst("//", "");
codeArea.replaceText(i, 0, i, line.length(), uncommentedLine);
} else {
codeArea.replaceText(i, 0, i, line.length(), "//" + line);
}
}
} else { // if we selected only one line
String line = codeArea.getText(startVisibleParIdx);
codeArea.replaceText(startVisibleParIdx, 0,
startVisibleParIdx, line.length(), "//" + line);
}
} else {
// Get the cursor position to figure out the paragraph
int offset = tabHelper.getCurrentCodeArea().getCaretPosition();
TwoDimensional.Position pos = tabHelper.getCurrentCodeArea().
offsetToPosition(offset, TwoDimensional.Bias.Forward);
Paragraph paragraph = tabHelper.getCurrentCodeArea().getParagraph(pos.getMajor());
// Once we have the paragraph, extract the text and see if we can comment/uncomment
String text = paragraph.getText();
StringBuilder commentedText = new StringBuilder();
String trimmedLine = text.trim();
if (trimmedLine.startsWith("//")) {
commentedText.append(text.replaceFirst("//", ""));
} else {
commentedText.append("//").append(text);
}
tabHelper.getCurrentCodeArea().replace(pos.getMajor(),0, pos.getMajor(),
paragraph.length(), commentedText.toString(),new ArrayList<String>());
}
}
/** Takes the string given to the console and writes it to the output stream */
private void handleInput(KeyEvent key) {
if (key.getCode() == KeyCode.ENTER){
try {
outputStream.write(outputString.getBytes(StandardCharsets.UTF_8));
outputStream.write(10); // 10 is the bytecode for new line
outputStream.flush();
outputString = "";
} catch (IOException ex) {
this.alertHandler.showAlert("IO Exception occured", "Error!");
}
}
else if (key.getCode() == KeyCode.BACK_SPACE) {
if (key.getText() != null && key.getText() != "") {
outputString = outputString.substring(0, outputString.length()-1);
}
}
else {
if (key.getText() != null && key.getText() != "") {
outputString += key.getText();
}
}
}
@FXML
/** Handles compile button*/
private boolean compile() {
File currentFile = tabFileMap.get(tabHelper.getCurrentTab());
// if the current file hasn't been saved before, save it first
if (currentFile == null) {
// if saving process is cancelled, do not continue with compiling
if (!handleSaveAs())
return false;
else
currentFile = tabFileMap.get(tabHelper.getCurrentTab());
}
// if the file has been changed since last save, give the save prompt
else if (textHasChangedMap.get(tabHelper.getCurrentTab())) {
Optional<ButtonType> saveResult = dialogHelper.saveDialog();
if (saveResult.get().getText().equals("Yes")) {
handleSave();
} else if (saveResult.get().getText().equals("No")) {
// if user presses no, don't do anything
} else {
return false; // user pressed cancel, quit the method
}
}
stop.setDisable(false);
final String[] message = {""};
File finalCurrentFile = currentFile;
// Start in new thread
this.currentThread = new Thread(() -> {
Compile comp = new Compile(finalCurrentFile, console);
comp.start();
while (true) {
if (Thread.interrupted()) {
comp.interrupt();
break;
}
if (!comp.isAlive()) {
break;
} else {
try {
comp.join(1);
} catch (InterruptedException e) {
Platform.runLater(() -> {
comp.interrupt();
this.alertHandler.showAlert("Compilation interrupted, exiting.",
"Process interruption!");
});
break;
}
}
}
if (comp.hasErrorMessage())
message[0] = comp.getErrorMessage();
stop.setDisable(true);
});
currentThread.start();
while (currentThread.isAlive()){
try {
currentThread.join();
} catch (InterruptedException e) {
this.alertHandler.showAlert("Compilation interrupted, exiting.",
"Process interruption!");
return false;
}
}
// display the compilation result message
console.append("******************\n", "");
if (message[0].length() > 0) {
console.append(message[0], "");
//return false;
} else {
console.append("Compilation successful!\n", "");
}
console.requestFollowCaret();
return true;
}
@FXML
/** Handles compile and run button*/
private void compileAndRun(){
// if we have error in compiling, do not run
if(!compile()){
return;
}
stop.setDisable(false);
final String[] message = {""};
this.currentThread = new Thread(() -> {
File currentFile = tabFileMap.get(tabHelper.getCurrentTab());
//stop.setDisable(false);
Run run = new Run(currentFile, console);
run.start();
while (true) {
if (Thread.interrupted()) {
run.interrupt();
break;
}
if(!run.isAlive()){
try {
outputStream.close();
} catch (IOException e) {
Platform.runLater(() -> {
run.killProcess();
alertHandler.showAlert("Error while closing outputStream",
"Error");
});
}
break;
}else {
try {
run.join(1);
} catch (InterruptedException e) {
Platform.runLater(() -> {
run.killProcess();
alertHandler.showAlert("Run interrupted", "Interrupted");
});
break;
}
}
}
if (run.hasErrorMessage())
message[0] = run.getErrorMessage();
stop.setDisable(true);
});
currentThread.start();
if (message[0].length()>0)
console.append(message[0], "");
else
console.append("Run Successful!\n", "");
console.append("******************\n\n", "");
console.requestFollowCaret();
}
}