diff --git a/.gitignore b/.gitignore index f69985ef1f..0032e353f2 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,7 @@ # Gradle build files /.gradle/ /build/ -src/main/resources/docs/ +src/duke.main/resources/docs/ # MacOS custom attributes files created by Finder .DS_Store diff --git a/README.md b/README.md index 8715d4d915..317859c75e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Duke project template +# duke.main.Duke project template This is a project template for a greenfield Java project. It's named after the Java mascot _Duke_. Given below are instructions on how to use it. @@ -13,7 +13,7 @@ Prerequisites: JDK 11, update Intellij to the most recent version. 1. If there are any further prompts, accept the defaults. 1. Configure the project to use **JDK 11** (not other versions) as explained in [here](https://www.jetbrains.com/help/idea/sdk.html#set-up-jdk).
In the same dialog, set the **Project language level** field to the `SDK default` option. -3. After that, locate the `src/main/java/Duke.java` file, right-click it, and choose `Run Duke.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: +3. After that, locate the `src/duke.main/java/duke.main.Duke.java` file, right-click it, and choose `Run duke.main.Duke.duke.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: ``` Hello from ____ _ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..452aae7437 --- /dev/null +++ b/build.gradle @@ -0,0 +1,60 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '5.1.0' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.testng:testng:6.14.3' + 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.0.2' + 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 + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + +application { + mainClassName = "duke.main.Launcher" +} + +shadowJar { + archiveBaseName = "snoopy" + archiveClassifier = null +} + +run{ + standardInput = System.in +} diff --git a/docs/README.md b/docs/README.md index 8077118ebe..da7b08ae0a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,29 +1,69 @@ # User Guide +This repo contains the code for the Snoopy chatbot. +Snoopy is optimized for use via a Graphical User Interface (GUI). + +Snoopy is supported by Java 11 and up. + +Let Snoopy help you with your task management, starting today! + ## Features -### Feature-ABC +### Add a todo task: `todo` -Description of the feature. +Adds a standard todo task to the list. -### Feature-XYZ +### Add a deadline task: `deadline` -Description of the feature. +Adds task with a deadline to the list. -## Usage +### Add an event task: `event` + +Adds a task with a start and end time to the list. + +### List out all tasks: `list` + +Obtains full list of tasks. + +### Mark task as complete: `mark` + +Marks selected task as complete. -### `Keyword` - Describe action +### Unmark task as complete: `unmark` -Describe the action and its outcome. +Marks selected task as not completed. -Example of usage: +### Find tasks: `find` -`keyword (optional arguments)` +Obtains list of tasks that match specified keyword. -Expected outcome: +### Delete tasks: `delete` -Description of the outcome. +Delete specified task from the list. + +### Mark as high priority: `priority` + +Marks selected task as high priority. High priority tasks will be bumped to the top of the list. + +### Exit Snoopy: `bye` + +Closes program. + +### Save tasks + +Tasks are automatically saved and loaded up the next time Snoopy is run. + +## Usage -``` -expected output -``` +Keyword | Usage +---------|----------- +**Todo** | `todo DESCRIPTION`
e.g. `todo have lunch` +**Deadline** | `deadline DESCRIPTION /by yyyy-mm-dd`
e.g. `deadline submit homework /by 2022-09-10` +**Event** | `event DESCRIPTION /at DATE`
e.g. `event graduation /at 6 March 9-11am` +**List** | `list` +**Mark** | `mark TASKNUMBER`
e.g. `mark 2` +**Unmark** | `unmark TASKNUMBER`
e.g. `unmark 2` +**Delete** | `delete TASKNUMBER`
e.g. `delete 2` +**Find** | `find KEYWORD`
e.g. `find eat` +**Priority** | `priority TASKNUMBER`
e.g. `priority 3` +**Bye** | `bye` diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..15a4cc63c9 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..a4b4429748 --- /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.3-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/duke/command/TaskList.java b/src/main/java/duke/command/TaskList.java new file mode 100644 index 0000000000..9683923e68 --- /dev/null +++ b/src/main/java/duke/command/TaskList.java @@ -0,0 +1,110 @@ +package duke.command; + +import duke.task.Task; + +import java.util.ArrayList; + +/** + * Stores list of tasks and related commands. + */ +public class TaskList { + private final ArrayList taskList; + + /** + * Constructs an empty list. + */ + public TaskList() { + this.taskList = new ArrayList<>(); + } + + /** + * Constructs TaskList with given list of tasks. + * @param taskList List of tasks. + */ + public TaskList(ArrayList taskList) { + this.taskList = taskList; + } + + /** + * Obtains list of tasks. + * @return List of tasks. + */ + public ArrayList getTasks() { + return this.taskList; + } + + /** + * Marks desired task as done. + * @param taskNumber Task number. + */ + public String markAsDone(int taskNumber) { + return taskList.get(taskNumber - 1).markAsDone(); + } + + /** + * Marks desired task as not done. + * @param taskNumber Task number. + */ + public String markNotDone(int taskNumber) { + return taskList.get(taskNumber - 1).markNotDone(); + } + + public String markHighPriority(int taskNumber) { + String output = taskList.get(taskNumber - 1).markAsPriority(); + taskList.sort((t1, t2) -> { + if (t1.checkPriority() && t2.checkPriority()) { + return 0; + } else if (t1.checkPriority() && !t2.checkPriority()) { + return -1; + } else { + return 1; + } + }); + return output; + } + + /** + * Removes desired task from list. + * @param taskNumber Task number. + */ + public void deleteTask(int taskNumber) { + taskList.remove(taskNumber - 1); + } + + /** + * Obtains relevant task from list. + * @param taskNumber Task number. + * @return required task. + */ + public Task retrieveTask(int taskNumber) { + return this.taskList.get(taskNumber - 1); + } + + /** + * Obtains size of the list. + * @return Size of list. + */ + public int getListSize() { + return taskList.size(); + } + + /** + * Adds task to the list. + * @param task Task to be added. + */ + public void addTask(Task task) { + taskList.add(task); + } + + public ArrayList searchTasks(String keyword) { + ArrayList matchingList = new ArrayList<>(); + for (Task task : taskList) { + String description = task.getDescription(); + if (description.contains(keyword)) { + matchingList.add(task); + } + } + return matchingList; + } + +} diff --git a/src/main/java/duke/exception/DukeException.java b/src/main/java/duke/exception/DukeException.java new file mode 100644 index 0000000000..ce34365cab --- /dev/null +++ b/src/main/java/duke/exception/DukeException.java @@ -0,0 +1,7 @@ +package duke.exception; + +/** + * Represents DukeException. + */ +public class DukeException extends Exception { +} diff --git a/src/main/java/duke/exception/EmptyTodoListException.java b/src/main/java/duke/exception/EmptyTodoListException.java new file mode 100644 index 0000000000..eded33e211 --- /dev/null +++ b/src/main/java/duke/exception/EmptyTodoListException.java @@ -0,0 +1,13 @@ +package duke.exception; + +/** + * Represents exception when todo command is run without providing description. + */ +public class EmptyTodoListException extends Exception { + /** + * Constructs an EmptyTodoListException. + */ + public EmptyTodoListException() { + super("OOPS!!! The description of a todo cannot be empty."); + } +} diff --git a/src/main/java/duke/exception/InvalidCommandException.java b/src/main/java/duke/exception/InvalidCommandException.java new file mode 100644 index 0000000000..b48052533e --- /dev/null +++ b/src/main/java/duke/exception/InvalidCommandException.java @@ -0,0 +1,13 @@ +package duke.exception; + +/** + * Represents exception when invalid command is run. + */ +public class InvalidCommandException extends Exception { + /** + * Constructs an InvalidCommandException. + */ + public InvalidCommandException() { + super("OOPS!!! I'm sorry, but I don't know what that means :-("); + } +} diff --git a/src/main/java/duke/main/DialogBox.java b/src/main/java/duke/main/DialogBox.java new file mode 100644 index 0000000000..d60ac48abe --- /dev/null +++ b/src/main/java/duke/main/DialogBox.java @@ -0,0 +1,61 @@ +package duke.main; + +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; + +import java.io.IOException; + +/** + * An example of a custom control using FXML. + * This control represents a dialog box consisting of an ImageView to represent the speaker's face and a label + * containing text from the speaker. + */ +public class DialogBox extends HBox { + @FXML + private Label dialog; + @FXML + private ImageView displayPicture; + + + private DialogBox(String s, Image i) { + 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(s); + displayPicture.setImage(i); + } + + /** + * Flips the dialog box such that the ImageView is on the left and text on the right. + */ + private void flip() { + this.setAlignment(Pos.TOP_LEFT); + ObservableList tmp = FXCollections.observableArrayList(this.getChildren()); + FXCollections.reverse(tmp); + this.getChildren().setAll(tmp); + } + + public static DialogBox getUserDialog(String s, Image i) { + return new DialogBox(s, i); + } + + public static DialogBox getDukeDialog(String s, Image i) { + var db = new DialogBox(s, i); + db.flip(); + return db; + } +} \ No newline at end of file diff --git a/src/main/java/duke/main/Duke.java b/src/main/java/duke/main/Duke.java new file mode 100644 index 0000000000..1ea5031fa4 --- /dev/null +++ b/src/main/java/duke/main/Duke.java @@ -0,0 +1,111 @@ +package duke.main; + +import duke.command.TaskList; +import duke.exception.DukeException; +import duke.exception.EmptyTodoListException; +import duke.exception.InvalidCommandException; +import duke.parser.Parser; +import duke.storage.Storage; +import duke.task.Deadline; +import duke.task.Event; +import duke.task.Task; +import duke.task.Todo; +import duke.ui.Ui; +import java.time.LocalDate; +import java.util.ArrayList; + +public class Duke { + + private final Storage storage; + private TaskList tasks; + private final Ui ui; + + + public Duke(String filePath) { + ui = new Ui(); + storage = new Storage(filePath); + try { + tasks = new TaskList(storage.load()); + } catch (DukeException e) { + ui.showLoadingError(); + tasks = new TaskList(); + } + } + + public String getResponse(String input) { + Parser parser = new Parser(); + String response = parser.checkResponse(input); + String dukeResponse; + try { + switch (response) { + case "find": { + String keyword = parser.getKeyword(); + ArrayList matchingTasks = tasks.searchTasks(keyword); + dukeResponse = ui.printMatchingList(matchingTasks); + break; + } + case "list": { + dukeResponse = ui.printList(tasks); + break; + } + case "mark": { + int taskNumber = parser.getTaskNumber(); + assert taskNumber > 0; + dukeResponse = tasks.markAsDone(taskNumber); + break; + } + case "unmark": { + int taskNumber = parser.getTaskNumber(); + assert taskNumber > 0; + dukeResponse = tasks.markNotDone(taskNumber); + break; + } + case "priority": { + int taskNumber = parser.getTaskNumber(); + dukeResponse = tasks.markHighPriority(taskNumber); + break; + } + case "delete": { + int taskNumber = parser.getTaskNumber(); + assert (taskNumber > 0); + dukeResponse = ui.printDeleteMessage(tasks, taskNumber); + tasks.deleteTask(taskNumber); + break; + } + case "deadline": { + String task = parser.getDeadlineDescription(); + LocalDate d1 = parser.getDeadlineTime(); + tasks.addTask(new Deadline(task, d1)); + dukeResponse = ui.printAddMessage(tasks); + break; + } + case "event": { + String task = parser.getEventDescription(); + String d1 = parser.getEventTime(); + tasks.addTask(new Event(task, d1)); + dukeResponse = ui.printAddMessage(tasks); + break; + } + case "todo": { + String task = parser.getTodoDescription(); + tasks.addTask(new Todo(task)); + dukeResponse = ui.printAddMessage(tasks); + break; + } + case "bye": { + dukeResponse = ui.printGoodbyeMessage(); + System.exit(0); + break; + } + default: + throw new InvalidCommandException(); + } + } catch (InvalidCommandException | EmptyTodoListException e) { + dukeResponse = e.getMessage(); + } + storage.saveTasks(tasks); + return dukeResponse; + } + + +} diff --git a/src/main/java/duke/main/Launcher.java b/src/main/java/duke/main/Launcher.java new file mode 100644 index 0000000000..b955ab9690 --- /dev/null +++ b/src/main/java/duke/main/Launcher.java @@ -0,0 +1,12 @@ +package duke.main; + +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); + } +} \ No newline at end of file diff --git a/src/main/java/duke/main/Main.java b/src/main/java/duke/main/Main.java new file mode 100644 index 0000000000..25848939a4 --- /dev/null +++ b/src/main/java/duke/main/Main.java @@ -0,0 +1,33 @@ +package duke.main; + +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 final Duke duke = new Duke("data/tasks.txt"); + + @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.setTitle("Snoopy"); + stage.setScene(scene); + stage.setResizable(false); + fxmlLoader.getController().setDuke(duke); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/duke/main/MainWindow.java b/src/main/java/duke/main/MainWindow.java new file mode 100644 index 0000000000..b075a32d3a --- /dev/null +++ b/src/main/java/duke/main/MainWindow.java @@ -0,0 +1,50 @@ +package duke.main; + +import duke.ui.Ui; +import javafx.fxml.FXML; +import javafx.scene.layout.AnchorPane; +import javafx.scene.image.Image; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.layout.VBox; + +public class MainWindow extends AnchorPane { + @FXML + private ScrollPane scrollPane; + @FXML + private VBox dialogContainer; + @FXML + private TextField userInput; + + private Duke duke; + private Ui ui = new Ui(); + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/legend.png")); + private Image dukeImage = new Image(this.getClass().getResourceAsStream("/images/snoopy.png")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + dialogContainer.getChildren().add(DialogBox.getDukeDialog(ui.printWelcomeMessage(), dukeImage)); + } + + public void setDuke(Duke d) { + duke = 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 = duke.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDukeDialog(response, dukeImage) + ); + userInput.clear(); + } + +} \ No newline at end of file diff --git a/src/main/java/duke/parser/Parser.java b/src/main/java/duke/parser/Parser.java new file mode 100644 index 0000000000..318826cfa3 --- /dev/null +++ b/src/main/java/duke/parser/Parser.java @@ -0,0 +1,122 @@ +package duke.parser; + +import duke.exception.EmptyTodoListException; + +import java.time.LocalDate; + +/** + * Makes sense of user command. + */ +public class Parser { + private String[] words; + + /** + * Retrieves command word entered by user. + * @param input Message entered. + * @return Command word. + */ + public String checkResponse(String input) { + words = input.split(" "); + return words[0]; + } + + /** + * Obtains task number for operation to be performed. + * @return Task number. + */ + public int getTaskNumber() { + assert words.length > 1; + return Integer.parseInt(words[1]); + } + + public String getKeyword() { + assert words.length > 1; + return words[1]; + } + + /** + * Obtains description of deadline task. + * @return Description of deadline task. + */ + public String getDeadlineDescription() { + int a = 2; + assert words.length > 1; + StringBuilder task = new StringBuilder(words[1]); + while (!words[a].equals("/by")) { + task.append(" "); + task.append(words[a]); + a++; + } + return task.toString(); + } + + /** + * Obtains time of deadline task. + * @return Time of deadline task. + */ + public LocalDate getDeadlineTime() { + int a = 2; + assert words.length > 1; + while (!words[a].equals("/by")) { + a++; + } + a++; + StringBuilder deadline = new StringBuilder(words[a]); + for (int b = a + 1; b < words.length; b++) { + deadline.append(" "); + deadline.append(words[b]); + } + return LocalDate.parse(deadline); + } + + /** + * Obtains description of event task. + * @return Description of event task. + */ + public String getEventDescription() { + int a = 2; + assert words.length > 1; + StringBuilder task = new StringBuilder(words[1]); + while (!words[a].equals("/at")) { + task.append(" "); + task.append(words[a]); + a++; + } + return task.toString(); + } + + /** + * Obtains time of event task. + * @return Time of event task. + */ + public String getEventTime() { + int a = 2; + assert words.length > 1; + while (!words[a].equals("/at")) { + a++; + } + a++; + StringBuilder event = new StringBuilder(words[a]); + for (int b = a + 1; b < words.length; b++) { + event.append(" "); + event.append(words[b]); + } + return event.toString(); + } + + /** + * Obtains description of todo task. + * @return Description of todo task. + */ + public String getTodoDescription() throws EmptyTodoListException { + if (words.length <= 1) { + throw new EmptyTodoListException(); + } + StringBuilder task = new StringBuilder(words[1]); + for (int a = 2; a < words.length; a++) { + task.append(" "); + task.append(words[a]); + } + return task.toString(); + } +} diff --git a/src/main/java/duke/storage/Storage.java b/src/main/java/duke/storage/Storage.java new file mode 100644 index 0000000000..df0016683d --- /dev/null +++ b/src/main/java/duke/storage/Storage.java @@ -0,0 +1,107 @@ +package duke.storage; + +import duke.command.TaskList; +import duke.exception.DukeException; +import duke.task.Deadline; +import duke.task.Event; +import duke.task.Task; +import duke.task.Todo; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Scanner; + +/** + * Controls loading of and saving to text file. + */ +public class Storage { + + private String filePath; + + /** + * Constructs a storage instance. + * @param filePath Path of text file. + */ + public Storage(String filePath) { + this.filePath = filePath; + } + + /** + * Obtains list of tasks from saved text file. + * @return List of tasks. + * @throws DukeException DukeException. + */ + public ArrayList load() throws DukeException { + File file = new File(this.filePath); + ArrayList tasks = new ArrayList<>(); + try { + file.getParentFile().mkdirs(); + file.createNewFile(); + Scanner myReader = new Scanner(file); + while (myReader.hasNextLine()) { + String data = myReader.nextLine(); + String[] words = data.split("\\s*\\|\\s*"); + Task newTask; + if (words[0].equals("T")) { + newTask = new Todo(words[3]); + } else if (words[0].equals("E")) { + newTask = new Event(words[3], words[4]); + } else { + newTask = new Deadline(words[3], LocalDate.parse(words[4])); + } + if (words[1].equals("1")) { + newTask.setDone(); + } + if (words[2].equals("1")) { + newTask.setPriority(); + } + tasks.add(newTask); + } + myReader.close(); + } catch (IOException e) { + throw new DukeException(); + } + return tasks; + } + + /** + * Saves list of tasks to text file. + * @param taskList List of tasks. + */ + public void saveTasks(TaskList taskList) { + try { + FileWriter myWriter = new FileWriter(this.filePath); + StringBuilder output = new StringBuilder(); + ArrayList tasks = taskList.getTasks(); + for (Task task : tasks) { + int number = 0; + int priority = 0; + if (task.checkDone()) { + number = 1; + } + if (task.checkPriority()) { + priority = 1; + } + if (task instanceof Todo) { + output.append("T | ").append(number).append(" | ").append(priority). + append(" | ").append(task.getDescription()).append("\n"); + } else if (task instanceof Event) { + output.append("E | ").append(number).append(" | ").append(priority).append(" | ") + .append(task.getDescription()).append(" | ").append(((Event) task).getTiming()) + .append("\n"); + } else { + output.append("D | ").append(number).append(" | ").append(priority).append(" | ") + .append(task.getDescription()).append(" | ").append(((Deadline) task).getDeadline()). + append("\n"); + } + } + myWriter.write(output.toString()); + myWriter.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/duke/task/Deadline.java b/src/main/java/duke/task/Deadline.java new file mode 100644 index 0000000000..9a06ada322 --- /dev/null +++ b/src/main/java/duke/task/Deadline.java @@ -0,0 +1,35 @@ +package duke.task; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +/** + * Stores type of task with deadline. + */ +public class Deadline extends Task { + + protected LocalDate deadlineDate; + + /** + * Constructs a deadline instance. + * @param description Description of task. + * @param by Deadline of task. + */ + public Deadline(String description, LocalDate by) { + super(description); + this.deadlineDate = by; + } + + /** + * Obtains string representation of deadline task. + * @return String representation. + */ + @Override + public String toString() { + return "[D]" + super.toString() + " (by: " + deadlineDate.format(DateTimeFormatter.ofPattern("MMM d yyyy")) + ")"; + } + + public LocalDate getDeadline() { + return this.deadlineDate; + } +} \ No newline at end of file diff --git a/src/main/java/duke/task/Event.java b/src/main/java/duke/task/Event.java new file mode 100644 index 0000000000..2444d73d79 --- /dev/null +++ b/src/main/java/duke/task/Event.java @@ -0,0 +1,32 @@ +package duke.task; + +/** + * Represents an event task. + */ +public class Event extends Task { + + protected String at; + + /** + * Constructs an event instance. + * @param description Description of task. + * @param at Time range for task. + */ + public Event(String description, String at) { + super(description); + this.at = at; + } + + public String getTiming() { + return this.at; + } + + /** + * Returns string representation of event task. + * @return String representation. + */ + @Override + public String toString() { + return "[E]" + super.toString() + " (at: " + at + ")"; + } +} \ No newline at end of file diff --git a/src/main/java/duke/task/Task.java b/src/main/java/duke/task/Task.java new file mode 100644 index 0000000000..1f942d1c8d --- /dev/null +++ b/src/main/java/duke/task/Task.java @@ -0,0 +1,86 @@ +package duke.task; + +/** + * Encapsulates a task. + */ +public class Task { + protected String description; + protected boolean isDone; + protected boolean isHighPriority; + + /** + * Constructs an instance of a task. + * @param description Description of task. + */ + public Task(String description) { + this.description = description; + this.isDone = false; + this.isHighPriority = false; + } + + /** + * Obtains icon used in string representation. + * @return Icon for completed status. + */ + public String getStatusIcon() { + return (isDone ? "X" : " "); // mark done task with X + } + + public void setDone() { + this.isDone = true; + } + + public void setPriority() { + this.isHighPriority = true; + } + + public boolean checkDone() { + return isDone; + } + + public boolean checkPriority() { + return isHighPriority; + } + + public String getDescription() { + return this.description; + } + + /** + * Marks task as done and prints message. + * @return Output message. + */ + public String markAsDone() { + this.isDone = true; + String output = "Nice! I've marked this task as done:\n"; + output += this.toString(); + return output; + } + + /** + * Marks task as not done and prints message. + * @return Output message. + */ + public String markNotDone() { + this.isDone = false; + String output = "OK, I've marked this task as not done yet:\n"; + output += this.toString(); + return output; + } + + public String markAsPriority() { + this.isHighPriority = true; + String output = "OK, I've marked this task as high priority:\n"; + output += this.toString(); + return output; + } + + /** + * Returns string representation of task. + * @return String representation. + */ + @Override + public String toString() { + return "[" + this.getStatusIcon() + "] " + this.description; + } +} \ No newline at end of file diff --git a/src/main/java/duke/task/Todo.java b/src/main/java/duke/task/Todo.java new file mode 100644 index 0000000000..70830f6080 --- /dev/null +++ b/src/main/java/duke/task/Todo.java @@ -0,0 +1,24 @@ +package duke.task; + +/** + * Encapsulates a todo task. + */ +public class Todo extends Task { + + /** + * Constructs an instance of todo task. + * @param description Description of task. + */ + public Todo(String description) { + super(description); + } + + /** + * Returns string representation of todo task. + * @return String representation. + */ + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/java/duke/ui/Ui.java b/src/main/java/duke/ui/Ui.java new file mode 100644 index 0000000000..d5189f6e58 --- /dev/null +++ b/src/main/java/duke/ui/Ui.java @@ -0,0 +1,70 @@ +package duke.ui; + +import duke.command.TaskList; +import duke.task.Task; + +import java.util.ArrayList; + +/** + * Handles interactions with user through command line. + */ +public class Ui { + + static final String WELCOME_MESSAGE = "Hello! I'm Snoopy\nWhat can I do for you?"; + static final String GOODBYE_MESSAGE = "Bye. Hope to see you again soon!"; + static final String LOADING_ERROR = "There was an error loading tasks from the file"; + + public void showLoadingError() { + System.out.println(LOADING_ERROR); + } + + public String printWelcomeMessage() { + return WELCOME_MESSAGE; + } + + public String printList(TaskList taskList) { + ArrayList tasks = taskList.getTasks(); + int i = tasks.size(); + StringBuilder output = new StringBuilder("Here are the tasks in your list:\n"); + for (int a = 1; a <= i; a++) { + Task curr = tasks.get(a - 1); + String taskString = curr.toString(); + output.append(a).append(".").append(taskString); + if (curr.checkPriority()) { + output.append(" (HIGH PRIORITY)"); + } + output.append("\n"); + } + return output.toString(); + } + + public String printMatchingList(ArrayList tasks) { + int i = tasks.size(); + StringBuilder output = new StringBuilder("Here are the matching tasks in your list:\n"); + for (int a = 1; a <= i; a++) { + String taskString = tasks.get(a - 1).toString(); + output.append(a).append(".").append(taskString).append("\n"); + } + return output.toString(); + } + + public String printDeleteMessage(TaskList taskList, int taskNumber) { + String output = "Noted. I've removed this task:\n"; + output += taskList.retrieveTask(taskNumber) + "\n"; + int i = taskList.getListSize() - 1; + output += "Now you have " + i + " tasks in the list." + "\n"; + return output; + } + + public String printAddMessage(TaskList taskList) { + int listSize = taskList.getListSize(); + String output = "Got it. I've added this task:\n"; + output += taskList.retrieveTask(listSize) + "\n"; + output += "Now you have " + listSize + " tasks in the list.\n"; + return output; + } + + public String printGoodbyeMessage() { + return GOODBYE_MESSAGE; + } +} diff --git a/src/main/resources/images/legend.png b/src/main/resources/images/legend.png new file mode 100644 index 0000000000..54581199b1 Binary files /dev/null and b/src/main/resources/images/legend.png differ diff --git a/src/main/resources/images/snoopy.png b/src/main/resources/images/snoopy.png new file mode 100644 index 0000000000..7ea0eda0dd Binary files /dev/null and b/src/main/resources/images/snoopy.png differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..e91888ea3e --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,8 @@ + + + + + + + + \ 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..9323e6b51e --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,19 @@ + + + + + + + + + + + +