diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..0ad7ce2eb9 --- /dev/null +++ b/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: samantha.main.Samantha + diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..871b43ef58 --- /dev/null +++ b/build.gradle @@ -0,0 +1,56 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '7.1.2' +} + +repositories { + mavenCentral() +} + +dependencies { + 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' + + 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' +} + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +application { + mainClass.set("main.Launcher") +} + +shadowJar { + archiveBaseName = "samantha" + archiveClassifier = null +} + +run{ + standardInput = System.in +} diff --git a/data/samantha.txt b/data/samantha.txt new file mode 100644 index 0000000000..76a14dd000 --- /dev/null +++ b/data/samantha.txt @@ -0,0 +1,19 @@ +T | 1 | read book +T | 1 | write book +T | 1 | sleep +T | 0 | play +T | 0 | add task 7 +T | 1 | ass +T | 1 | play football +E | 1 | project meeting | 2pm | 4pm +E | 0 | project meeting | 2pm | 4pm +D | 0 | return love | 2033-10-15 +D | 0 | return book | 2025-09-15 +D | 0 | finish 2103T | 2025-02-21 +T | 0 | stay hungry +T | 0 | like +E | 0 | stay foolish | 7pm | 9pm +E | 0 | be foolish | 7pm | 9pm +D | 0 | ip | 2025-02-21 +D | 0 | iptasks | 2025-02-21 +D | 0 | return book | 2025-02-01 diff --git a/docs/README.md b/docs/README.md index 47b9f984f7..6924ec7ca8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,30 +1,145 @@ -# Duke User Guide +# Samantha User Guide -// Update the title above to match the actual product name +![UI Example](Ui.png) -// Product screenshot goes here -// Product intro goes here +**This is Samantha, a Java-based chatBot to manage your personal tasks.** -## Adding deadlines +## 1. Adding deadlines -// Describe the action and its outcome. +Add a deadline task by its description and due date. -// Give examples of usage +Example: `deadline ip /by 2025-02-21` -Example: `keyword (optional arguments)` +Expected output: +``` +____________________________________________________________ +Got it. I've added this task: + [D][ ] ip (by: Feb 21 2025) +Now you have 19 tasks in the list. +____________________________________________________________ +``` + +## 2. Adding todos + +Add a todo task by its description. + +Example: `todo stay hungry` + +``` +____________________________________________________________ +Got it. I've added this task: + [T][ ] stay hungry +Now you have 15 tasks in the list. +____________________________________________________________ +``` + +## 3. Adding events + +Add a event task by its description and time period. -// A description of the expected outcome goes here +Example: `event stay foolish /from 7pm /to 9pm` +Expected output: ``` -expected output +____________________________________________________________ +Got it. I've added this task: + [E][ ] stay foolish (from: 7pm to: 9pm) +Now you have 17 tasks in the list. +____________________________________________________________ ``` -## Feature ABC +## 4. Marking tasks as done + +Mark a task as done. + +Example: `mark 7` + +Expected output: +``` +____________________________________________________________ +Nice! I've marked this task as done: + [T][X] add task 7 +____________________________________________________________ +``` + +## 5. Marking tasks as undone + +Mark a task as done. + +Example: `unmark 10` + +Expected output: +``` +____________________________________________________________ +OK, I've marked this task as not done yet: + [E][ ] project meeting (from: 2pm to: 4pm) +____________________________________________________________ +``` + +## 6. Listing tasks + +List all the task so far. + +Example: `list` + +Expected output: +``` +____________________________________________________________ +Here are the tasks in your list: + 1. [T][X] play + 2. [D][ ] return book (by: Dec 12 2022) + 3. [T][ ] read book + 4. [T][X] write book + 5. [T][ ] sleep + 6. [T][ ] play + 7. [T][X] add task 7 + 8. [T][X] ass + 9. [T][X] play football + 10. [E][ ] project meeting (from: 2pm to: 4pm) + 11. [E][ ] project meeting (from: 2pm to: 4pm) + 12. [D][ ] return love (by: Oct 15 2033) + 13. [D][ ] return book (by: Sep 15 2025) + 14. [D][ ] finish 2103T (by: Feb 21 2025) +____________________________________________________________ +``` + +## 7. Deleting tasks + +Delete the task according to its index. + +Example: `delete 1` + +Expected output: +``` +____________________________________________________________ +OK. I've removed this task: + [T][X] play +Now you have 19 tasks in the list. +____________________________________________________________ +``` + +## 8. Finding tasks + +Find the task according to its information. + +Example: `find stay` + +Expected output: +``` +____________________________________________________________ +Here are the matching tasks in your list: + 1. [T][ ] stay hungry + 2. [E][ ] stay foolish (from: 7pm to: 9pm) +____________________________________________________________ +``` -// Feature details +## 9. Special feature +**1. Friendlier syntax for commands.** -## Feature XYZ +Examples: `l for list, m for mark, u for unmark, +d for delete, t for todo, de for deadline, +e for event, f for find` -// Feature details \ No newline at end of file +**2. Type 'bye' to exit.** diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..29beefb3f8 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/command/Parser.java b/src/main/java/command/Parser.java new file mode 100644 index 0000000000..52163cfe13 --- /dev/null +++ b/src/main/java/command/Parser.java @@ -0,0 +1,98 @@ +package command; + +import task.TaskList; +import task.Todo; +import task.Deadline; +import task.Event; +import task.Task; +import ui.Ui; +import exception.SamanthaException; +import exception.CommandException; + +/** + * The Parser class is responsible for parsing user commands + * and executing the corresponding actions on the TaskList. + */ +public class Parser { + /** + * Parses the user input command and executes the corresponding action. + * + * @param command The user input command as a String. + * @param tasks The TaskList that stores all tasks. + * @param ui The UI instance for displaying messages. + * @throws SamanthaException If the command is invalid. + */ + public static String parseCommand(String command, TaskList tasks, Ui ui) throws SamanthaException { + if (command.equals("list") || command.equals("l")) { + return ui.showMessage(tasks.listTasks()); + } else if (command.startsWith("mark ")) { + int taskIndex = Integer.parseInt(command.substring(5)) - 1; + assert taskIndex >= 0 && taskIndex < tasks.getSize() : "Invalid task index"; + tasks.markTask(taskIndex, true); + return ui.showMessage("Nice! I've marked this task as done:\n " + tasks.getTask(taskIndex)); + } else if (command.startsWith("m ")) { + int taskIndex = Integer.parseInt(command.substring(2)) - 1; + assert taskIndex >= 0 && taskIndex < tasks.getSize() : "Invalid task index"; + tasks.markTask(taskIndex, true); + return ui.showMessage("Nice! I've marked this task as done:\n " + tasks.getTask(taskIndex)); + } else if (command.startsWith("unmark ")) { + int taskIndex = Integer.parseInt(command.substring(7)) - 1; + assert taskIndex >= 0 && taskIndex < tasks.getSize() : "Invalid task index"; + tasks.markTask(taskIndex, false); + return ui.showMessage("OK, I've marked this task as not done yet:\n " + tasks.getTask(taskIndex)); + } else if (command.startsWith("u ")) { + int taskIndex = Integer.parseInt(command.substring(2)) - 1; + assert taskIndex >= 0 && taskIndex < tasks.getSize() : "Invalid task index"; + tasks.markTask(taskIndex, false); + return ui.showMessage("OK, I've marked this task as not done yet:\n " + tasks.getTask(taskIndex)); + } else if (command.startsWith("delete ")) { + int taskIndex = Integer.parseInt(command.substring(7)) - 1; + assert taskIndex >= 0 && taskIndex < tasks.getSize() : "Invalid task index"; + Task removedTask = tasks.removeTask(taskIndex); + return ui.showMessage("OK. I've removed this task:\n " + removedTask + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("d ")) { + int taskIndex = Integer.parseInt(command.substring(2)) - 1; + assert taskIndex >= 0 && taskIndex < tasks.getSize() : "Invalid task index"; + Task removedTask = tasks.removeTask(taskIndex); + return ui.showMessage("OK. I've removed this task:\n " + removedTask + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("todo ")) { + assert command.length() > 5 : "Todo command must have a description"; + tasks.addTask(new Todo(command.substring(5))); + return ui.showMessage("Got it. I've added this task:\n " + tasks.getLastTask() + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("t ")) { + assert command.length() > 2 : "Todo command must have a description"; + tasks.addTask(new Todo(command.substring(2))); + return ui.showMessage("Got it. I've added this task:\n " + tasks.getLastTask() + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("deadline ")) { + String[] parts = command.substring(9).split(" /by "); + assert parts.length == 2 : "Deadline command format incorrect"; + tasks.addTask(new Deadline(parts[0], parts[1])); + return ui.showMessage("Got it. I've added this task:\n " + tasks.getLastTask() + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("de ")) { + String[] parts = command.substring(3).split(" /by "); + assert parts.length == 2 : "Deadline command format incorrect"; + tasks.addTask(new Deadline(parts[0], parts[1])); + return ui.showMessage("Got it. I've added this task:\n " + tasks.getLastTask() + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("event ")) { + String[] parts = command.substring(6).split(" /from | /to "); + assert parts.length == 3 : "Event command format incorrect"; + tasks.addTask(new Event(parts[0], parts[1], parts[2])); + return ui.showMessage("Got it. I've added this task:\n " + tasks.getLastTask() + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("e ")) { + String[] parts = command.substring(2).split(" /from | /to "); + assert parts.length == 3 : "Event command format incorrect"; + tasks.addTask(new Event(parts[0], parts[1], parts[2])); + return ui.showMessage("Got it. I've added this task:\n " + tasks.getLastTask() + "\nNow you have " + tasks.getSize() + " tasks in the list."); + } else if (command.startsWith("find ")) { + String keyword = command.substring(5).trim(); + assert !keyword.isEmpty() : "Find command must have a keyword"; + return ui.showMessage(tasks.findTasks(keyword)); + } else if (command.startsWith("f ")) { + String keyword = command.substring(2).trim(); + assert !keyword.isEmpty() : "Find command must have a keyword"; + return ui.showMessage(tasks.findTasks(keyword)); + } else { + throw new CommandException("Your command beyond my ability."); + } + } +} \ No newline at end of file diff --git a/src/main/java/exception/CommandException.java b/src/main/java/exception/CommandException.java new file mode 100644 index 0000000000..2ad335bf1e --- /dev/null +++ b/src/main/java/exception/CommandException.java @@ -0,0 +1,16 @@ +package exception; + +/** + * Represents an exception specific to the Command. + */ +public class CommandException extends SamanthaException { + + /** + * Constructs a new CommandException with a specific message. + * + * @param message The error message. + */ + public CommandException(String message) { + super(message); + } +} diff --git a/src/main/java/exception/SamanthaException.java b/src/main/java/exception/SamanthaException.java new file mode 100644 index 0000000000..74e2063e0a --- /dev/null +++ b/src/main/java/exception/SamanthaException.java @@ -0,0 +1,16 @@ +package exception; + +/** + * Represents an exception specific to the Samantha task management system. + */ +public class SamanthaException extends Exception { + + /** + * Constructs a new SamanthaException with a specific message. + * + * @param message The error message. + */ + public SamanthaException(String message) { + super(message); + } +} diff --git a/src/main/java/main/DialogBox.java b/src/main/java/main/DialogBox.java new file mode 100644 index 0000000000..862c472ddd --- /dev/null +++ b/src/main/java/main/DialogBox.java @@ -0,0 +1,82 @@ +package main; + +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; + +/** + * 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; + + /** + * Creates a DialogBox with the given text and image. + * + * @param text The dialog text. + * @param img The image representing the speaker. + */ + private DialogBox(String text, Image img) { + try { + assert text != null : "Text cannot be null"; + assert img != null : "Image cannot be null"; + FXMLLoader fxmlLoader = new FXMLLoader(MainWindow.class.getResource("/view/DialogBox.fxml")); + fxmlLoader.setController(this); + fxmlLoader.setRoot(this); + fxmlLoader.load(); + } catch (IOException e) { + e.printStackTrace(); + } + + dialog.setText(text); + displayPicture.setImage(img); + } + + /** + * Flips the dialog box such that the ImageView is on the left and text on the right. + */ + private void flip() { + ObservableList tmp = FXCollections.observableArrayList(this.getChildren()); + Collections.reverse(tmp); + getChildren().setAll(tmp); + setAlignment(Pos.TOP_LEFT); + } + + /** + * Creates a dialog box for the user. + * + * @param text The user's input text. + * @param img The user's image. + * @return A DialogBox instance representing the user's dialog. + */ + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + /** + * Creates a dialog box for Samantha (AI response). + * + * @param text The AI's response text. + * @param img The AI's image. + * @return A DialogBox instance representing Samantha's response. + */ + public static DialogBox getSamanthaDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/main/Launcher.java b/src/main/java/main/Launcher.java new file mode 100644 index 0000000000..4a4db81b76 --- /dev/null +++ b/src/main/java/main/Launcher.java @@ -0,0 +1,13 @@ +package 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); + } +} + diff --git a/src/main/java/main/Main.java b/src/main/java/main/Main.java new file mode 100644 index 0000000000..f9cc3420d0 --- /dev/null +++ b/src/main/java/main/Main.java @@ -0,0 +1,38 @@ +package 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 Samantha using FXML. + */ +public class Main extends Application { + + private Samantha samantha = new Samantha("./data/samantha.txt"); + + /** + * Starts the JavaFX application. + * + * @param stage The primary stage for this application. + */ + @Override + public void start(Stage stage) { + assert stage != null : "Stage cannot be null"; + 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().setSamantha(samantha); + stage.setTitle("Samantha"); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/main/MainWindow.java b/src/main/java/main/MainWindow.java new file mode 100644 index 0000000000..5810e1ece8 --- /dev/null +++ b/src/main/java/main/MainWindow.java @@ -0,0 +1,77 @@ +package main; + +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; +import ui.Ui; + +/** + * Controller for the main GUI. + */ +public class MainWindow extends AnchorPane { + @FXML + private ScrollPane scrollPane; + @FXML + private VBox dialogContainer; + @FXML + private TextField userInput; + @FXML + private Button sendButton; + + private static final String EXIT_COMMAND = "bye"; + private static final String GREETING_MESSAGE = "Hi I'm Samantha!"; + private Samantha samantha; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/Phoneix.jpg")); + private Image samanthaImage = new Image(this.getClass().getResourceAsStream("/images/Samantha.jpg")); + + /** + * Initializes the GUI. + */ + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + /** + * Injects the samantha instance + */ + public void setSamantha(Samantha d) { + samantha = d; + greeting(); + } + + /** + * Displays the greeting message. + */ + private void greeting() { + String greetingMessage = GREETING_MESSAGE; + dialogContainer.getChildren().add( + DialogBox.getSamanthaDialog(greetingMessage, samanthaImage) + ); + } + + + /** + * Creates two dialog boxes, one echoing user input and the other containing Samantha'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 = samantha.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getSamanthaDialog(response, samanthaImage) + ); + userInput.clear(); + + if (input.equalsIgnoreCase(EXIT_COMMAND)) { + System.exit(0); + } + } +} diff --git a/src/main/java/main/Samantha.java b/src/main/java/main/Samantha.java new file mode 100644 index 0000000000..3dcc5f6f94 --- /dev/null +++ b/src/main/java/main/Samantha.java @@ -0,0 +1,100 @@ +package main; +import storage.Storage; +import task.TaskList; +import ui.Ui; +import command.Parser; +import exception.SamanthaException; + +import java.util.Scanner; +import java.util.ArrayList; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Main class for running the Samantha task management system. + */ +public class Samantha { + private static final String FILE_PATH = "./data/samantha.txt"; + private static final String EXIT_COMMAND = "bye"; + private Storage storage; + private TaskList tasks; + private Ui ui; + + /** + * Initializes the Samantha system. + * + * @param filePath The path of the file used for task storage. + */ + public Samantha(String filePath) { + ui = new Ui(); + storage = new Storage(); + try { + tasks = new TaskList(storage.loadTasks(filePath)); + } catch (Exception e) { + ui.showError("Error when loading tasks."); + tasks = new TaskList(new ArrayList<>()); + } + } + + /** + * Runs the main event loop for the Samantha system. + */ + public void run() { + ui.showWelcome(); + Scanner scanner = new Scanner(System.in); + + while (true) { + String userCommand = ui.readCommand(scanner).trim(); + if (EXIT_COMMAND.equalsIgnoreCase(userCommand)) { + break; + } + processCommand(userCommand); + } + + ui.showGoodbye(); + scanner.close(); + } + + /** + * Processes a single user command. + * + * @param userCommand The user input command. + */ + private void processCommand(String userCommand) { + try { + String response = Parser.parseCommand(userCommand, tasks, ui); + System.out.println(response); + storage.saveTasks(FILE_PATH, tasks.getTasks()); + } catch (SamanthaException e) { + ui.showError(e.getMessage()); + } + } + + + /** + * The entry point of the Samantha application. + * + * @param args Command-line arguments. + */ + public static void main(String[] args) { + try { + new Samantha(FILE_PATH).run(); + } catch (Exception e) { + throw new IllegalArgumentException("Something went wrong"); + } + } + + /** + * Generates a response for the user's chat message. + */ + public String getResponse(String input){ + try { + storage.saveTasks(FILE_PATH, tasks.getTasks()); + return Parser.parseCommand(input, tasks, ui); + } catch (SamanthaException e) { + return "[ERROR] " + e.getMessage(); + } + } +} + diff --git a/src/main/java/storage/Storage.java b/src/main/java/storage/Storage.java new file mode 100644 index 0000000000..52ed78dd0a --- /dev/null +++ b/src/main/java/storage/Storage.java @@ -0,0 +1,76 @@ +package storage; + +import task.Task; +import java.io.File; +import java.io.FileWriter; +import java.io.BufferedWriter; +import java.io.IOException; +import java.util.List; +import java.util.ArrayList; +import java.util.Scanner; + +/** + * Handles loading and saving tasks to a file. + */ +public class Storage { + + /** + * Saves the list of tasks to the specified file path. + * + * @param filePath The file path where tasks should be saved. + * @param tasks The list of tasks to save. + */ + public static void saveTasks(String filePath, List tasks) { + try { + File file = new File(filePath); + + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + for (Task task : tasks) { + writer.write(task.toSaveFormat()); + writer.newLine(); + } + writer.close(); + } catch (IOException e) { + System.out.println("Saving tasks error: " + e.getMessage()); + } + } + + /** + * Loads tasks from the specified file path. + * + * @param filePath The file path from which tasks should be loaded. + * @return A list of tasks loaded from the file. + */ + public static ArrayList loadTasks(String filePath) { + ArrayList tasks = new ArrayList<>(); + File file = new File(filePath); + if (!file.exists()) { + return tasks; + } + + try { + Scanner scanner = new Scanner(file); + + if (!scanner.hasNextLine()) { + scanner.close(); + return tasks; + } + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + if (line.isEmpty()) { + continue; + } + try { + tasks.add(Task.fromSaveFormat(line)); + } catch (Exception e) { + System.out.println("Task entry error" ); + } + } + scanner.close(); + } catch (IOException e) { + System.out.println("Loading tasks error: " + e.getMessage()); + } + return tasks; + } +} \ No newline at end of file diff --git a/src/main/java/task/Deadline.java b/src/main/java/task/Deadline.java new file mode 100644 index 0000000000..11b58c629e --- /dev/null +++ b/src/main/java/task/Deadline.java @@ -0,0 +1,54 @@ +package task; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +/** + * Represents a task with a deadline. + */ +public class Deadline extends Task { + + protected LocalDate by; + + /** + * Creates a Deadline task. + * + * @param description The description of the task. + * @param by The due date of the task. + */ + public Deadline(String description, String by) { + super(description); + try { + this.by = LocalDate.parse(by); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid date format. Please use yyyy-MM-dd."); + } + + } + + @Override + public String toSaveFormat() { + return "D | " + (isDone ? "1" : "0") + " | " + description + " | " + by; + } + + /** + * Creates a Deadline task from a saved file format. + * + * @param line The saved format string. + * @return A Deadline task. + */ + public static Deadline fromSaveFormat(String line) { + String[] parts = line.split(" \\| "); + boolean isDone = parts[1].equals("1"); + Deadline task = new Deadline(parts[2], parts[3]); + if (isDone) { + task.markAsDone(); + } + return task; + } + + @Override + public String toString() { + return "[D]" + super.toString() + " (by: " + by.format(DateTimeFormatter.ofPattern("MMM dd yyyy")) + ")"; + } +} diff --git a/src/main/java/task/Event.java b/src/main/java/task/Event.java new file mode 100644 index 0000000000..e0393b9982 --- /dev/null +++ b/src/main/java/task/Event.java @@ -0,0 +1,48 @@ +package task; + +/** + * Represents an event task with a start and end time. + */ +public class Event extends Task { + protected String from; + protected String to; + + /** + * Creates an Event task. + * + * @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, String from, String to) { + super(description); + this.from = from; + this.to = to; + } + + @Override + public String toSaveFormat() { + return "E | " + (isDone ? "1" : "0") + " | " + description + " | " + from + " | " + to; + } + + /** + * Creates an Event task from a saved file format. + * + * @param line The saved format string. + * @return An Event task. + */ + public static Event fromSaveFormat(String line) { + String[] parts = line.split(" \\| "); + boolean isDone = parts[1].equals("1"); // + Event task = new Event(parts[2], parts[3], parts[4]); + if (isDone) { + task.markAsDone(); + } + return task; + } + + @Override + public String toString() { + return "[E]" + super.toString() + " (from: " + from + " to: " + to + ")"; + } +} diff --git a/src/main/java/task/Task.java b/src/main/java/task/Task.java new file mode 100644 index 0000000000..8bb5d45f79 --- /dev/null +++ b/src/main/java/task/Task.java @@ -0,0 +1,86 @@ +package task; + +/** + * Represents a generic task. + */ +public class Task { + protected String description; + protected boolean isDone; + + /** + * Creates a new Task. + * + * @param description The description of the task. + */ + public Task(String description) { + this.description = description; + this.isDone = false; + } + + /** + * Returns the status icon of the task. + * "X" represents a completed task, while " " represents an incomplete task. + * + * @return A string representing the status icon. + */ + public String getStatusIcon() { + return (isDone ? "X" : " "); // mark done task with X + } + + /** + * Marks this task as done. + */ + public void markAsDone() { + this.isDone = true; + } + + /** + * Marks this task as undone. + */ + public void markAsUndone() { + this.isDone = false; + } + + /** + * Converts the task to a format suitable for saving to a file. + * + * @return A string representing the task in a savable format. + */ + public String toSaveFormat() { + return description; + } + + /** + * Creates a Task object from a string representation in save format. + * + * @param line A string representing a saved task. + * @return A Task object corresponding to the saved data. + * @throws IllegalArgumentException If the task type is invalid. + */ + public static Task fromSaveFormat(String line) { + String[] parts = line.split(" \\| "); + String type = parts[0]; + + switch (type) { + case "T": + return Todo.fromSaveFormat(line); + case "D": + return Deadline.fromSaveFormat(line); + case "E": + return Event.fromSaveFormat(line); + default: + throw new IllegalArgumentException("Invalid task type in file"); + } + + } + + /** + * Returns a string representation of the task. + * + * @return A string describing the task with its completion status. + */ + @Override + public String toString() { + return "[" + getStatusIcon() + "] " + description; + } +} \ No newline at end of file diff --git a/src/main/java/task/TaskList.java b/src/main/java/task/TaskList.java new file mode 100644 index 0000000000..72603c81ef --- /dev/null +++ b/src/main/java/task/TaskList.java @@ -0,0 +1,143 @@ +package task; + + +import task.Task; +import exception.SamanthaException; + +import java.util.Scanner; +import java.util.List; +import java.util.ArrayList; + +/** + * Represents a list of tasks that can be modified by the user. + */ +public class TaskList { + private final ArrayList tasks; + + /** + * Creates a TaskList with an initial set of tasks. + * + * @param tasks The list of tasks. + */ + public TaskList(ArrayList tasks) { + this.tasks = tasks; + } + + /** + * Adds a task to the list. + * + * @param task The task to be added. + */ + public void addTask(Task task) { + tasks.add(task); + } + + /** + * Removes a task from the list by its index. + * + * @param index The index of the task to be removed. + * @return The removed task. + * @throws SamanthaException If the index is out of bounds. + */ + public Task removeTask(int index) throws SamanthaException { + if (index < 0 || index >= tasks.size()) { + throw new SamanthaException("Invalid task number."); + } + return tasks.remove(index); + } + + /** + * Marks a task as done or undone. + * + * @param index The index of the task. + * @param isDone True to mark as done, false to mark as undone. + * @throws SamanthaException If the index is out of bounds. + */ + public void markTask(int index, boolean isDone) throws SamanthaException { + if (index < 0 || index >= tasks.size()) { + throw new SamanthaException("Invalid task number."); + } + if (isDone) { + tasks.get(index).markAsDone(); + } else { + tasks.get(index).markAsUndone(); + } + } + + /** + * Returns the list of tasks as a formatted string. + * + * @return A string representation of the tasks. + */ + public String listTasks() { + if (tasks.isEmpty()) { + return "List is empty."; + } + String[] taskArray = new String[tasks.size() + 1]; + taskArray[0] = "Here are the tasks in your list:"; + + for (int i = 0; i < tasks.size(); i++) { + taskArray[i + 1] = " " + (i + 1) + ". " + tasks.get(i); + } + + return String.join("\n", taskArray); + } + + /** + * Finds tasks that contain the specified keyword. + * + * @param keyword The keyword to search for. + * @return A string containing matching tasks. + */ + public String findTasks(String keyword) { + ArrayList matchingTasks = new ArrayList<>(); + matchingTasks.add("Here are the matching tasks in your list:"); + + int count = 0; + for (Task task : tasks) { + if (task.toString().contains(keyword)) { + count++; + matchingTasks.add(" " + count + ". " + task); + } + } + + return count == 0 ? "Fail to find matching tasks." : String.join("\n", matchingTasks); + } + + /** + * Retrieves a task by its index. + * + * @param index The index of the task. + * @return The corresponding task. + */ + public Task getTask(int index) { + return tasks.get(index); + } + + /** + * Retrieves the last task in the list. + * + * @return The last task added. + */ + public Task getLastTask() { + return tasks.get(tasks.size() - 1); + } + + /** + * Returns the number of tasks in the list. + * + * @return The size of the task list. + */ + public int getSize() { + return tasks.size(); + } + + /** + * Returns the full list of tasks. + * + * @return An ArrayList of tasks. + */ + public ArrayList getTasks() { + return tasks; + } +} \ No newline at end of file diff --git a/src/main/java/task/Todo.java b/src/main/java/task/Todo.java new file mode 100644 index 0000000000..4156675e1a --- /dev/null +++ b/src/main/java/task/Todo.java @@ -0,0 +1,40 @@ +package task; + +/** + * Represents a to-do task. + */ +public class Todo extends Task { + + /** + * Creates a Todo task. + * + * @param description The description of the task. + */ + public Todo(String description) { + super(description); + } + @Override + public String toSaveFormat() { + return "T | " + (isDone ? "1" : "0") + " | " + description; + } + + /** + * Creates a Todo task from a saved file format. + * + * @param line The saved format string. + * @return A Todo task. + */ + public static Todo fromSaveFormat(String line) { + String[] parts = line.split(" \\| "); + boolean isDone = parts[1].equals("1"); + Todo task = new Todo(parts[2]); + if (isDone) { + task.markAsDone(); + } + return task; + } + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/java/ui/Ui.java b/src/main/java/ui/Ui.java new file mode 100644 index 0000000000..9f492cf813 --- /dev/null +++ b/src/main/java/ui/Ui.java @@ -0,0 +1,40 @@ +package ui; +import java.util.Scanner; + +/** + * Handles user interactions. + */ +public class Ui { + /** Displays a welcome message. */ + public void showWelcome() { + System.out.println("____________________________________________________________"); + System.out.println(" Hello! I'm Samantha"); + System.out.println(" What can I do for you?"); + System.out.println("____________________________________________________________"); + } + + /** Displays a goodbye message. */ + public void showGoodbye() { + System.out.println("____________________________________________________________"); + System.out.println(" Bye. Hope to see you again soon!"); + System.out.println("____________________________________________________________"); + } + + /** Displays a given message. */ + public String showMessage(String message) { + String formattedMessage = "____________________________________________________________\n" + + message + "\n" + + "____________________________________________________________"; + return formattedMessage; + } + + /** Reads user input from the given scanner. */ + public String readCommand(Scanner scanner) { + return scanner.nextLine(); + } + + /** Displays an error message. */ + public void showError(String errorMessage) { + System.out.println("[ERROR] " + errorMessage); + } +} diff --git a/src/main/resources/images/Phoneix.jpg b/src/main/resources/images/Phoneix.jpg new file mode 100644 index 0000000000..44524f95d9 Binary files /dev/null and b/src/main/resources/images/Phoneix.jpg differ diff --git a/src/main/resources/images/Samantha.jpg b/src/main/resources/images/Samantha.jpg new file mode 100644 index 0000000000..058a1c798f Binary files /dev/null and b/src/main/resources/images/Samantha.jpg differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..fe672c90ea --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..255848bc5f --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,44 @@ + + + + + + + + + + + +