diff --git a/.gitignore b/.gitignore index f69985ef1f..a401e5ac0c 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,7 @@ bin/ /text-ui-test/ACTUAL.txt text-ui-test/EXPECTED-UNIX.TXT +text-ui-test/data/chick.txt +data/chick.txt +src/main/resources/images/anya.jpg +src/main/resources/images/chick.png diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..b47d07c3b8 --- /dev/null +++ b/build.gradle @@ -0,0 +1,61 @@ +plugins { + id 'java' + id 'checkstyle' + id 'application' + id 'com.github.johnrengelman.shadow' version '5.1.0' +} + +repositories { + mavenCentral() +} + +checkstyle { + toolVersion = '10.2' +} + +dependencies { + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.5.0' + testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.5.0' + + String javaFxVersion = '11' + + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'linux' +} + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +application { + mainClassName = "chick.Launcher" +} + +shadowJar { + archiveBaseName = "chick" + archiveClassifier = null +} + +run { + standardInput = System.in +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000000..ded28679af --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000000..135ea49ee0 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index 8077118ebe..7b7893dcd2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,28 +2,227 @@ ## Features -### Feature-ABC +### Task List +Chick Bot features a task list which helps us keep track of and manage our tasks. -Description of the feature. +**Functionalities:** +1. Adding and removing tasks +2. Marking and unmarking tasks as done +3. Searching for tasks with keyword +4. Displaying of task list +5. Loading and saving of task list +6. Preventing duplicate tasks -### Feature-XYZ - -Description of the feature. +**Commands available:** +1. deadline +2. event +3. todo +4. mark +5. unmark +6. delete +7. find +8. list +9. bye +10. help ## Usage -### `Keyword` - Describe action +Chick Bot can be used with the following 10 commands. + +### 1. `deadline` + +Add a deadline task to the task list managed by Chick Bot. + +*Format*: `deadline {task_name} /by {yyyy-MM-dd}` + +**Example of usage:** + +`deadline ip /by 2022-09-16` + +**Expected outcome:** + +Adds the deadline task to task list. + +``` +Added: +[D][ ] ip (by: Sep-16-2022) +``` + +### 2. `event` + +Add an event task to the task list managed by Chick Bot. + +*Format*: `event {task_name} /at {yyyy-MM-dd}` + +**Example of usage:** + +`event project meeting /at 2022-09-21` + +**Expected outcome:** + +Adds the event task to task list. + +``` +Added: +[E][ ] project meeting (at: Sep-21-2022) +``` + +### 3. `todo` + +Add a todo task to the task list managed by Chick Bot. + +*Format*: `todo {task_name}` + +**Example of usage:** + +`todo sample todo task` + +**Expected outcome:** + +Adds the todo task to task list. + +``` +Added: +[T][ ] sample todo task +``` + +### 4. `mark` + +Marks a task in the task list as done. + +*Format*: `mark {task_index}` + +**Example of usage:** + +`mark 1` + +**Expected outcome:** + +Marks the task at the index as done. + +``` +Marked: +[T][X] sample todo task +``` + +### 5. `unmark` + +Marks a task in the task list as not done. + +*Format*: `unmark {task_index}` + +**Example of usage:** + +`unmark 1` -Describe the action and its outcome. +**Expected outcome:** -Example of usage: +Marks the task at the index as not done. -`keyword (optional arguments)` +``` +Unmarked: +[T][ ] sample todo task +``` + +### 6. `delete` + +Removes a task in the task list. + +*Format*: `delete {task_index}` + +**Example of usage:** + +`delete 1` + +**Expected outcome:** + +Removes the task at the index. + +``` +Removed: +[T][ ] sample todo task +``` + +### 7. `find` + +Search for tasks given by a keyword and displays them. + +*Format*: `find {keyword}` + +**Example of usage:** + +`find sample` + +**Expected outcome:** + +Display tasks containing "sample". + +``` +Here: +[T][ ] sample todo task +``` + +### 8. `list` -Expected outcome: +Displays all tasks in the task list. -Description of the outcome. +*Format*: `list` +**Example of usage:** + +`list` + +**Expected outcome:** + +Display all tasks. + +``` +Here: +1. [T][ ] sample todo task ``` -expected output + +### 9. `bye` + +Exits Chick Bot and saves task list. + +*Format*: `bye` + +**Example of usage:** + +`bye` + +**Expected outcome:** + +Exit and save task list. + +``` +bye +``` + +### 10. `help` + +Displays a list of commands available for Chick Bot. + +*Format*: `help` + +**Example of usage:** + +`help` + +**Expected outcome:** + +Display list of available commands. + ``` +Commands: +deadline {task_name} /by {YYYY-mm-dd} +event {task_name} /at {YYYY-mm-dd} +todo {task_name} +mark {task_index} +unmark {task_index} +delete {task_index} +find {keyword} +list +bye +help +``` \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..3f27a7a63c Binary files /dev/null and b/docs/Ui.png differ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..f3d88b1c2f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..b7c8c5dbf5 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000..2fe81a7d95 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000000..62bd9b9cce --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,103 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/Duke.java b/src/main/java/Duke.java deleted file mode 100644 index 5d313334cc..0000000000 --- a/src/main/java/Duke.java +++ /dev/null @@ -1,10 +0,0 @@ -public class Duke { - public static void main(String[] args) { - String logo = " ____ _ \n" - + "| _ \\ _ _| | _____ \n" - + "| | | | | | | |/ / _ \\\n" - + "| |_| | |_| | < __/\n" - + "|____/ \\__,_|_|\\_\\___|\n"; - System.out.println("Hello from\n" + logo); - } -} diff --git a/src/main/java/chick/Chick.java b/src/main/java/chick/Chick.java new file mode 100644 index 0000000000..ec61fc8485 --- /dev/null +++ b/src/main/java/chick/Chick.java @@ -0,0 +1,67 @@ +package chick; + +/** + * Main class representing Chick Bot which is also a Duke Bot. + */ +public class Chick { + protected Ui ui; + protected TaskList tasks; + protected Parser parser; + + private boolean isChickRunning; + + /** + * Class constructor for Chick Bot. + */ + public Chick() { + ui = new Ui(); + ui.printLogo(); + tasks = new TaskList(ui); + parser = new Parser(tasks, this, ui); + tasks.loadTasks(parser); + isChickRunning = true; + } + + /** + * Returns the next line input by user. + * + * @return String input by user. + */ + public String getNextLine() { + return ui.getNextLine(); + } + + /** + * Parses and executes a command string. + * + * @param command Command string to be parsed and executed. + * @return Response string from Duke Bot. + */ + public String parseCommand(String command) { + try { + return parser.parse(command, true); + } catch (ChickException e) { + return ui.printMessage(e.getMessage()); + } + } + + /** + * Terminates running of Duke Bot. + * This method sets the runningDuke flag to false. + */ + public void terminate() { + isChickRunning = false; + } + + /** + * Main method to run Duke Bot. + * @param args Unused input arguments. + */ + public static void main(String[] args) { + Chick chick = new Chick(); + while (chick.isChickRunning) { + String userInput = chick.getNextLine(); + chick.parseCommand(userInput); + } + } +} diff --git a/src/main/java/chick/ChickException.java b/src/main/java/chick/ChickException.java new file mode 100644 index 0000000000..8489c8454c --- /dev/null +++ b/src/main/java/chick/ChickException.java @@ -0,0 +1,15 @@ +package chick; + +/** + * Class representing DukeException, a custom exception for Duke Bot. + */ +public class ChickException extends Exception { + /** + * Class constructor for DukeException. + * + * @param message Error message for DukeException. + */ + public ChickException(String message) { + super(message); + } +} diff --git a/src/main/java/chick/DialogBox.java b/src/main/java/chick/DialogBox.java new file mode 100644 index 0000000000..4338f3dd5b --- /dev/null +++ b/src/main/java/chick/DialogBox.java @@ -0,0 +1,72 @@ +package chick; + +import java.io.IOException; +import java.util.Collections; + +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; +import javafx.geometry.Pos; +import javafx.scene.Node; +import javafx.scene.control.Label; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.HBox; + +/** + * Javafx DialogBox for Duke Bot GUI. + */ +public class DialogBox extends HBox { + @FXML + private Label dialog; + @FXML + private ImageView displayPicture; + + private DialogBox(String text, Image img) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(MainWindow.class.getResource("/view/DialogBox.fxml")); + fxmlLoader.setController(this); + fxmlLoader.setRoot(this); + fxmlLoader.load(); + } catch (IOException e) { + e.printStackTrace(); + } + dialog.setText(text); + displayPicture.setImage(img); + } + + /** + * Flips the dialog box such that the ImageView is on the left and text on the right. + */ + private void flip() { + ObservableList tmp = FXCollections.observableArrayList(this.getChildren()); + Collections.reverse(tmp); + getChildren().setAll(tmp); + setAlignment(Pos.TOP_LEFT); + } + + /** + * Creates an instance of DialogBox for the user. + * + * @param text Text input from user. + * @param img Profile picture for user. + * @return Instance of dialogue box for user. + */ + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + /** + * Creates an instance of DialogBox for Duke Bot. + * + * @param text Text input from Duke Bot. + * @param img Profile picture for Duke Bot. + * @return Instance of dialogue box for Duke Bot. + */ + public static DialogBox getDukeDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/chick/Launcher.java b/src/main/java/chick/Launcher.java new file mode 100644 index 0000000000..165cbba1f2 --- /dev/null +++ b/src/main/java/chick/Launcher.java @@ -0,0 +1,12 @@ +package chick; + +import javafx.application.Application; + +/** + * A launcher class to workaround classpath issues. + */ +public class Launcher { + public static void main(String[] args) { + Application.launch(Main.class, args); + } +} diff --git a/src/main/java/chick/Main.java b/src/main/java/chick/Main.java new file mode 100644 index 0000000000..9e1a988367 --- /dev/null +++ b/src/main/java/chick/Main.java @@ -0,0 +1,32 @@ +package chick; + +import java.io.IOException; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.scene.layout.AnchorPane; +import javafx.stage.Stage; + +/** + * A GUI for Duke using FXML. + */ +public class Main extends Application { + + private Chick chick = new Chick(); + + @Override + public void start(Stage stage) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/view/MainWindow.fxml")); + AnchorPane ap = fxmlLoader.load(); + Scene scene = new Scene(ap); + stage.setScene(scene); + stage.setTitle("Chick Bot"); + fxmlLoader.getController().setChick(chick); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/chick/MainWindow.java b/src/main/java/chick/MainWindow.java new file mode 100644 index 0000000000..d6e499d885 --- /dev/null +++ b/src/main/java/chick/MainWindow.java @@ -0,0 +1,62 @@ +package chick; + +import javafx.application.Platform; +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.image.Image; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.VBox; + +/** + * Controller for MainWindow. Provides the layout for the other controls. + */ +public class MainWindow extends AnchorPane { + @FXML + private ScrollPane scrollPane; + @FXML + private VBox dialogContainer; + @FXML + private TextField userInput; + @FXML + private Button sendButton; + + private Chick chick; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/chick_red_nobg.png")); + private Image chickImage = new Image(this.getClass().getResourceAsStream("/images/chick_nobg.png")); + + /** + * Initialize MainWindow. + */ + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + dialogContainer.getChildren().addAll( + DialogBox.getDukeDialog("whats up", chickImage) + ); + } + + public void setChick(Chick d) { + chick = d; + } + + /** + * Creates two dialog boxes, one echoing user input and the other containing Duke's reply and then appends them to + * the dialog container. Clears the user input after processing. + */ + @FXML + private void handleUserInput() { + String input = userInput.getText(); + String response = chick.parseCommand(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDukeDialog(response, chickImage) + ); + userInput.clear(); + if (response.equals("bye")) { + Platform.exit(); + } + } +} diff --git a/src/main/java/chick/Parser.java b/src/main/java/chick/Parser.java new file mode 100644 index 0000000000..95e7ff6444 --- /dev/null +++ b/src/main/java/chick/Parser.java @@ -0,0 +1,185 @@ +package chick; + +import java.time.format.DateTimeParseException; + +import chick.task.DeadlineTask; +import chick.task.EventTask; +import chick.task.Task; +import chick.task.TodoTask; + +/** + * Class that handles parsing and execution of command strings for Duke Bot commands. + */ +public class Parser { + private static String[] commandList = new String[] {"deadline {task_name} /by {YYYY-mm-dd}", + "event {task_name} /at {YYYY-mm-dd}", + "todo {task_name}", + "mark {task_index}", + "unmark {task_index}", + "delete {task_index}", + "find {keyword}", + "list", + "bye", + "help"}; + + private TaskList tasks; + private Chick chick; + private Ui ui; + private int parseErrorCount; + + /** + * Class constructor for Parser. + * + * @param taskList TaskList instance tracking tasks in Duke Bot. + * @param chickInstance Duke instance representing Duke Bot. + * @param uiInstance Ui instance representing user interface for Duke Bot. + */ + public Parser(TaskList taskList, Chick chickInstance, Ui uiInstance) { + tasks = taskList; + chick = chickInstance; + ui = uiInstance; + parseErrorCount = 0; + } + + /** + * Parses and executes a command for Duke Bot. + * Verbose argument can be used to control output of Ui. + * + * @param command Command string for parsing and execution. + * @param isVerbose Boolean to indicate verbosity of Ui. + * @return Response string from Duke Bot. + * @throws ChickException If command cannot be parsed or is invalid. + */ + public String parse(String command, boolean isVerbose) throws ChickException { + ui.setVerbose(isVerbose); + if (command.startsWith("deadline ") || command.startsWith("event ") || command.startsWith("todo ")) { + return parseTask(command); + } else if (command.startsWith("mark") || command.startsWith("unmark") || command.startsWith("delete")) { + return parseTwo(command); + } else if (command.startsWith("find")) { + return parseFind(command); + } else if (command.startsWith("list") || command.startsWith("bye") || command.startsWith("help")) { + return parseOne(command); + } else { + parseErrorCount++; + String response; + if (parseErrorCount > 5) { + response = "oi"; + } else if (parseErrorCount > 3) { + response = "stop it"; + } else if (command.length() > 10) { + response = "bruh"; + } else { + String[] chickResponses = new String[] {"??", "lmao"}; + int responseIndex = (int) Math.round(Math.random() * (chickResponses.length - 0.5)); + response = chickResponses[responseIndex]; + } + throw new ChickException(response); + } + } + + /** + * Parses and executes task commands for Duke Bot. + * Task commands are in the format "task description separator time". + * + * @param command Task command string. + * @return Response string from Duke Bot. + * @throws ChickException If command cannot be parsed or is invalid. + */ + public String parseTask(String command) throws ChickException { + parseErrorCount = 0; + Task t = null; + try { + if (command.startsWith("deadline")) { + t = new DeadlineTask(command); + } else if (command.startsWith("event")) { + t = new EventTask(command); + } else if (command.startsWith("todo")) { + t = new TodoTask(command); + } + assert t != null; + return tasks.addTask(t); + } catch (DateTimeParseException e) { + throw new ChickException("wrong date format, use yyyy-MM-dd"); + } + } + + /** + * Parses and executes commands that are two parts long for Duke Bot. + * Two part long commands contains one whitespace after command. + * Two part long commands are in the format "command description". + * + * @param command Two part long command. + * @return Response string from Duke Bot. + * @throws ChickException If command cannot be parsed or is invalid. + */ + public String parseTwo(String command) throws ChickException { + parseErrorCount = 0; + String[] commandSplit = command.split(" ", 2); + String commandName = commandSplit[0]; + int id = tasks.getSize(); + if (commandSplit.length > 1) { + try { + id = Integer.parseInt(commandSplit[1]); + } catch (NumberFormatException e) { + throw new ChickException("Please input a valid number."); + } + } else if (id == 0) { + throw new ChickException("Task list is empty."); + } + + if (commandName.equals("delete")) { + return tasks.deleteTask(id - 1); + } else if (commandName.equals("mark")) { + return tasks.markTask(id - 1); + } else if (commandName.equals("unmark")) { + return tasks.unmarkTask(id - 1); + } else { + throw new ChickException("Unknown command"); + } + } + + /** + * Parses and executes find command for Duke Bot. + * + * @param command Find command. + * @return Response string from Duke Bot. + * @throws ChickException If command cannot be parsed or is invalid. + */ + public String parseFind(String command) throws ChickException { + parseErrorCount = 0; + String[] commandSplit = command.split(" ", 2); + if (commandSplit.length < 2) { + throw new ChickException("Please input string for find."); + } + return tasks.findTask(commandSplit[1]); + } + + /** + * Parses and executes commands that are one part long for Duke Bot. + * One part long commands are in the format "command". + * + * @param command One part long command. + * @return Response string from Duke Bot. + * @throws ChickException If command cannot be parsed or is invalid. + */ + public String parseOne(String command) throws ChickException { + parseErrorCount = 0; + if (command.startsWith("bye")) { + tasks.saveTasks(); + chick.terminate(); + return "bye"; + } else if (command.startsWith("list")) { + return tasks.generateList(); + } else if (command.startsWith("help")) { + String commandString = "Commands:\n"; + for (String commandName: commandList) { + commandString += commandName; + commandString += "\n"; + } + return commandString; + } else { + throw new ChickException("Invalid command format."); + } + } +} diff --git a/src/main/java/chick/Storage.java b/src/main/java/chick/Storage.java new file mode 100644 index 0000000000..bb0584a35e --- /dev/null +++ b/src/main/java/chick/Storage.java @@ -0,0 +1,63 @@ +package chick; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Class that handles loading and saving of tasks for Duke Bot. + */ +public class Storage { + + private String previousText; + + /** + * Class constructor for Storage. + * + * Calling the constructor will: + * 1. Create a data folder if it doesn't already exist. + * 2. Load text at data/duke.txt if it exists. + */ + public Storage() { + File dataFolder = new File("data"); + if (!dataFolder.exists()) { + // make data directory if it doesnt exist + dataFolder.mkdir(); + assert dataFolder.exists(); + } else if (new File("data/chick.txt").exists()) { + // else if save file exists, load it into memory + try { + previousText = Files.readString(Path.of("data/chick.txt")); + } catch (java.io.IOException e) { + System.out.println("Unable to read storage file: " + e); + } + } + } + + /** + * Returns saved text from previous instance of Duke Bot. + * + * @return Saved text from previous instance of Duke Bot. + */ + public String getPreviousText() { + return previousText; + } + + /** + * Writes a string to save file of Duke Bot. + * + * @param storageString String to be written to save file. + */ + public void saveText(String storageString) { + try { + assert new File("data/chick.txt").exists(); + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("data/chick.txt")); + bufferedWriter.write(storageString); + bufferedWriter.close(); + } catch (java.io.IOException e) { + System.out.println("Failed to write text to save file: " + e); + } + } +} diff --git a/src/main/java/chick/TaskList.java b/src/main/java/chick/TaskList.java new file mode 100644 index 0000000000..1a69c364f2 --- /dev/null +++ b/src/main/java/chick/TaskList.java @@ -0,0 +1,184 @@ +package chick; + +import java.util.ArrayList; +import java.util.HashSet; + +import chick.task.Task; + +/** + * Class that stores and manipulates tasks for Duke Bot. + */ +public class TaskList { + protected final ArrayList tasks; + private final Storage store; + private final Ui ui; + private final HashSet taskSet; + + /** + * Class constructor for TaskList. + * + * @param uiInstance Ui instance being used in Duke Bot. + */ + public TaskList(Ui uiInstance) { + tasks = new ArrayList<>(); + store = new Storage(); + ui = uiInstance; + taskSet = new HashSet<>(); + } + + /** + * Adds a task to TaskList. + * + * @param task Task to be added. + * @return Response string from Duke Bot. + * @throws ChickException If duplicate task is added. + */ + public String addTask(Task task) throws ChickException { + if (taskSet.contains(task.toStorageString())) { + throw new ChickException("no duplicate tasks pls"); + } + tasks.add(task); + taskSet.add(task.toStorageString()); + saveTasks(); + return ui.printMessage("Added:\n " + + task + + "\n Total " + + tasks.size() + + " tasks."); + } + + /** + * Deletes a task from TaskList. + * + * @param id Index of task to be deleted. Index is numbering from calling "list" command. + * @return Response string from Duke Bot. + * @throws ChickException If id is out of bounds. + */ + public String deleteTask(int id) throws ChickException { + if (id < 0 || id >= tasks.size()) { + throw new ChickException("proper index pls"); + } + Task t = tasks.remove(id); + taskSet.remove(t.toStorageString()); + saveTasks(); + return ui.printMessage("Removed:\n " + + t + + "\n Total " + + tasks.size() + + " tasks."); + } + + /** + * Marks a task from TaskList as done. + * + * @param id Index of task to be marked. Index is numbering from calling "list" command. + * @return Response string from Duke Bot. + * @throws ChickException If id is out of bounds. + */ + public String markTask(int id) throws ChickException { + if (id < 0 || id >= tasks.size()) { + throw new ChickException("proper index pls"); + } + Task t = tasks.get(id); + boolean statusChanged = t.setAsDone(); + if (statusChanged) { + saveTasks(); + } + return ui.printMessage("Marked:\n " + t); + } + + /** + * Marks a task from TaskList as undone. + * + * @param id Index of task to be unmarked. Index is numbering from calling "list" command. + * @return Response string from Duke Bot. + * @throws ChickException If id is out of bounds. + */ + public String unmarkTask(int id) throws ChickException { + if (id < 0 || id >= tasks.size()) { + throw new ChickException("proper index pls"); + } + Task t = tasks.get(id); + boolean statusChanged = t.setAsUndone(); + if (statusChanged) { + saveTasks(); + } + return ui.printMessage("Unmarked:\n " + t); + } + + /** + * Prints list of tasks in TaskList that contains identifier. + * + * @param identifier String to search for tasks. + * @return Response string from Duke Bot. + */ + public String findTask(String identifier) { + StringBuilder messageList = new StringBuilder(); + int taskCount = 1; + for (Task t: tasks) { + if (t.getDescription().contains(identifier)) { + messageList.append("\n ").append(taskCount++).append(". ").append(t); + } + } + return ui.printMessage("Here:" + messageList); + } + + /** + * Returns number of tasks in TaskList + * + * @return Size of TaskList. + */ + public int getSize() { + return tasks.size(); + } + + /** + * Prints list representation of TaskList. + * Ui instance is used to print this list. + * + * @return Response string from Duke Bot. + */ + public String generateList() { + StringBuilder messageList = new StringBuilder(); + int taskCount = 1; + for (Task t: tasks) { + messageList.append("\n ").append(taskCount++).append(". ").append(t); + } + return ui.printMessage("Here:" + messageList); + } + + /** + * Loads tasks from previous instance of Duke Bot. + * Previous tasks are obtained from an instance of Storage. + * These previous tasks are presented as Duke Bot commands and are loaded back into TaskList by parsing them. + * + * @param parser Parser being used for Duke Bot. + */ + public void loadTasks(Parser parser) { + String tasks = store.getPreviousText(); + if (tasks == null) { + return; + } + String[] taskSplit = tasks.split("\n"); + for (String s: taskSplit) { + try { + parser.parse(s, false); + } catch (ChickException e) { + System.out.println("Failed to load saved tasks: " + e); + } + } + } + + /** + * Saves tasks from current TaskList. + * Tasks are saved using an instance of Storage. + */ + public void saveTasks() { + StringBuilder storageString = new StringBuilder(); + for (Task t : tasks) { + storageString.append(t.toStorageString()); + storageString.append("\n"); + } + store.saveText(storageString.toString()); + } +} diff --git a/src/main/java/chick/Ui.java b/src/main/java/chick/Ui.java new file mode 100644 index 0000000000..c5ba0a9c6f --- /dev/null +++ b/src/main/java/chick/Ui.java @@ -0,0 +1,68 @@ +package chick; + +import java.util.Scanner; + +/** + * Class that handles user interface of Duke Bot. + */ +public class Ui { + public static final String LOGO = " ____ _ \n" + + "| _ \\ _ _| | _____ \n" + + "| | | | | | | |/ / _ \\\n" + + "| |_| | |_| | < __/\n" + + "|____/ \\__,_|_|\\_\\___|\n"; + private Scanner scanner; + private boolean isVerbose; + + /** + * Class constructor for Ui. + */ + public Ui() { + scanner = new Scanner(System.in); + isVerbose = true; + } + + /** + * Gets the next line of user input. + * + * @return Next line of user input. + */ + public String getNextLine() { + return scanner.nextLine(); + } + + /** + * Prints the logo of Duke Bot. + */ + public void printLogo() { + if (isVerbose) { + System.out.println("Hello from\n" + LOGO); + } + } + + /** + * Formats and prints a string. + * + * @param message Message string to be printed. + * @return The formatted and printed message. + */ + public String printMessage(String message) { + String formattedMessage = " __________________________________________________\n " + + message + + "\n __________________________________________________\n"; + if (isVerbose) { + System.out.println(formattedMessage); + } + return message; + } + + /** + * Sets the verbosity of user interface. + * Verbosity determines whether the user interface prints messages. + * + * @param verbosity Value of verbosity. + */ + public void setVerbose(boolean verbosity) { + isVerbose = verbosity; + } +} diff --git a/src/main/java/chick/task/DeadlineTask.java b/src/main/java/chick/task/DeadlineTask.java new file mode 100644 index 0000000000..53ca192895 --- /dev/null +++ b/src/main/java/chick/task/DeadlineTask.java @@ -0,0 +1,42 @@ +package chick.task; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +import chick.ChickException; + +/** + * Class representing a DeadlineTask. + */ +public class DeadlineTask extends Task { + protected LocalDate by; + + /** + * Class constructor for DeadlineTask. + * + * @param description Command string being used to create DeadlineTask. + * @throws DateTimeParseException If datetime given cannot be parsed. + * @throws ChickException If command is invalid. + */ + public DeadlineTask(String description) throws DateTimeParseException, ChickException { + super(); + this.commandString = description; + int descriptionStartIndex = "deadline ".length(); + description = description.substring(descriptionStartIndex); + String[] split = description.split(" /by "); + int correctSplitCount = 2; + if (split.length < correctSplitCount) { + throw new ChickException("Deadline description or deadline time is missing."); + } else if (split.length > correctSplitCount) { + throw new ChickException("Multiple usage of /by separator is not allowed."); + } + this.description = split[0]; + this.by = LocalDate.parse(split[1]); + } + + @Override + public String toString() { + return "[D]" + super.toString() + " (by: " + by.format(DateTimeFormatter.ofPattern("MMM-dd-yyyy")) + ")"; + } +} diff --git a/src/main/java/chick/task/EventTask.java b/src/main/java/chick/task/EventTask.java new file mode 100644 index 0000000000..bf6fe74c35 --- /dev/null +++ b/src/main/java/chick/task/EventTask.java @@ -0,0 +1,43 @@ +package chick.task; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +import chick.ChickException; + +/** + * Class representing an EventTask. + */ +public class EventTask extends Task { + protected LocalDate at; + + /** + * Class constructor for EventTask. + * + * @param description Command string being used to create EventTask. + * @throws DateTimeParseException If datetime given cannot be parsed. + * @throws ChickException If command is invalid. + */ + public EventTask(String description) throws DateTimeParseException, ChickException { + super(); + this.commandString = description; + int descriptionStartIndex = "event ".length(); + description = description.substring(descriptionStartIndex); + String[] split = description.split(" /at "); + int correctSplitCount = 2; + if (split.length < correctSplitCount) { + throw new ChickException("Event description or event time is missing."); + } else if (split.length > correctSplitCount) { + throw new ChickException("Multiple usage of /by separator is not allowed."); + } + this.description = split[0]; + this.at = LocalDate.parse(split[1]); + } + + @Override + public String toString() { + return "[E]" + super.toString() + " (at: " + at.format(DateTimeFormatter.ofPattern("MMM-dd-yyyy")) + ")"; + } + +} diff --git a/src/main/java/chick/task/Task.java b/src/main/java/chick/task/Task.java new file mode 100644 index 0000000000..5442fed541 --- /dev/null +++ b/src/main/java/chick/task/Task.java @@ -0,0 +1,87 @@ +package chick.task; + +/** + * Abstract class representing a Task for Duke Bot. + */ +public abstract class Task { + protected String description; + protected String commandString; + protected boolean isDone; + + /** + * Constructor for Task. + */ + public Task() { + this.isDone = false; + } + + /** + * Gets a string representing whether Task is done or not. + * + * @return "X" if task is done, " " if task is not yet done. + */ + public String getStatusIcon() { + return (isDone ? "X" : " "); // mark done task with X + } + + /** + * Marks current Task as done. + * + * @return Whether task status changed. + */ + public boolean setAsDone() { + boolean previousStatus = isDone; + isDone = true; + return !previousStatus; + } + + /** + * Marks current Task as not done. + * + * @return Whether task status changed. + */ + public boolean setAsUndone() { + boolean previousStatus = isDone; + isDone = false; + return previousStatus; + } + + /** + * Returns string representation of Task. + * This representation is formatted with the status icon. + * + * @return String representation of Task. + */ + public String toString() { + assert description != null; + return "[" + getStatusIcon() + "] " + this.description; + } + + /** + * Returns description of Task. + * + * @return Description string of Task. + */ + public String getDescription() { + return description; + } + + /** + * Returns string representation of Task for storage purposes. + * This string representation is the command used to create and store the Task. + * + * @return String representation of Task for storage purposes. + */ + public String toStorageString() { + assert commandString != null; + return isDone ? commandString + "\nmark" : commandString; + } + + @Override + public boolean equals(Object task) { + if (task instanceof Task) { + return ((Task) task).toStorageString().equals(toStorageString()); + } + return false; + } +} diff --git a/src/main/java/chick/task/TodoTask.java b/src/main/java/chick/task/TodoTask.java new file mode 100644 index 0000000000..faa816463a --- /dev/null +++ b/src/main/java/chick/task/TodoTask.java @@ -0,0 +1,30 @@ +package chick.task; + +import chick.ChickException; + +/** + * Class representing a TodoTask. + */ +public class TodoTask extends Task { + /** + * Class constructor for TodoTask. + * + * @param description Command string being used to create TodoTask. + * @throws ChickException If command is invalid. + */ + public TodoTask(String description) throws ChickException { + super(); + this.commandString = description; + int descriptionStartIndex = "todo ".length(); + description = description.substring(descriptionStartIndex); + if (description.length() <= 0) { + throw new ChickException("The description of a todo cannot be empty."); + } + this.description = description; + } + + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/resources/images/chick_nobg.png b/src/main/resources/images/chick_nobg.png new file mode 100644 index 0000000000..162d371c49 Binary files /dev/null and b/src/main/resources/images/chick_nobg.png differ diff --git a/src/main/resources/images/chick_red_nobg.png b/src/main/resources/images/chick_red_nobg.png new file mode 100644 index 0000000000..1d70393756 Binary files /dev/null and b/src/main/resources/images/chick_red_nobg.png differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..da72905877 --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..7d61c83e40 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,19 @@ + + + + + + + + + + + +