diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..b1e0ede129 --- /dev/null +++ b/build.gradle @@ -0,0 +1,61 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '7.1.2' + id 'checkstyle' +} + +checkstyle { + toolVersion = '10.2' +} + +repositories { + mavenCentral() +} + +dependencies { + String javaFxVersion = '17.0.7' + + 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' + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.10.0' + testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.10.0' +} + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +application { + mainClass.set("jarvis.Launcher") +} + +shadowJar { + archiveBaseName = "jarvis" + archiveClassifier = null + dependsOn("distZip", "distTar") +} + +run{ + standardInput = System.in +} \ No newline at end of file diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000000..eb761a9b9a --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000000..39efb6e4ac --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/data/jarvis.txt b/data/jarvis.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/data/tasks.txt b/data/tasks.txt new file mode 100644 index 0000000000..b9e1581358 --- /dev/null +++ b/data/tasks.txt @@ -0,0 +1,2 @@ +E | 0 | project meeting | Sep 2 2022 1200 | Sep 2 2022 1600 +D | 0 | return book | Sep 1 2023 1800 diff --git a/docs/README.md b/docs/README.md index 8077118ebe..7a24adf3f9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,29 +1,136 @@ +# Jarvis # User Guide -## Features -### Feature-ABC +## Feature List +Specific features will be explained in detail in the following section. -Description of the feature. +* Add a 'Todo' task +* Add a 'Deadline' task +* Add an 'Event' task +* List all tasks added +* Mark a task as done +* Mark a task as not done +* Delete a task from your list +* Find all tasks matching a keyword +* Find the closest 'Deadline' task that is not done yet +* Say goodbye to Jarvis -### Feature-XYZ +## Add a 'Todo' task +### `todo` - Adds a 'Todo' task with a task description to the task list +Format: `todo [DESCRIPTION]` -Description of the feature. +Example of usage: -## Usage +`todo study` -### `Keyword` - Describe action +Expected outcome: -Describe the action and its outcome. +Jarvis will add a new Todo task with description 'study' to the task list -Example of usage: +## Add a 'Deadline' task +### `deadline` - Adds a 'Deadline' task with a task description and a 'do-by date time' to the task list +Format: `deadline [DESCRIPTION] [/by DO_BY_DATE_TIME]` -`keyword (optional arguments)` +> The DO_BY_DATE_TIME must be in d/M/yyyy HHmm format + +Example of usage: + +`deadline return book /by 01/09/2023 1800` + +Expected outcome: + +Jarvis will add a new Deadline task with description 'return book' +and a do-by date time of '01/09/2023 1800' to the task list + +## Add an 'Event' task +### `event` - Adds a 'Event' task with a task description, start date time and end date time to the task list +Format: `event [DESCRIPTION] [from START_DATE_TIME] [/to END_TIME]` + +> The START_DATE_TIME and END_DATE_TIME must be in d/M/yyyy HHmm format + +Example of usage: + +'event project meeting /from 02/09/2022 1200 /to 02/09/2022 1600' + +Expected outcome: + +Jarvis will add a new Event task with description 'project meeting' +and a start date time of '02/09/2022 1200' +and a end date time of '02/09/2022 1600' to the task list + +## List all tasks added +### `list` - List all the tasks you have added to your list +Format: `list` + +Expected outcome: + +Jarvis will list all the tasks you have added + +## Mark a task as done +### `mark` - Marks a task on the list as done +Format: `mark [TASK_ID]` + +Example of usage: + +`mark 1` + +Expected outcome: + +Task 1 will be marked as done. + +## Mark a task as not done +### `unmark` - Marks a task on the list as not done +Format: `unmark [TASK_ID]` + +Example of usage: + +`unmark 2' + +Expected outcome: + +Task 2 will be marked as not done. + +## Delete a task from your list +### `delete` - Deletes a task from the list +Format: `delete [TASK_ID]` + +Example of usage: + +`delete 3` Expected outcome: -Description of the outcome. +Task 3 will be removed from the list + +## Find all tasks matching a keyword +### `find` - Searches the task list and returns all task that contains the words provided +Format: `find [WORD]` + +Example of usage: + +`find book` + +Expected outcome: + +Jarvis will display all tasks that contains 'book' in their description + +## Find the closest 'Deadline' task that is not done yet +### `reminder` - Displays a reminder of the closest 'Deadline' task that is not done yet +Format: `reminder` + +Example of usage: + +`reminder` + +Expected outcome: + +Displays a reminder of the closest 'Deadline' task that is not done yet + +## Say goodbye to Jarvis +### `bye` - Says goodbye to Jarvis and see him bid farewell to you back +Format: `bye` + +Expected outcome: -``` -expected output -``` +Jarvis will bid you farewell and not accept any user input thereafter. diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..c9ad413362 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..033e24c4cd 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..66c01cfeba --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000..fcb6fca147 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# 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"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000000..6689b85bee --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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% equ 0 goto execute + +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 execute + +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 + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +: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/jarvis/DialogBox.java b/src/main/java/jarvis/DialogBox.java new file mode 100644 index 0000000000..c8d59ee9ba --- /dev/null +++ b/src/main/java/jarvis/DialogBox.java @@ -0,0 +1,61 @@ +package jarvis; + +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; + +/** + * 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 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); + } + + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + public static DialogBox getJarvisDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/jarvis/Jarvis.java b/src/main/java/jarvis/Jarvis.java new file mode 100644 index 0000000000..f080e110e9 --- /dev/null +++ b/src/main/java/jarvis/Jarvis.java @@ -0,0 +1,63 @@ +package jarvis; + +import jarvis.command.Command; +import jarvis.exception.JarvisException; +import jarvis.parser.Parser; +import jarvis.storage.Storage; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents the main Jarvis application. + * Initializes the application and starts the interaction with the user. + */ +public class Jarvis { + + private Ui ui; + private Storage storage; + private Parser parser; + private TaskList tasks; + private boolean isExit; + + /** + * Constructs a Jarvis object. + * + * @param filePath The file path of the file to store the tasks. + */ + public Jarvis(String filePath) { + assert filePath != null && !filePath.isEmpty() : "File path should not be null or empty"; + + this.ui = new Ui(); + this.storage = new Storage(filePath); + tasks = new TaskList(storage.loadTasks()); + this.parser = new Parser(); + } + + /** + * You should have your own function to generate a response to user input. + * Replace this stub with your completed method. + */ + public String getResponse(String fullCommand) { + try { + Command c = parser.parse(fullCommand); + String response = c.execute(tasks, ui, storage); + this.isExit = c.isExit(); + return response; + } catch (JarvisException e) { + return e.getMessage(); + } + } + + /** + * Gets the greeting message to be displayed to the user. + * + * @return The greeting message to be displayed to the user. + */ + public String getGreeting() { + return ui.greet(); + } + + public boolean hasExited() { + return this.isExit; + } +} diff --git a/src/main/java/jarvis/Launcher.java b/src/main/java/jarvis/Launcher.java new file mode 100644 index 0000000000..2ac3bfcdae --- /dev/null +++ b/src/main/java/jarvis/Launcher.java @@ -0,0 +1,12 @@ +package jarvis; + +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/jarvis/Main.java b/src/main/java/jarvis/Main.java new file mode 100644 index 0000000000..656705b6e9 --- /dev/null +++ b/src/main/java/jarvis/Main.java @@ -0,0 +1,31 @@ +package jarvis; + +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 Jarvis jarvis = new Jarvis("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.setScene(scene); + fxmlLoader.getController().setJarvis(jarvis); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/jarvis/MainWindow.java b/src/main/java/jarvis/MainWindow.java new file mode 100644 index 0000000000..c80d49a7ec --- /dev/null +++ b/src/main/java/jarvis/MainWindow.java @@ -0,0 +1,65 @@ +package jarvis; + +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 Jarvis jarvis; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/Users.jpg")); + private Image jarvisImage = new Image(this.getClass().getResourceAsStream("/images/Jarvis.jpg")); + + /** + * Initializes the MainWindow. + */ + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + /** + * Sets the Jarvis object. + * + * @param d The Jarvis object. + */ + public void setJarvis(Jarvis d) { + jarvis = d; + dialogContainer.getChildren().addAll( + DialogBox.getJarvisDialog(jarvis.getGreeting(), jarvisImage) + ); + } + + /** + * Creates two dialog boxes, one echoing user input and the other containing Jarvis's reply and then appends them to + * the dialog container. Clears the user input after processing. + */ + @FXML + private void handleUserInput() { + if (!jarvis.hasExited()) { + String input = userInput.getText(); + String response = jarvis.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getJarvisDialog(response, jarvisImage) + ); + userInput.clear(); + } + } +} diff --git a/src/main/java/jarvis/command/AddCommand.java b/src/main/java/jarvis/command/AddCommand.java new file mode 100644 index 0000000000..5add55b129 --- /dev/null +++ b/src/main/java/jarvis/command/AddCommand.java @@ -0,0 +1,43 @@ +package jarvis.command; + +import jarvis.storage.Storage; +import jarvis.task.Task; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to add a task to the task list. + * Contains the task to be added. + */ +public class AddCommand extends Command { + private Task taskToAdd; + + /** + * Constructs an AddCommand object. + * + * @param task The task to be added. + */ + public AddCommand(Task task) { + assert task != null : "Task to add should not be null"; + this.taskToAdd = task; + } + + /** + * Executes the AddCommand. + * Adds the task to the task list, displays the added task, and saves the updated task list to storage. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the added task to the user. + * @param storage The Storage object, for saving the updated task list. + * @return + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) { + int initialSize = tasks.size(); + tasks.add(taskToAdd); + assert tasks.contains(taskToAdd) : "Added task should be in the task list"; + assert tasks.size() == initialSize + 1 : "Task list size should increase by 1 after adding a task"; + storage.saveTasks(tasks); + return ui.displayAddedTask(taskToAdd, tasks); + } +} diff --git a/src/main/java/jarvis/command/Command.java b/src/main/java/jarvis/command/Command.java new file mode 100644 index 0000000000..5165a13c58 --- /dev/null +++ b/src/main/java/jarvis/command/Command.java @@ -0,0 +1,34 @@ +package jarvis.command; + +import jarvis.exception.JarvisException; +import jarvis.storage.Storage; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents an abstract command that can be executed by Jarvis. + * This class serves as the base class for all specific commands + * that Jarvis can execute. + */ +public abstract class Command { + protected boolean isExit = false; + + /** + * Executes the specific implementation of this command. + * + * @param tasks The list of tasks currently managed by Jarvis. + * @param ui The Ui object to interact with the user. + * @param storage The Storage object to read or save tasks to disk. + * @throws JarvisException If there is any error during the command execution. + */ + public abstract String execute(TaskList tasks, Ui ui, Storage storage) throws JarvisException; + + /** + * Checks if this command should cause Jarvis to exit. + * + * @return true if Jarvis should exit, false otherwise. + */ + public boolean isExit() { + return isExit; + } +} diff --git a/src/main/java/jarvis/command/DeleteCommand.java b/src/main/java/jarvis/command/DeleteCommand.java new file mode 100644 index 0000000000..e83b7700ce --- /dev/null +++ b/src/main/java/jarvis/command/DeleteCommand.java @@ -0,0 +1,51 @@ +package jarvis.command; + +import jarvis.exception.JarvisException; +import jarvis.exception.JarvisInvalidIndexException; +import jarvis.storage.Storage; +import jarvis.task.Task; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to delete a task from the task list. + * Contains the index of the task to be deleted. + */ +public class DeleteCommand extends Command { + private int taskIndexToDelete; + + /** + * Constructs a DeleteCommand object. + * + * @param taskIndexToDelete The index of the task to be deleted. + */ + public DeleteCommand(int taskIndexToDelete) { + this.taskIndexToDelete = taskIndexToDelete; + } + + /** + * Executes the DeleteCommand. + * Deletes the task from the task list, displays the deleted task, and saves the updated task list to storage. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the deleted task to the user. + * @param storage The Storage object, for saving the updated task list. + * @throws JarvisInvalidIndexException If the task index is invalid. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws JarvisException { + if (taskIndexToDelete <= 0 || taskIndexToDelete > tasks.size()) { + throw new JarvisInvalidIndexException(taskIndexToDelete); + } + + int initialSize = tasks.size(); + + Task deletedTask = tasks.get(taskIndexToDelete - 1); // Lists are 0-indexed, but users see a 1-indexed list. + tasks.remove(taskIndexToDelete - 1); + storage.saveTasks(tasks); + + assert tasks.size() == initialSize - 1 : "Task list size should decrease by 1 after deletion"; + + return ui.displayDeletedTask(deletedTask, tasks); + } +} diff --git a/src/main/java/jarvis/command/ExitCommand.java b/src/main/java/jarvis/command/ExitCommand.java new file mode 100644 index 0000000000..1059b8e0f7 --- /dev/null +++ b/src/main/java/jarvis/command/ExitCommand.java @@ -0,0 +1,25 @@ +package jarvis.command; + +import jarvis.storage.Storage; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to exit the application. + */ +public class ExitCommand extends Command { + + /** + * Executes the ExitCommand. + * Displays the farewell message to the user. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the farewell message to the user. + * @param storage The Storage object, not used in this command. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) { + isExit = true; + return ui.farewell(); + } +} diff --git a/src/main/java/jarvis/command/FindCommand.java b/src/main/java/jarvis/command/FindCommand.java new file mode 100644 index 0000000000..00b6fc27d7 --- /dev/null +++ b/src/main/java/jarvis/command/FindCommand.java @@ -0,0 +1,40 @@ +package jarvis.command; + +import java.util.ArrayList; + +import jarvis.storage.Storage; +import jarvis.task.Task; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to find tasks that contain a keyword. + * Contains the keyword to search for. + */ +public class FindCommand extends Command { + + private String keyword; + + /** + * Constructor for FindCommand. + * + * @param keyword The keyword to search for. + */ + public FindCommand(String keyword) { + this.keyword = keyword; + } + + /** + * Executes the FindCommand. + * Finds all tasks that contain the keyword, and displays them to the user. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the matching tasks to the user. + * @param storage The Storage object, not used here. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) { + ArrayList matchingTasks = tasks.find(keyword); + return ui.displayMatchingTasks(matchingTasks); + } +} diff --git a/src/main/java/jarvis/command/ListCommand.java b/src/main/java/jarvis/command/ListCommand.java new file mode 100644 index 0000000000..9f4c562fc6 --- /dev/null +++ b/src/main/java/jarvis/command/ListCommand.java @@ -0,0 +1,30 @@ +package jarvis.command; + +import jarvis.exception.JarvisException; +import jarvis.storage.Storage; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to list all tasks in the task list. + */ +public class ListCommand extends Command { + + /** + * Executes the ListCommand. + * Displays the list of tasks to the user. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the list of tasks to the user. + * @param storage The Storage object, not used in this command. + * @throws JarvisException If there is any error during the command execution. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws JarvisException { + if (tasks.size() == 0) { + return ui.displayEmptyList(); + } else { + return ui.displayList(tasks); + } + } +} diff --git a/src/main/java/jarvis/command/MarkCommand.java b/src/main/java/jarvis/command/MarkCommand.java new file mode 100644 index 0000000000..8848548c2c --- /dev/null +++ b/src/main/java/jarvis/command/MarkCommand.java @@ -0,0 +1,50 @@ +package jarvis.command; + +import jarvis.exception.JarvisException; +import jarvis.exception.JarvisInvalidIndexException; +import jarvis.storage.Storage; +import jarvis.task.Task; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to mark a task in the task list as done. + * Contains the index of the task to be marked. + */ +public class MarkCommand extends Command { + private int taskIndexToMark; + + /** + * Constructs a MarkCommand object. + * + * @param taskIndexToMark The index of the task to be marked. + */ + public MarkCommand(int taskIndexToMark) { + this.taskIndexToMark = taskIndexToMark; + } + + /** + * Executes the MarkCommand. + * Marks the task as done, displays the marked task, and saves the updated task list to storage. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the marked task to the user. + * @param storage The Storage object, for saving the updated task list. + * @throws JarvisInvalidIndexException If the task index is invalid. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws JarvisException { + if (taskIndexToMark <= 0 || taskIndexToMark > tasks.size()) { + throw new JarvisInvalidIndexException(taskIndexToMark); + } + + Task taskToMark = tasks.get(taskIndexToMark - 1); + taskToMark.mark(); + + assert taskToMark.isDone() : "Task should be marked as done after executing the MarkCommand"; + + storage.saveTasks(tasks); + return ui.displayMarkedTask(taskToMark); + + } +} diff --git a/src/main/java/jarvis/command/UnmarkCommand.java b/src/main/java/jarvis/command/UnmarkCommand.java new file mode 100644 index 0000000000..d71fbbdab3 --- /dev/null +++ b/src/main/java/jarvis/command/UnmarkCommand.java @@ -0,0 +1,50 @@ +package jarvis.command; + +import jarvis.exception.JarvisException; +import jarvis.exception.JarvisInvalidIndexException; +import jarvis.storage.Storage; +import jarvis.task.Task; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to unmark a task in the task list as done. + * Contains the index of the task to be unmarked. + */ +public class UnmarkCommand extends Command { + private int taskIndexToUnmark; + + /** + * Constructs a UnmarkCommand object. + * + * @param taskIndexToUnmark The index of the task to be unmarked. + */ + public UnmarkCommand(int taskIndexToUnmark) { + this.taskIndexToUnmark = taskIndexToUnmark; + } + + /** + * Executes the UnmarkCommand. + * Unmarks the task as done, displays the unmarked task, and saves the updated task list to storage. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the unmarked task to the user. + * @param storage The Storage object, for saving the updated task list. + * @throws JarvisInvalidIndexException If the task index is invalid. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws JarvisException { + if (taskIndexToUnmark <= 0 || taskIndexToUnmark > tasks.size()) { + throw new JarvisInvalidIndexException(taskIndexToUnmark); + } + + Task taskToUnmark = tasks.get(taskIndexToUnmark - 1); + taskToUnmark.unmark(); + + assert !taskToUnmark.isDone() : "Task should be marked as undone after executing the UnmarkCommand"; + + storage.saveTasks(tasks); + return ui.displayUnmarkedTask(taskToUnmark); + + } +} diff --git a/src/main/java/jarvis/command/UpcomingCommand.java b/src/main/java/jarvis/command/UpcomingCommand.java new file mode 100644 index 0000000000..123b59b7e0 --- /dev/null +++ b/src/main/java/jarvis/command/UpcomingCommand.java @@ -0,0 +1,31 @@ +package jarvis.command; + +import java.time.LocalDateTime; + +import jarvis.exception.JarvisException; +import jarvis.storage.Storage; +import jarvis.task.Deadline; +import jarvis.tasklist.TaskList; +import jarvis.ui.Ui; + +/** + * Represents a command to display the nearest upcoming deadline that is not done yet. + */ +public class UpcomingCommand extends Command { + + /** + * Executes the UpcomingCommand. + * Displays the nearest upcoming deadline that is not done yet. + * + * @param tasks The list of tasks. + * @param ui The Ui object, for displaying the unmarked task to the user. + * @param storage The Storage object, for saving the updated task list. + * @throws JarvisException If there is any error during the command execution. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws JarvisException { + LocalDateTime now = LocalDateTime.now(); + Deadline upcomingDeadline = tasks.getUpcomingDeadline(now); + return ui.displayUpcomingDeadline(upcomingDeadline); + } +} diff --git a/src/main/java/jarvis/exception/JarvisException.java b/src/main/java/jarvis/exception/JarvisException.java new file mode 100644 index 0000000000..b11a00cffb --- /dev/null +++ b/src/main/java/jarvis/exception/JarvisException.java @@ -0,0 +1,16 @@ +package jarvis.exception; + +/** + * Represents an exception that is specific to Jarvis. + */ +public class JarvisException extends Exception { + + /** + * Creates a new JarvisException with the specified message. + * + * @param message The message to be displayed. + */ + public JarvisException(String message) { + super(message); + } +} diff --git a/src/main/java/jarvis/exception/JarvisInvalidIndexException.java b/src/main/java/jarvis/exception/JarvisInvalidIndexException.java new file mode 100644 index 0000000000..68a5afe2fa --- /dev/null +++ b/src/main/java/jarvis/exception/JarvisInvalidIndexException.java @@ -0,0 +1,16 @@ +package jarvis.exception; + +/** + * Represents an exception that occurs when the user provides an invalid index. + */ +public class JarvisInvalidIndexException extends JarvisException { + + /** + * Creates a new JarvisInvalidIndexException with the specified task index. + * + * @param taskIndex The task index that is invalid. + */ + public JarvisInvalidIndexException(int taskIndex) { + super("OOPS!!! No such task with index " + taskIndex); + } +} diff --git a/src/main/java/jarvis/exception/JarvisMissingValueException.java b/src/main/java/jarvis/exception/JarvisMissingValueException.java new file mode 100644 index 0000000000..a99eec2ded --- /dev/null +++ b/src/main/java/jarvis/exception/JarvisMissingValueException.java @@ -0,0 +1,21 @@ +package jarvis.exception; + +/** + * Represents an exception that occurs when the user does not provide a value for a command. + */ +public class JarvisMissingValueException extends JarvisException { + + /** + * Creates a new JarvisMissingValueException with the specified value and command. + * + * @param value The value that is missing. + * @param command The command that requires the value. + */ + public JarvisMissingValueException(String value, String command) { + super(String.format("OOPS!!! The %s of %s cannot be empty.", value, command)); + + // Assert that neither value nor command is null or empty + assert value != null && !value.trim().isEmpty() : "Value should not be null or empty"; + assert command != null && !command.trim().isEmpty() : "Command should not be null or empty"; + } +} diff --git a/src/main/java/jarvis/exception/JarvisUnrecognisedCommandException.java b/src/main/java/jarvis/exception/JarvisUnrecognisedCommandException.java new file mode 100644 index 0000000000..d0c5b88e09 --- /dev/null +++ b/src/main/java/jarvis/exception/JarvisUnrecognisedCommandException.java @@ -0,0 +1,14 @@ +package jarvis.exception; + +/** + * Represents an exception that occurs when the user provides an unrecognised command. + */ +public class JarvisUnrecognisedCommandException extends JarvisException { + + /** + * Creates a new JarvisUnrecognisedCommandException. + */ + public JarvisUnrecognisedCommandException() { + super("OOPS!!! I'm sorry, but I don't know what that means :-("); + } +} diff --git a/src/main/java/jarvis/exception/JarvisWrongDateFormatException.java b/src/main/java/jarvis/exception/JarvisWrongDateFormatException.java new file mode 100644 index 0000000000..4ac4a39667 --- /dev/null +++ b/src/main/java/jarvis/exception/JarvisWrongDateFormatException.java @@ -0,0 +1,14 @@ +package jarvis.exception; + +/** + * Represents an exception that occurs when the user provides an invalid date time format. + */ +public class JarvisWrongDateFormatException extends JarvisException { + + /** + * Creates a new JarvisWrongDateFormatException. + */ + public JarvisWrongDateFormatException() { + super("Please use the correct date time format: d/M/yyyy HHmm."); + } +} diff --git a/src/main/java/jarvis/parser/Parser.java b/src/main/java/jarvis/parser/Parser.java new file mode 100644 index 0000000000..0ca59002ae --- /dev/null +++ b/src/main/java/jarvis/parser/Parser.java @@ -0,0 +1,181 @@ +package jarvis.parser; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +import jarvis.command.AddCommand; +import jarvis.command.Command; +import jarvis.command.DeleteCommand; +import jarvis.command.ExitCommand; +import jarvis.command.FindCommand; +import jarvis.command.ListCommand; +import jarvis.command.MarkCommand; +import jarvis.command.UnmarkCommand; +import jarvis.command.UpcomingCommand; +import jarvis.exception.JarvisException; +import jarvis.exception.JarvisMissingValueException; +import jarvis.exception.JarvisUnrecognisedCommandException; +import jarvis.exception.JarvisWrongDateFormatException; +import jarvis.task.Deadline; +import jarvis.task.Event; +import jarvis.task.Todo; + +/** + * The Parser class is responsible for interpreting user inputs + * and converting them into executable Command objects for the Jarvis application. + * + *

It recognizes specific keywords in the user input (such as "todo", "deadline", + * "event", etc.) and creates the corresponding Command objects with the necessary + * information extracted from the input.

+ */ +public class Parser { + + + private static final DateTimeFormatter INPUT_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("d/M/yyyy HHmm"); + private static final String EXIT_COMMAND = "bye"; + private static final String LIST_COMMAND = "list"; + private static final String TODO_COMMAND = "todo"; + private static final String DEADLINE_COMMAND = "deadline"; + private static final String EVENT_COMMAND = "event"; + private static final String DELETE_COMMAND = "delete"; + private static final String MARK_COMMAND = "mark"; + private static final String UNMARK_COMMAND = "unmark"; + private static final String FIND_COMMAND = "find"; + private static final String UPCOMING_COMMAND = "upcoming"; + + /** + * Parses user input into a recognizable Command object. + * + * @param fullCommand The entire user input string. + * @return The Command object corresponding to the user input. + * @throws JarvisException If the user input is not recognized or has an incorrect format. + */ + public Command parse(String fullCommand) throws JarvisException { + String[] parts = fullCommand.split(" ", 2); + String commandType = parts[0]; + + switch (commandType) { + case EXIT_COMMAND: + return new ExitCommand(); + case LIST_COMMAND: + return new ListCommand(); + case UPCOMING_COMMAND: + return new UpcomingCommand(); + case TODO_COMMAND: + return parseTodo(parts); + case DEADLINE_COMMAND: + return parseDeadline(parts); + case EVENT_COMMAND: + return parseEvent(parts); + case DELETE_COMMAND: + return parseDelete(parts); + case MARK_COMMAND: + return parseMark(parts); + case UNMARK_COMMAND: + return parseUnmark(parts); + case FIND_COMMAND: + return parseFind(parts); + default: + throw new JarvisUnrecognisedCommandException(); + } + } + + private String[] ensureValidParts(String[] parts, String[] parameters, String[] delimiters) throws JarvisException { + assert parts != null : "Parts array should not be null"; + + if (parts.length < 2 || parts[1].isEmpty()) { + throw new JarvisMissingValueException(parameters[0], parts[0]); + } + + // Start by using the original parts[1] for extraction + String remainingPart = parts[1]; + String[] extractedParameters = new String[parameters.length]; + + // Iterate through each delimiter and extract the corresponding parameter + for (int i = 0; i < delimiters.length; i++) { + if (remainingPart.contains(delimiters[i])) { + String[] splitParts = remainingPart.split(delimiters[i], 2); + extractedParameters[i] = splitParts[0].trim(); + remainingPart = splitParts[1]; + } else { + throw new JarvisMissingValueException(parameters[i + 1], parts[0]); + } + } + + // The last parameter will be the remaining content after all splits + extractedParameters[parameters.length - 1] = remainingPart.trim(); + + return extractedParameters; + } + + private LocalDateTime parseDateTime(String dateTime) throws JarvisWrongDateFormatException { + try { + return LocalDateTime.parse(dateTime, INPUT_DATE_TIME_FORMATTER); + } catch (DateTimeParseException e) { + throw new JarvisWrongDateFormatException(); + } + } + + private Command parseTodo(String[] parts) throws JarvisException { + String[] taskParameters = new String[]{"description"}; + String[] delimiters = new String[]{}; // no delimiters + String[] parameterValues = ensureValidParts(parts, taskParameters, delimiters); + String description = parameterValues[0]; + return new AddCommand(new Todo(description)); + } + + private Command parseDeadline(String[] parts) throws JarvisException { + String[] taskParameters = new String[]{"description", "deadline time"}; + String[] delimiters = new String[]{" /by "}; + String[] parameterValues = ensureValidParts(parts, taskParameters, delimiters); + String description = parameterValues[0]; + LocalDateTime by = parseDateTime(parameterValues[1]); + return new AddCommand(new Deadline(description, by)); + } + + private Command parseEvent(String[] parts) throws JarvisException { + String[] taskParameters = new String[]{"description", "start time", "end time"}; + String[] delimiters = new String[]{" /from ", " /to "}; + String[] parameterValues = ensureValidParts(parts, taskParameters, delimiters); + String description = parameterValues[0]; + LocalDateTime from = parseDateTime(parameterValues[1]); + LocalDateTime to = parseDateTime(parameterValues[2]); + return new AddCommand(new Event(description, from, to)); + } + + private Command parseFind(String[] parts) throws JarvisException { + String[] taskParameters = new String[]{"keyword"}; + String[] delimiters = new String[]{}; // no delimiters + String[] parameterValues = ensureValidParts(parts, taskParameters, delimiters); + String keyword = parameterValues[0]; + return new FindCommand(keyword); + } + + private int parseIndex(String[] parts) throws JarvisException { + String[] taskParameters = new String[]{"task index"}; + String[] delimiters = new String[]{}; // no delimiters + String[] parameterValues = ensureValidParts(parts, taskParameters, delimiters); + String indexString = parameterValues[0]; + try { + return Integer.parseInt(indexString); + } catch (NumberFormatException e) { + throw new JarvisException("Please provide a valid task index."); + } + } + + private Command parseDelete(String[] parts) throws JarvisException { + int deleteIndex = parseIndex(parts); + return new DeleteCommand(deleteIndex); + } + + private Command parseMark(String[] parts) throws JarvisException { + int markIndex = parseIndex(parts); + return new MarkCommand(markIndex); + } + + private Command parseUnmark(String[] parts) throws JarvisException { + int unmarkIndex = parseIndex(parts); + return new UnmarkCommand(unmarkIndex); + } +} diff --git a/src/main/java/jarvis/storage/Storage.java b/src/main/java/jarvis/storage/Storage.java new file mode 100644 index 0000000000..bceb39792f --- /dev/null +++ b/src/main/java/jarvis/storage/Storage.java @@ -0,0 +1,119 @@ +package jarvis.storage; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +import jarvis.task.Deadline; +import jarvis.task.Event; +import jarvis.task.Task; +import jarvis.task.Todo; +import jarvis.tasklist.TaskList; + +/** + * The Storage class is responsible for saving and loading the task list to and from the hard disk. + */ +public class Storage { + private static final DateTimeFormatter SAVE_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("MMM d yyyy HHmm"); + private static final String TODO_IDENTIFIER = "T"; + private static final String DEADLINE_IDENTIFIER = "D"; + private static final String EVENT_IDENTIFIER = "E"; + private String filePath; + + /** + * Constructs a Storage object. + * + * @param filePath The path to the save file. + */ + public Storage(String filePath) { + this.filePath = filePath; + } + + /** + * Saves the task list to the save file. + * + * @param tasks The list of tasks to be saved. + */ + public void saveTasks(TaskList tasks) { + try { + FileWriter writer = new FileWriter(this.filePath); + + assert tasks != null : "Tasks list to be saved should not be null"; + + for (int i = 0; i < tasks.size(); i++) { + writer.write(tasks.get(i).toSaveString() + "\n"); + } + + writer.close(); + } catch (IOException e) { + System.out.println("An error occurred while saving tasks."); + e.printStackTrace(); + } + } + + /** + * Loads the task list from the save file. + * + * @return The list of tasks loaded from the save file. + */ + public ArrayList loadTasks() { + File file = new File(this.filePath); + + assert file != null : "File path to load tasks from cannot be null"; + + if (!file.exists()) { + System.out.println("No save file detected. Attempting to create one..."); + if (file.getParentFile() != null) { + file.getParentFile().mkdirs(); // This creates the directory structure if it doesn't exist + } + try { + file.createNewFile(); + } catch (IOException e) { + System.out.println("An error occurred while creating a new save file."); + e.printStackTrace(); + } + System.out.println("Save file created successfully at " + this.filePath); + } + + try { + List lines = Files.readAllLines(file.toPath()); + return getTasks(lines); + } catch (IOException e) { + System.out.println("An error occurred while loading tasks."); + return null; + } + } + + private LocalDateTime parseSavedDateTime(String dateTimeString) { + return LocalDateTime.parse(dateTimeString, SAVE_DATE_TIME_FORMATTER); + } + + private ArrayList getTasks(List lines) { + ArrayList tasks = new ArrayList<>(); + + for (String line : lines) { + String[] parts = line.split(" \\| "); + boolean isMarked = parts[1].equals("1"); + + switch (parts[0]) { + case TODO_IDENTIFIER: + tasks.add(new Todo(parts[2], isMarked)); + break; + case DEADLINE_IDENTIFIER: + tasks.add(new Deadline(parts[2], isMarked, parseSavedDateTime(parts[3]))); + break; + case EVENT_IDENTIFIER: + tasks.add(new Event(parts[2], isMarked, parseSavedDateTime(parts[3]), parseSavedDateTime(parts[4]))); + break; + default: + break; + } + } + return tasks; + } +} diff --git a/src/main/java/jarvis/task/Deadline.java b/src/main/java/jarvis/task/Deadline.java new file mode 100644 index 0000000000..07b3fb4a9c --- /dev/null +++ b/src/main/java/jarvis/task/Deadline.java @@ -0,0 +1,75 @@ +package jarvis.task; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Represents a deadline task. + * + * A Deadline is a task with an additional LocalDateTime attribute to indicate its deadline. + */ +public class Deadline extends Task { + + protected LocalDateTime by; + + /** + * Constructs a Deadline object with the specified description and deadline date-time. + * + * @param description The description of the deadline. + * @param by The deadline date-time of the task. + */ + public Deadline(String description, LocalDateTime by) { + super(description, false); + this.by = by; + } + + /** + * Constructs a Deadline object with the specified description, completion status, and deadline date-time. + * + * @param description The description of the deadline. + * @param isDone Indicates if the task has been completed. + * @param by The deadline date-time of the task. + */ + public Deadline(String description, Boolean isDone, LocalDateTime by) { + super(description, isDone); + this.by = by; + } + + /** + * Returns the deadline date-time. + * + * @return The deadline date-time of the task. + */ + public LocalDateTime getBy() { + return this.by; + } + + /** + * Returns the deadline date-time as a formatted string. + * + * @return A string representing the formatted deadline date-time. + */ + public String getByString() { + return this.by.format(DateTimeFormatter.ofPattern("MMM d yyyy HHmm")); + } + + /** + * Converts the Deadline object to a string format suitable for saving to a file. + * + * @return A string representation of the Deadline object for saving purposes. + */ + @Override + public String toSaveString() { + return "D | " + super.toSaveString() + " | " + getByString(); + } + + /** + * Returns a string representation of the Deadline object. + * + * @return A string representation of the Deadline object. + */ + @Override + public String toString() { + return "[D]" + super.toString() + " (by: " + getByString() + ")"; + } +} diff --git a/src/main/java/jarvis/task/Event.java b/src/main/java/jarvis/task/Event.java new file mode 100644 index 0000000000..04caaf0c68 --- /dev/null +++ b/src/main/java/jarvis/task/Event.java @@ -0,0 +1,98 @@ +package jarvis.task; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Represents an event task. + * + * An Event is a task with additional LocalDateTime attributes to indicate its start and end times. + */ +public class Event extends Task { + + protected LocalDateTime from; + protected LocalDateTime to; + + /** + * Constructs an Event object with the specified description, start time, and end time. + * + * @param description The description of the event. + * @param from The start time of the event. + * @param to The end time of the event. + */ + public Event(String description, LocalDateTime from, LocalDateTime to) { + super(description, false); + this.from = from; + this.to = to; + } + + /** + * Constructs an Event object with the specified description, completion status, start time, and end time. + * + * @param description The description of the event. + * @param isDone Indicates if the task has been completed. + * @param from The start time of the event. + * @param to The end time of the event. + */ + public Event(String description, Boolean isDone, LocalDateTime from, LocalDateTime to) { + super(description, isDone); + this.from = from; + this.to = to; + } + + /** + * Returns the start time of the event. + * + * @return The start time of the event. + */ + public LocalDateTime getFrom() { + return this.from; + } + + /** + * Returns the end time of the event. + * + * @return The end time of the event. + */ + public LocalDateTime getTo() { + return this.to; + } + + /** + * Returns the start time of the event as a formatted string. + * + * @return A string representing the formatted start time of the event. + */ + public String getFromString() { + return this.from.format(DateTimeFormatter.ofPattern("MMM d yyyy HHmm")); + } + + /** + * Returns the end time of the event as a formatted string. + * + * @return A string representing the formatted end time of the event. + */ + public String getToString() { + return this.to.format(DateTimeFormatter.ofPattern("MMM d yyyy HHmm")); + } + + /** + * Converts the Event object to a string format suitable for saving to a file. + * + * @return A string representation of the Event object for saving purposes. + */ + @Override + public String toSaveString() { + return "E | " + super.toSaveString() + " | " + getFromString() + " | " + getToString(); + } + + /** + * Returns a string representation of the Event object. + * + * @return A string representation of the Event object. + */ + @Override + public String toString() { + return "[E]" + super.toString() + " (from: " + getFromString() + " to: " + getToString() + ")"; + } +} diff --git a/src/main/java/jarvis/task/Task.java b/src/main/java/jarvis/task/Task.java new file mode 100644 index 0000000000..bd5bfeaa16 --- /dev/null +++ b/src/main/java/jarvis/task/Task.java @@ -0,0 +1,86 @@ +package jarvis.task; + +/** + * Represents a generic task. + * + * This class serves as a parent for more specific types of tasks such as + * {@code Todo}, {@code Deadline}, and {@code Event}. + */ +public class Task { + + protected String description; + protected boolean isDone; + + /** + * Constructs a Task object with the specified description and completion status. + * + * @param description The description or name of the task. + * @param isDone Indicates if the task has been completed. + */ + public Task(String description, Boolean isDone) { + this.description = description; + this.isDone = isDone; + } + + /** + * Returns the completion status of the task. + * + * @return true if the task is completed, false otherwise. + */ + public Boolean isDone() { + return this.isDone; + } + + /** + * Returns the description of the task. + * + * @return A string representing the description of the task. + */ + public String getDescription() { + return this.description; + } + + /** + * Returns the status icon of the task based on its completion status. + * A completed task is represented by "X", and an incomplete task is represented by a space. + * + * @return A string representing the status icon ("X" or " "). + */ + public String getStatusIcon() { + return (isDone ? "X" : " "); // mark done task with X + } + + /** + * Marks the task as done. + */ + public void mark() { + this.isDone = true; + } + + /** + * Marks the task as not done. + */ + public void unmark() { + this.isDone = false; + } + + /** + * Converts the Task object to a string format suitable for saving to a file. + * + * @return A string representation of the Task object for saving purposes. + */ + public String toSaveString() { + return (isDone ? "1" : "0") + " | " + this.description; + } + + /** + * Returns a string representation of the Task object. + * The representation includes the status icon and the description of the task. + * + * @return A string representation of the Task object. + */ + @Override + public String toString() { + return "[" + this.getStatusIcon() + "] " + this.description; + } +} diff --git a/src/main/java/jarvis/task/Todo.java b/src/main/java/jarvis/task/Todo.java new file mode 100644 index 0000000000..87400d8bc2 --- /dev/null +++ b/src/main/java/jarvis/task/Todo.java @@ -0,0 +1,52 @@ +package jarvis.task; + +/** + * Represents a Todo task. + * + * It is a type of task that only contains a description without any specific time or date associated with it. + */ +public class Todo extends Task { + + /** + * Constructs a Todo object with the specified description. + * The completion status of the task is set to false (i.e., not done) by default. + * + * @param description The description or name of the todo task. + */ + public Todo(String description) { + super(description, false); + } + + /** + * Constructs a Todo object with the specified description and completion status. + * + * @param description The description or name of the todo task. + * @param isDone Indicates if the task has been completed. + */ + public Todo(String description, Boolean isDone) { + super(description, isDone); + } + + /** + * Converts the Todo object to a string format suitable for saving to a file. + * The format includes an identifier for the task type ("T") followed by the save string of the parent Task class. + * + * @return A string representation of the Todo object for saving purposes. + */ + @Override + public String toSaveString() { + return "T | " + super.toSaveString(); + } + + /** + * Returns a string representation of the Todo object. + * The representation includes an identifier for the task type ("T") + * followed by the string representation of the parent Task class. + * + * @return A string representation of the Todo object. + */ + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/java/jarvis/tasklist/TaskList.java b/src/main/java/jarvis/tasklist/TaskList.java new file mode 100644 index 0000000000..cc7651cc16 --- /dev/null +++ b/src/main/java/jarvis/tasklist/TaskList.java @@ -0,0 +1,140 @@ +package jarvis.tasklist; + +import java.time.LocalDateTime; +import java.util.ArrayList; + +import jarvis.task.Deadline; +import jarvis.task.Task; + +/** + * Represents a list of tasks, providing utility methods for managing tasks. + * This class provides a convenient way to handle tasks, such as adding, removing, and retrieving tasks. + */ +public class TaskList { + + private ArrayList tasks; + + /** + * Initializes a new empty task list. + */ + public TaskList() { + this.tasks = new ArrayList<>(); + } + + /** + * Initializes a task list with a given list of tasks. + * + * @param loadedTasks An ArrayList of tasks to initialize the task list with. + */ + public TaskList(ArrayList loadedTasks) { + this.tasks = loadedTasks; + } + + /** + * Adds a task to the list. + * + * @param task The task to be added to the list. + */ + public void add(Task task) { + assert task != null : "Task to be added should not be null"; + + tasks.add(task); + } + + /** + * Removes a task from the list based on its index. + * + * @param index The index of the task to be removed. + * @return The task that was removed. + */ + public Task remove(int index) { + assert isValidIndex(index) : "Invalid task index for retrieval"; + + return tasks.remove(index); + } + + /** + * Retrieves a task from the list based on its index. + * + * @param index The index of the task to be retrieved. + * @return The task at the specified index. + */ + public Task get(int index) { + assert isValidIndex(index) : "Invalid task index for retrieval"; + + return tasks.get(index); + } + + /** + * Checks if the list contains the specified task. + * + * @param task The task to be checked. + * @return True if the task is in the list, false otherwise. + */ + public boolean contains(Task task) { + assert task != null : "Task to be checked should not be null"; + + return tasks.contains(task); + } + + /** + * Returns the number of tasks in the list. + * + * @return The size of the task list. + */ + public int size() { + return tasks.size(); + } + + /** + * Provides access to the entire list of tasks. + * + * @return An ArrayList containing all tasks in the TaskList. + */ + public ArrayList getTasks() { + return tasks; + } + + /** + * Returns a list of tasks that contain the specified keyword in their description. + * + * @param keyword The keyword to search for. + * @return A list of tasks that match the keyword. + */ + public ArrayList find(String keyword) { + ArrayList matchingTasks = new ArrayList<>(); + for (Task task : tasks) { + if (task.getDescription().contains(keyword)) { + matchingTasks.add(task); + } + } + return matchingTasks; + } + + /** + * Returns the nearest deadline that is not done yet + * + * @param now The time at which the command was given + * @return The nearest deadline that is not done yet + */ + public Deadline getUpcomingDeadline(LocalDateTime now) { + Deadline upcomingDeadline = null; + LocalDateTime upcomingDeadlineDateTime = null; + + for (Task task : tasks) { + if (!task.isDone() && task instanceof Deadline) { + Deadline deadline = (Deadline) task; + LocalDateTime deadlineDateTime = deadline.getBy(); + if (upcomingDeadline == null || deadlineDateTime.isBefore(upcomingDeadlineDateTime)) { + upcomingDeadline = deadline; + upcomingDeadlineDateTime = deadlineDateTime; + } + } + } + return upcomingDeadline; + } + + private boolean isValidIndex(int index) { + return index >= 0 && index < tasks.size(); + } +} diff --git a/src/main/java/jarvis/ui/Ui.java b/src/main/java/jarvis/ui/Ui.java new file mode 100644 index 0000000000..32cce13119 --- /dev/null +++ b/src/main/java/jarvis/ui/Ui.java @@ -0,0 +1,156 @@ +package jarvis.ui; + +import java.util.ArrayList; + +import jarvis.task.Deadline; +import jarvis.task.Task; +import jarvis.tasklist.TaskList; + + +/** + * Represents the user interface for interacting with the user. + * The class is responsible for displaying messages to the user and reading user input. + */ +public class Ui { + + /** + * Initializes the Ui class and prepares it to read user input. + */ + public Ui() { + } + + /** + * Displays the provided texts to the user surrounded by horizontal lines. + * + * @param text The messages to be displayed to the user. + */ + public String display(String... text) { + assert text != null : "Text to be displayed should not be null"; + + String response = ""; + for (String i : text) { + response += i + "\n"; + } + return response; + } + + /** + * Displays a greeting message to the user. + */ + public String greet() { + return display("Hello Master! I'm Jarvis, your AI personal assistant.", "What can I do for you?"); + } + + /** + * Displays a farewell message to the user. + */ + public String farewell() { + return display("Bye. Hope to see you again soon!"); + } + + /** + * Displays a message confirming that a task has been added. + * + * @param task The task that has been added. + * @param tasks The current task list. + */ + public String displayAddedTask(Task task, TaskList tasks) { + assert task != null : "Task to be displayed should not be null"; + assert tasks != null : "Task list should not be null"; + + return display("Got it. I've added this task:", task.toString(), + "Now you have " + tasks.size() + " tasks in the list."); + } + + /** + * Displays a message confirming that a task has been deleted. + * + * @param task The task that has been deleted. + * @param tasks The current task list. + */ + public String displayDeletedTask(Task task, TaskList tasks) { + assert task != null : "Task to be displayed should not be null"; + assert tasks != null : "Task list should not be null"; + + return display("Got it. I've removed this task:", task.toString(), + "Now you have " + tasks.size() + " tasks in the list."); + } + + /** + * Displays a message confirming that a task has been marked as done. + * + * @param task The task that has been marked. + */ + public String displayMarkedTask(Task task) { + assert task != null : "Task to be displayed should not be null"; + + return display("Nice! I've marked this task as done:", task.toString()); + } + + /** + * Displays a message confirming that a task has been unmarked. + * + * @param task The task that has been unmarked. + */ + public String displayUnmarkedTask(Task task) { + assert task != null : "Task to be displayed should not be null"; + + return display("OK, I've marked this task as not done yet:", task.toString()); + } + + /** + * Displays a message informing the user that their task list is currently empty. + */ + public String displayEmptyList() { + return display("You currently have no tasks in your list."); + } + + /** + * Displays all the tasks in the user's task list. + * + * @param tasks The user's current task list. + */ + public String displayList(TaskList tasks) { + assert tasks != null : "Task list should not be null"; + + String response = ""; + response += "Here are the tasks in your list:\n"; + for (int i = 0; i < tasks.size(); i++) { + response += (i + 1) + "." + tasks.get(i) + "\n"; + } + return response; + } + + /** + * Displays tasks that match a search query. + * + * @param tasks The list of tasks that match the search query. + */ + public String displayMatchingTasks(ArrayList tasks) { + assert tasks != null : "Task list should not be null"; + + if (tasks.isEmpty()) { + return display("No tasks matched your search query."); + } else { + String response = ""; + response += "Here are the matching tasks in your list:\n"; + for (int i = 0; i < tasks.size(); i++) { + response += (i + 1) + "." + tasks.get(i) + "\n"; + } + return response; + } + } + + /** + * Displays the nearest upcoming deadline that is not done yet. + * + * @param upcomingDeadline The nearest deadline that is not done yet. + */ + public String displayUpcomingDeadline(Deadline upcomingDeadline) { + if (upcomingDeadline == null) { + return display("There are no upcoming deadlines that are not done yet."); + } else { + return display("The nearest deadline that needs to be done is", upcomingDeadline.toString()); + } + } +} diff --git a/src/main/resources/images/Jarvis.jpg b/src/main/resources/images/Jarvis.jpg new file mode 100644 index 0000000000..6d0203d27f Binary files /dev/null and b/src/main/resources/images/Jarvis.jpg differ diff --git a/src/main/resources/images/Users.jpg b/src/main/resources/images/Users.jpg new file mode 100644 index 0000000000..08466ebf6d Binary files /dev/null and b/src/main/resources/images/Users.jpg differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..d3e6e9db86 --- /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..a86a02b144 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,19 @@ + + + + + + + + + + + +