diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 0000000000..ddcdab8e18 --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,51 @@ +name: Java CI + +on: [push, pull_request] + +jobs: + build: + strategy: + matrix: + platform: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.platform }} + + steps: + - name: Set up repository + uses: actions/checkout@master + + - name: Set up repository + uses: actions/checkout@master + with: + ref: master + + - name: Merge to master + run: git checkout --progress --force ${{ github.sha }} + + - name: Validate Gradle Wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup JDK 17 + uses: actions/setup-java@v1 + with: + java-version: '17' + java-package: jdk+fx + + - name: Build and check with Gradle + run: ./gradlew check + +# NO NEED FOR TEXT UI TESTING ANYMORE +# - name: Perform IO redirection test (*NIX) +# if: runner.os == 'Linux' +# working-directory: ${{ github.workspace }}/text-ui-test +# run: ./runtest.sh +# +# - name: Perform IO redirection test (MacOS) +# if: always() && runner.os == 'macOS' +# working-directory: ${{ github.workspace }}/text-ui-test +# run: ./runtest.sh +# +# - name: Perform IO redirection test (Windows) +# if: always() && runner.os == 'Windows' +# working-directory: ${{ github.workspace }}/text-ui-test +# shell: cmd +# run: runtest.bat \ No newline at end of file diff --git a/.gitignore b/.gitignore index 2873e189e1..8d164427f7 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,5 @@ bin/ /text-ui-test/ACTUAL.TXT text-ui-test/EXPECTED-UNIX.TXT +jar-test/Nether.jar-all.jar +jar-test/Instructions diff --git a/README.md b/README.md deleted file mode 100644 index 90aa7f092a..0000000000 --- a/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Duke project template - -This is a project template for a greenfield Java project. It's named after the Java mascot _Duke_. Given below are instructions on how to use it. - -## Setting up in Intellij - -Prerequisites: JDK 17, update Intellij to the most recent version. - -1. Open Intellij (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project first) -1. Open the project into Intellij as follows: - 1. Click `Open`. - 1. Select the project directory, and click `OK`. - 1. If there are any further prompts, accept the defaults. -1. Configure the project to use **JDK 17** (not other versions) as explained in [here](https://www.jetbrains.com/help/idea/sdk.html#set-up-jdk).
- In the same dialog, set the **Project language level** field to the `SDK default` option. -3. After that, locate the `src/main/java/Duke.java` file, right-click it, and choose `Run Duke.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: - ``` - Hello from - ____ _ - | _ \ _ _| | _____ - | | | | | | | |/ / _ \ - | |_| | |_| | < __/ - |____/ \__,_|_|\_\___| - ``` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..2982ecde10 --- /dev/null +++ b/build.gradle @@ -0,0 +1,81 @@ +plugins { + id 'checkstyle' + 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 'com.google.guava:guava:33.0-jre' + 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() + jvmArgs '-ea' + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +checkstyle { + toolVersion = '10.12.7' + configDirectory = file("$rootDir/config/checkstyle") +} + +configurations.checkstyle { + resolutionStrategy.capabilitiesResolution.withCapability("com.google.collections:google-collections") { + select("com.google.guava:guava:0") + } +} + +tasks.withType(Checkstyle).configureEach { + reports { + xml.required = true + html.required = true // Enable the HTML report + } +} + +application { + mainClass.set("Launcher") +} + +shadowJar { + archiveBaseName = "Nether.jar" +// archiveClassifier = null +} + +run{ + jvmArgs '-ea' + standardInput = System.in + jvmArgs = [ + '--module-path', classpath.asPath, + '--add-modules', 'javafx.controls,javafx.fxml' + ] +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000000..acac1a8e28 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000000..135ea49ee0 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/data/nether.txt b/data/nether.txt new file mode 100644 index 0000000000..b262d5194f --- /dev/null +++ b/data/nether.txt @@ -0,0 +1,4 @@ +T| |Chores|Buy groceries +D|X|School|Submit CS2103T assignment|2024-09-19 2359 +E| |School|Festival|2024-09-01 0700|2024-09-30 2300 +T| ||Read Book diff --git a/docs/README.md b/docs/README.md index 47b9f984f7..9eb317dab5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,30 +1,215 @@ -# Duke User Guide +

Nether User Guide

-// Update the title above to match the actual product name +___ -// Product screenshot goes here + -// Product intro goes here +**Welcome to Nether!** -## Adding deadlines +Meet your personal aide, Nether, a chatbot designed to make your life easier by keep track of all your tasks +systematically. Whether you're juggling deadlines, attending events, or simply trying to keep your daily tasks in order, +Nether is here to help. -// Describe the action and its outcome. +With Nether, you can organize your tasks through simple chat commands. Nether offers a streamlined, conversational +experience that feels natural and straightforward. -// Give examples of usage +## Table of Contents +- [Nether User Guide](#nether-user-guide) +- [Features](#features) + - [Add a ToDo Task: `todo`](#add-a-todo-task-todo) + - [Add a Deadline Task: `deadline`](#add-a-deadline-task-deadline) + - [Add an Event Task: `event`](#add-an-event-task-event) + - [Mark a Task: `mark`, `unmark`](#mark-a-task-mark-unmark) + - [List Out Tasks: `list`](#list-out-tasks-list) + - [Find a Task: `find`](#find-a-task-find) + - [Delete a Task: `delete`](#delete-a-task-delete) + - [Tagging: `#`](#tagging-) + - [Miscellaneous Commands: `nether`, `bye`](#miscellaneous-commands-nether-bye) +- [Known Issues](#known-issues) +- [Command Summary](#command-summary) +- [Acknowledgements](#acknowledgements) -Example: `keyword (optional arguments)` +

Features

-// A description of the expected outcome goes here +_____ +## Add a ToDo Task: `todo` +Adds a `todo` task to the task list. + +Format: `todo (description) [#tag]` + +> [!NOTE] +> `#tag` is an optional part of the command. Learn more about how to add tags to your tasks [here](#tagging-) + +Example input: +`todo Read Book` + +Expected output: +``` +Got it. I've added this task: + [T][ ] Read Book +``` + +## Add a Deadline Task: `deadline` + +Adds a `deadline` task to the task list. + +Format: `deadline (description) [#tag] /by (time)` + +> [!IMPORTANT] +> The only acceptable time format is `yyyy-MM-dd HHmm` +> e.g. `2024-09-19-2359` + +Example input: `deadline Submit CS2103T Assignment /by 2024-09-20 2359` + +Expected output: ``` -expected output +Got it. I've added this task: + [D][ ] Submit CS2103T Assignment (by: Sep 20 2024, 11:59pm) +``` + +## Add an Event Task: `event` + +Adds an `event` task to the task list. + +Format: `event (description) [#tag] /from (time) /to (time)` + +Example input: `event Festival /from 2024-09-01 0700 /to 2024-09-03 1900` + +Expected output: ``` +Got it. I've added this task: + [E][ ] Festival (from: Sep 1 2024, 7:00am to: Sep 03 2024, 7:00pm) +``` + +## Mark a Task: `mark`, `unmark` + +Mark your task as done or not done using `mark` and `unmark` respectively. + +### Mark a task as done: `mark` +Format: `mark (task number)` + +Example input: `mark 3` + +Expected output: +``` +Well done! I've marked this task as done: + [E][X] Festival (from: Sep 1 2024, 7:00am to: Sep 03 2024, 7:00pm) +``` + +### Mark a task as not done: `unmark` +Format `unmark (task number)` + +Example input: `unmark 3` + +Expected output: +``` +Understood, I've marked this task as not done: + [E][ ] Festival (from: Sep 1 2024, 7:00am to: Sep 03 2024, 7:00pm) +``` + +## List Out Tasks: `list` +List out all the tasks you have in your task list. + +Format: `list` + +Example input: `list` + +Expected output: +``` +Here are the tasks in your list: +1. [T][ ] Read Book +2. [D][ ] Submit CS2103T Assignment (by: Sep 20 2024, 11:59pm) +3. [E][ ] Festival (from: Sep 1 2024, 7:00am to: Sep 03 2024, 7:00pm) +``` + +## Find a Task: `find` +Find all tasks that contain the input search keyword (not case-sensitive). + +Format: `find (keyword)` + +Example input: `find book` + +Expected output: +``` +Here are the tasks that match your search in your list: +1. [T][ ] Read Book +``` + +## Delete a Task: `delete` +Delete a task from your task list. + +Format: `delete (task number)` + +Example input: `delete 1` + +Expected output: +``` +Noted, I've removed this task from the list: + [T][ ] Read Book +Now you have 2 tasks in the list. +``` + +## Tagging: `#` +Tag or find your tasks using `#`. + +> [!IMPORTANT] +> Tags may not contain any whitespace. + +### Add tasks with a tag + +Format: `(type) (description) [#tag] [time for deadline or event task]` + +Example input: `deadline Do Laundry #Chores /by 2024-09-20 0600` + +Expected output: +``` +Got it. I've added this task: + [D][ ] Do Laundry (by: Sep 20 2024, 6:00am) +``` + +### Find tasks with a tag + +List out all the tasks that contain the searched tag. + +Format: `find (tag)` + +Example input: `find #chores` + +Expected output: +``` +Here are the tasks that match your search in your list: +1. [D][ ] Do Laundry (by: Sep 20 2024, 6:00am) +``` + +## Miscellaneous Commands: `nether`, `bye` + +`nether` prompts nether to respond to you in a not so interesting way. + +`bye` stops nether from running and closes the application after a short delay. + +___ +

Known Issues

+___ + +NONE (as of now) -## Feature ABC -// Feature details +

Command Summary

+___ +- ToDo: `todo Read book` +- Deadline: `deadline Return book /by 2024-09-20 2359` +- Event: `event Book Festival /from 2024-09-01 0700 /to 2024-09-03 1200` +- Mark: `mark 1`, `unmark 2` +- List: `list` +- Find: `find book` +- Delete: `delete 3` +- Tagging: `todo Read Book #for-fun` +- Misc: `nether`, `bye` -## Feature XYZ +

Acknowledgements

-// Feature details \ No newline at end of file +1. Used ChatGPT to help generate roughly half of the JavaDoc comments. +2. Used ChatGPT to give recommendations on how to refactor the code to be more OOP, using the existing code as a base. +3. Followed majority of the code for GUI implementation from the JavaFX guide provided. \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..a8be0259e8 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/DialogBox.java b/src/main/java/DialogBox.java new file mode 100644 index 0000000000..ce696e65f0 --- /dev/null +++ b/src/main/java/DialogBox.java @@ -0,0 +1,79 @@ +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; +import javafx.scene.shape.Circle; + +/** + * 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(); + } + + Circle c = new Circle(40, 40, 40); + dialog.setText(text); + displayPicture.setClip(c); + displayPicture.setImage(img); + + // Determine if the message is an error message and apply the appropriate style + if (isErrorMessage(text)) { + dialog.getStyleClass().add("error-label"); + } else { + dialog.getStyleClass().add("label"); + } + } + + /** + * Determines if the given message should be treated as an error message. + * @param message The message to check. + * @return true if it's an error message, false otherwise. + */ + private boolean isErrorMessage(String message) { + // Define the logic to determine if a message is an error. This is just an example. + return message.toLowerCase().contains("sir,") || message.toLowerCase().contains("not in our database"); + } + + /** + * 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); + dialog.getStyleClass().add("reply-label"); + } + + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + public static DialogBox getDukeDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} 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/Launcher.java b/src/main/java/Launcher.java new file mode 100644 index 0000000000..43d64c26fb --- /dev/null +++ b/src/main/java/Launcher.java @@ -0,0 +1,10 @@ +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.java b/src/main/java/Main.java new file mode 100644 index 0000000000..f650c5fd92 --- /dev/null +++ b/src/main/java/Main.java @@ -0,0 +1,32 @@ +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; +import nether.Nether; + +/** + * A GUI for Duke using FXML. + */ +public class Main extends Application { + private final Nether nether = new Nether("./data/nether.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.setMinHeight(220); + stage.setMinWidth(417); + stage.setScene(scene); + fxmlLoader.getController().setNether(nether); // inject the Nether instance + stage.setTitle("Nether"); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/MainWindow.java b/src/main/java/MainWindow.java new file mode 100644 index 0000000000..fd06ab0293 --- /dev/null +++ b/src/main/java/MainWindow.java @@ -0,0 +1,62 @@ +import javafx.animation.PauseTransition; +import javafx.application.Platform; +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.image.Image; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.VBox; +import javafx.util.Duration; +import nether.Nether; + + +/** + * 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 Nether nether; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/UserIcon.png")); + private Image netherImage = new Image(this.getClass().getResourceAsStream("/images/Nether.jpeg")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + /** Injects the Duke instance */ + public void setNether(Nether nether) { + this.nether = nether; + } + + /** + * Creates two dialog boxes, one echoing user input and the other containing Duke's reply and then appends them to + * the dialog container. Clears the user input after processing. + */ + @FXML + private void handleUserInput() { + String input = userInput.getText(); + String response = nether.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDukeDialog(response, netherImage) + ); + userInput.clear(); + if (this.nether.isExit()) { + // Create a pause transition of 2.5 seconds + PauseTransition delay = new PauseTransition(Duration.seconds(2.5)); + delay.setOnFinished(event -> Platform.exit()); // Set action after delay + delay.play(); // Start the delay + } + } +} diff --git a/src/main/java/nether/Nether.java b/src/main/java/nether/Nether.java new file mode 100644 index 0000000000..bf0d73b7b4 --- /dev/null +++ b/src/main/java/nether/Nether.java @@ -0,0 +1,106 @@ +package nether; + +import javafx.scene.control.Alert; +import nether.command.Command; +import nether.parser.Parser; +import nether.storage.Storage; +import nether.task.TaskList; + +/** + * The main class of Nether - a task management chatbot that manages different types of tasks + * (e.g., to-do, deadline, event tasks). + * + * The class initializes the following essential components: + * - {@link Storage} for reading and writing tasks to a file. + * - {@link TaskList} for managing the list of tasks. + * - {@link Ui} for interacting with the user. + * - {@link Parser} for interpreting user input. + * + * The application runs in a loop, taking user input, processing commands, and + * executing the appropriate actions until an exit command is given. + */ + +public class Nether { + // the file path where task data is stored + private static boolean isExit = false; + private static final String STORAGE_FILE_PATH = "./data/nether.txt"; + private final Storage storage; + private final TaskList tasks; + private final Ui ui; + private final Parser parser; + + /** + * Constructs a new Nether instance. + * + * @param filePath The path to the file used for storing task data. + */ + + public Nether(String filePath) { + ui = new Ui(); + storage = new Storage(filePath); + parser = new Parser(); + tasks = new TaskList(storage.loadTasks()); + // can add a welcome msg next time HERE + } + + /** + * Runs the Nether application, producing a welcome message, and processing user commands in a loop. + * The loop continues until an exit command is issued by the user. + * It handles user input and executes the appropriate commands. + */ + public void run() { + while (!isExit) { + try { + String fullCommand = ui.readCommand(); + Command c = parser.parse(fullCommand); + c.execute(tasks, ui, storage); + isExit = c.isExit(); + } catch (AssertionError ae) { + // Handle assertion error, e.g., show a dialog box or update status message in GUI + System.out.println("reached"); + showAlert("Input Error", ae.getMessage()); + } catch (NetherException ne) { + // Handle other exceptions + System.out.println("reached"); + showAlert("Command Error", ne.getMessage()); + } + } + } + + private void showAlert(String title, String message) { + Alert alert = new Alert(Alert.AlertType.ERROR); + alert.setTitle(title); + alert.setHeaderText(null); + alert.setContentText(message); + alert.showAndWait(); + } + + /** + * Generates a response for the user's chat message. + */ + public String getResponse(String input) { + StringBuilder response = new StringBuilder(); + try { + Command c = parser.parse(input); + response.append(c.execute(tasks, ui, storage)); + isExit = c.isExit(); + return response.toString(); + } catch (NetherException e) { + return ui.printError(e.getMessage()); + } + } + + /** + * Initializes the application with the specified storage file path and starts it. + * + * @param args command-line arguments (not used) + */ + public static void main(String[] args) { + new Nether(STORAGE_FILE_PATH).run(); + } + + public boolean isExit() { + return isExit; + } + +} diff --git a/src/main/java/nether/NetherException.java b/src/main/java/nether/NetherException.java new file mode 100644 index 0000000000..6cf5744a09 --- /dev/null +++ b/src/main/java/nether/NetherException.java @@ -0,0 +1,15 @@ +package nether; + +/** + * Represents a custom exception for the Nether application. + * + * By using this custom exception, the application can provide more meaningful error + * messages to the user and handle exceptions. + * + */ + +public class NetherException extends RuntimeException { + public NetherException(String message) { + super(message); + } +} diff --git a/src/main/java/nether/Ui.java b/src/main/java/nether/Ui.java new file mode 100644 index 0000000000..46b5c0e353 --- /dev/null +++ b/src/main/java/nether/Ui.java @@ -0,0 +1,128 @@ +package nether; + +import java.util.Random; +import java.util.Scanner; + +import nether.task.Task; +import nether.task.TaskList; + + +/** + * Handles all interactions with the user, including displaying messages and reading user input. + * + * The {@code Ui} class mainly provides methods to print messages, read/parse commands from the user, + * and display information related to the application's operation. + */ + +public class Ui { + private final Scanner scanner; + + /** + * Constructs a new {@code Ui} object with a {@link Scanner} to read user input. + */ + public Ui() { + this.scanner = new Scanner(System.in); + } + + /** + * Reads the command input by the user, trimming the input off leading or trailing whitespaces + * + * @return Input string provided by the user without leading or trailing whitespaces + */ + public String readCommand() { + return scanner.nextLine().trim(); + } + + /** + * Prints the exit message to be shown when program is closed. + */ + public String printExitMessage() { + return "Bye. If you need any more help in the future, feel free to ask me. Enjoy your day!"; + } + + /** + * Prints a message for the user when an invalid or unregistered command is used. + * + * @param message message The error message explaining the issue. + */ + public String printError(String message) { + return "Sir, " + message; + } + + /** + * Prints a message indicating that a task has been successfully added to the task list. + * + * @param task The task that was added. + */ + public String printTaskAdded(Task task) { + StringBuilder response = new StringBuilder(); + response.append("Got it. I've added this task:\n"); + response.append(" ").append(task.toString()); + return response.toString(); + } + + /** + * Prints a message indicating that a task has been successfully deleted from the task list. + * + * @param task The task that was deleted. + * @param size The new size of the task list after deletion. + */ + @SuppressWarnings("checkstyle:SingleSpaceSeparator") + public String printTaskDeleted(Task task, int size) { + StringBuilder response = new StringBuilder(); + response.append("Noted, I've removed this task from the list:\n"); + response.append(" ").append(task.toString()).append("\n"); + response.append("Now you have ").append(size).append(" task").append(size > 1 ? "s" : "") + .append(" in the list."); + return response.toString(); + } + + /** + * Prints a message when a task is marked or unmarked, showing the task's new status. + * + * @param taskToMark The task that was marked or unmarked. + * @param markMessage The message describing the action (e.g., marked as done). + */ + public String printMarkMessage(Task taskToMark, String markMessage) { + StringBuilder response = new StringBuilder(); + response.append(markMessage).append("\n"); + response.append(" ").append(taskToMark.toString()); + return response.toString(); + } + + /** + * Returns a list of tasks that match the search criteria. + * If no matching tasks are found, it returns a message indicating that no matches were found. + * + * @param matchingTasks The TaskList containing tasks that match the search criteria. + * @return A string of all matching tasks or a message indicating no matches found. + */ + public String printMatchingTasks(TaskList matchingTasks) { + StringBuilder response = new StringBuilder(); + if (matchingTasks.getSize() == 0) { + return "No matching tasks found in your list."; + } + response.append("Here are the tasks that match your search in your list:\n"); + for (int i = 0; i < matchingTasks.getSize(); i++) { + response.append((i + 1)).append(".").append(matchingTasks.getTask(i).toString()).append("\n"); + } + return response.toString(); + } + + /** + * Returns a string that shows of the personality of Nether. + * It will randomly choose to return 1 out of 2 phrases. + * + * @return A string that shows Nether's personality. + */ + public String printSelf() { + Random random = new Random(); + int num = random.nextInt(100) + 1; // Random number between 1 and 100 + + if (num % 2 == 0) { + return "Hello there, is there anything I may help you with?"; + } else { + return "Yes sir? I am here, please enter your command."; + } + } +} diff --git a/src/main/java/nether/command/AddCommand.java b/src/main/java/nether/command/AddCommand.java new file mode 100644 index 0000000000..24728db509 --- /dev/null +++ b/src/main/java/nether/command/AddCommand.java @@ -0,0 +1,39 @@ +package nether.command; + +import nether.Ui; +import nether.storage.Storage; +import nether.task.Task; +import nether.task.TaskList; + +/** + * Represents a command to add a task to the task list. + * The {@code AddCommand} class is responsible for adding a specified task to the task list, + * printing a confirmation message, and saving the updated task list to storage. + */ +public class AddCommand extends Command { + private final Task task; + + /** + * Constructs an {@code AddCommand} with the specified task. + * + * @param task The task to be added to the task list. + */ + public AddCommand(Task task) { + this.task = task; + } + + /** + * Executes the add command by adding the task to the task list, printing a confirmation message, + * and saving the updated task list to storage. + * + * @param tasks The {@code TaskList} to which the task will be added. + * @param ui The {@code Ui} instance used to print the task addition message. + * @param storage The {@code Storage} instance used to save the updated task list. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) { + tasks.addTask(task); + storage.saveTasks(tasks.getTasks()); + return ui.printTaskAdded(task); + } +} diff --git a/src/main/java/nether/command/Command.java b/src/main/java/nether/command/Command.java new file mode 100644 index 0000000000..f8b799fd5a --- /dev/null +++ b/src/main/java/nether/command/Command.java @@ -0,0 +1,40 @@ +package nether.command; + +import nether.NetherException; +import nether.Ui; +import nether.storage.Storage; +import nether.task.TaskList; + +/** + * Represents an abstract command in the Nether application. + * + * The {@code Command} class provides a blueprint for all command types used in the application. + * It defines the basic structure and behavior for executing commands and handling termination. + * + */ +public abstract class Command { + /** + * Executes the command with the provided task list, user interface, and storage. + * + * This method must be implemented by subclasses to define the specific behavior of the command. + * + * @param tasks The {@code TaskList} to be modified or queried by the command. + * @param ui The {@code Ui} instance used to interact with the user. + * @param storage The {@code Storage} instance used to persist changes. + * @throws NetherException If an error occurs during command execution. + */ + public abstract String execute(TaskList tasks, Ui ui, Storage storage) throws NetherException; + + /** + * Determines if the command indicates the end of the application. + * + * The default implementation returns {@code false}, indicating that the command does not terminate the application. + * Subclasses may override this method to provide specific termination behavior. + * + * @return {@code true} if the command signals an exit; {@code false} otherwise. + */ + public boolean isExit() { + return false; + } + +} diff --git a/src/main/java/nether/command/DeleteCommand.java b/src/main/java/nether/command/DeleteCommand.java new file mode 100644 index 0000000000..60700376db --- /dev/null +++ b/src/main/java/nether/command/DeleteCommand.java @@ -0,0 +1,49 @@ +package nether.command; + +import nether.NetherException; +import nether.Ui; +import nether.storage.Storage; +import nether.task.Task; +import nether.task.TaskList; + +/** + * Represents a command to delete a task from the task list. + * The {@code DeleteCommand} class handles the deletion of a specified task from the task list based on the provided + * task index. + * + */ +public class DeleteCommand extends Command { + private final int taskIndex; + + /** + * Constructs a {@code DeleteCommand} with the specified task index. + * + * @param taskIndex The index of the task to be deleted (1-based index). + */ + public DeleteCommand(int taskIndex) { + this.taskIndex = taskIndex; + } + + /** + * Executes the delete command by removing the specified task from the task list. + * This method checks if the provided task index is valid, performs the deletion, updates the task list, + * notifies the user, and saves the updated task list to storage. + * + * @param tasks The {@code TaskList} to be modified by the command. + * @param ui The {@code Ui} instance used to interact with the user. + * @param storage The {@code Storage} instance used to persist changes. + * @throws NetherException If the task index is invalid (i.e., out of range or negative). + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws NetherException { + if (taskIndex > tasks.getSize() || taskIndex < 0) { + throw new NetherException("invalid task number!"); + } + + // taskIndex needs to be decremented since list index starts from 0 + Task removedTask = tasks.getTask(taskIndex - 1); + tasks.deleteTask(taskIndex - 1); + storage.saveTasks(tasks.getTasks()); + return ui.printTaskDeleted(removedTask, tasks.getSize()); + } +} diff --git a/src/main/java/nether/command/ExitCommand.java b/src/main/java/nether/command/ExitCommand.java new file mode 100644 index 0000000000..9ecf687eb3 --- /dev/null +++ b/src/main/java/nether/command/ExitCommand.java @@ -0,0 +1,40 @@ +package nether.command; + +import nether.Ui; +import nether.storage.Storage; +import nether.task.TaskList; + +/** + * Represents a command to exit the application. + *

+ * The {@code ExitCommand} class handles the termination of the application by printing an exit message + * and signaling that the application should close. + *

+ */ +public class ExitCommand extends Command { + /** + * Executes the exit command by displaying an exit message to the user. + *

+ * This method interacts with the user interface to print a goodbye message and does not modify the task list + * or storage. + *

+ * + * @param tasks The {@code TaskList} instance (unused in this command). + * @param ui The {@code Ui} instance used to interact with the user. + * @param storage The {@code Storage} instance (unused in this command). + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) { + return ui.printExitMessage(); + } + + /** + * Returns {@code true} to indicate that this command represents an exit command. + * + * @return {@code true} to indicate that the application should terminate. + */ + @Override + public boolean isExit() { + return true; + } +} diff --git a/src/main/java/nether/command/FindCommand.java b/src/main/java/nether/command/FindCommand.java new file mode 100644 index 0000000000..d8a741aaa3 --- /dev/null +++ b/src/main/java/nether/command/FindCommand.java @@ -0,0 +1,30 @@ +package nether.command; + +import nether.Ui; +import nether.storage.Storage; +import nether.task.TaskList; + +/** + * A command that searches for tasks in the task list that match the user's input string. + * The search is case-insensitive and returns a list of all tasks that contain the input string. + */ +public class FindCommand extends Command { + private final String searchString; + + public FindCommand(String searchString) { + this.searchString = searchString.toLowerCase(); + } + + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) { + TaskList searchResult; + if (searchString.startsWith("#")) { + searchResult = tasks.searchTag(searchString.substring(1).toLowerCase().trim()); + // search from 2nd character onwards + } else { + searchResult = tasks.searchTask(searchString); + } + return ui.printMatchingTasks(searchResult); + } + +} diff --git a/src/main/java/nether/command/ListCommand.java b/src/main/java/nether/command/ListCommand.java new file mode 100644 index 0000000000..804767ad83 --- /dev/null +++ b/src/main/java/nether/command/ListCommand.java @@ -0,0 +1,30 @@ +package nether.command; + +import nether.Ui; +import nether.storage.Storage; +import nether.task.TaskList; + +/** + * Represents a command to list all tasks in the task list. + *

+ * The {@code ListCommand} class extends {@code Command} and provides the implementation for + * displaying the list of tasks to the user. + *

+ */ +public class ListCommand extends Command { + /** + * Executes the command to list all tasks. + *

+ * This method calls the {@code printList} method of the {@code TaskList} class to display + * the current list of tasks to the user. + *

+ * + * @param tasks The {@code TaskList} object that contains all tasks. + * @param ui The {@code Ui} object used for printing the task list to the user. + * @param storage The {@code Storage} object (not used in this method). + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) { + return tasks.printList(); + } +} diff --git a/src/main/java/nether/command/MarkCommand.java b/src/main/java/nether/command/MarkCommand.java new file mode 100644 index 0000000000..6104f9fe11 --- /dev/null +++ b/src/main/java/nether/command/MarkCommand.java @@ -0,0 +1,73 @@ +package nether.command; + +import nether.NetherException; +import nether.Ui; +import nether.storage.Storage; +import nether.task.Task; +import nether.task.TaskList; + +/** + * Represents a command that marks a task as done or not done. + *

+ * The {@code MarkCommand} class is an abstract class that defines the common functionality for all commands. + *

+ */ +public abstract class MarkCommand extends Command { + protected int taskIndex; + + /** + * Constructs a {@code MarkCommand} with the specified task number. + * + * @param taskNumber The index of the task to be marked. + */ + public MarkCommand(int taskNumber) { + this.taskIndex = taskNumber; + } + + /** + * Executes the mark command by marking the specified task and updating the task list, user interface, + * and storage. + *

+ * This method validates the task number, retrieves the task, marks it accordingly, prints a message + * to the user, and saves the updated task list. + *

+ * + * @param tasks The {@code TaskList} instance containing the tasks. + * @param ui The {@code Ui} instance used to interact with the user. + * @param storage The {@code Storage} instance used to save the updated tasks. + * @throws NetherException If the task number is invalid. + */ + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws NetherException { + if (taskIndex > tasks.getSize() || taskIndex < 1) { + throw new NetherException("invalid task number!"); + } + + Task taskToMark = tasks.getTask(taskIndex - 1); + // taskNumber needs to be decremented since list index starts from 0 + markTask(taskToMark); + + storage.saveTasks(tasks.getTasks()); + return ui.printMarkMessage(taskToMark, getMarkMessage()); + } + + /** + * Marks the specified task as done or not done. + *

+ * This method must be implemented by subclasses to define specific marking behavior. + *

+ * + * @param taskToMark The task to be marked. + */ + public abstract void markTask(Task taskToMark); + + /** + * Returns the message to be displayed to the user after marking a task. + *

+ * This method must be implemented by subclasses to provide the appropriate marking message. + *

+ * + * @return The message indicating the result of the marking operation. + */ + public abstract String getMarkMessage(); +} diff --git a/src/main/java/nether/command/MarkDoneCommand.java b/src/main/java/nether/command/MarkDoneCommand.java new file mode 100644 index 0000000000..59049a0e3b --- /dev/null +++ b/src/main/java/nether/command/MarkDoneCommand.java @@ -0,0 +1,47 @@ +package nether.command; + +import nether.task.Task; + +/** + * Represents a command to mark a task as done. + *

+ * The {@code MarkDoneCommand} class extends {@code MarkCommand} and provides the specific implementation + * for marking a task as completed. + *

+ */ +public class MarkDoneCommand extends MarkCommand { + /** + * Constructs a {@code MarkDoneCommand} with the specified task number. + * + * @param taskNumber The index of the task to be marked as done. + */ + public MarkDoneCommand(int taskNumber) { + super(taskNumber); + } + + /** + * Marks the specified task as done. + *

+ * This method sets the status of the task to done by calling the {@code markAsDone} method on the task. + *

+ * + * @param taskToMark The task to be marked as done. + */ + @Override + public void markTask(Task taskToMark) { + taskToMark.markAsDone(); + } + + /** + * Returns the message to be displayed to the user after marking a task as done. + *

+ * This method provides a message indicating that the task has been successfully marked as done. + *

+ * + * @return The message "Well done! I've marked this task as done:". + */ + @Override + public String getMarkMessage() { + return "Well done! I've marked this task as done:"; + } +} diff --git a/src/main/java/nether/command/MarkNotDoneCommand.java b/src/main/java/nether/command/MarkNotDoneCommand.java new file mode 100644 index 0000000000..283d31d54b --- /dev/null +++ b/src/main/java/nether/command/MarkNotDoneCommand.java @@ -0,0 +1,48 @@ +package nether.command; + +import nether.task.Task; + +/** + * Represents a command to mark a task as not done. + *

+ * The {@code MarkNotDoneCommand} class is a subclass of {@code MarkCommand} and provides the implementation + * for marking a task as incomplete or not done. + *

+ */ +public class MarkNotDoneCommand extends MarkCommand { + + /** + * Constructs a {@code MarkNotDoneCommand} with the specified task number. + * + * @param taskNumber The index of the task to be marked as not done. + */ + public MarkNotDoneCommand(int taskNumber) { + super(taskNumber); + } + + /** + * Marks the specified task as not done. + *

+ * This method sets the status of the task to not done by calling the {@code markAsNotDone} method on the task. + *

+ * + * @param taskToMark The task to be marked as not done. + */ + @Override + public void markTask(Task taskToMark) { + taskToMark.markAsNotDone(); + } + + /** + * Returns the message to be displayed to the user after marking a task as not done. + *

+ * This method provides a message indicating that the task has been successfully marked as not done. + *

+ * + * @return The message "Understood, I've marked this task as not done:". + */ + @Override + public String getMarkMessage() { + return "Understood, I've marked this task as not done:"; + } +} diff --git a/src/main/java/nether/command/NetherCommand.java b/src/main/java/nether/command/NetherCommand.java new file mode 100644 index 0000000000..d3d82c2ffb --- /dev/null +++ b/src/main/java/nether/command/NetherCommand.java @@ -0,0 +1,18 @@ +package nether.command; + +import nether.NetherException; +import nether.Ui; +import nether.storage.Storage; +import nether.task.TaskList; + +/** + * Represents a command to let Nether express its personality to the users. + * The {@code NetherCommand} class returns a response String that lets the users know more about Nether's behaviour. + * + */ +public class NetherCommand extends Command { + @Override + public String execute(TaskList tasks, Ui ui, Storage storage) throws NetherException { + return ui.printSelf(); + } +} diff --git a/src/main/java/nether/parser/Parser.java b/src/main/java/nether/parser/Parser.java new file mode 100644 index 0000000000..cdc3d0fcb5 --- /dev/null +++ b/src/main/java/nether/parser/Parser.java @@ -0,0 +1,224 @@ +package nether.parser; + +import java.util.Objects; + +import nether.NetherException; +import nether.command.AddCommand; +import nether.command.Command; +import nether.command.DeleteCommand; +import nether.command.ExitCommand; +import nether.command.FindCommand; +import nether.command.ListCommand; +import nether.command.MarkDoneCommand; +import nether.command.MarkNotDoneCommand; +import nether.command.NetherCommand; +import nether.task.DeadlineTask; +import nether.task.EventTask; +import nether.task.TodoTask; + + +/** + * Handles the parsing of user input into commands and arguments that the program can understand. + * The Parser class provides methods to interpret different types of tasks and extract relevant details. + */ + +public class Parser { + /** + * Parses the user input to identify the {@code Command} and extracts details relevant to the {@code Command}. + * + * @param userInput The full input string provided by the user (without trailing or leading whitespaces). + * @return An array of strings containing the parts of the user input necessary to create tasks. + * @throws NetherException If the command is not recognized or the input format is incorrect. + */ + public Command parse(String userInput) throws NetherException { + assert !Objects.equals(userInput, "") : "Your input cannot be empty!"; + String[] processedInput; + String commandWord = extractCommandWord(userInput); + + switch (commandWord) { + case "list": + return new ListCommand(); + case "todo": + processedInput = extractInputDetails(userInput, "todo"); + return new AddCommand(new TodoTask(processedInput[0], processedInput[1])); + case "deadline": + processedInput = extractInputDetails(userInput, "deadline"); + return new AddCommand(new DeadlineTask(processedInput[0], processedInput[1], processedInput[2])); + case "event": + processedInput = extractInputDetails(userInput, "event"); + return new AddCommand(new EventTask(processedInput[0], processedInput[1], processedInput[2], + processedInput[3])); + case "mark": + return new MarkDoneCommand(extractTaskNumber(userInput)); + case "unmark": + return new MarkNotDoneCommand(extractTaskNumber(userInput)); + case "delete": + return new DeleteCommand(extractTaskNumber(userInput)); + case "find": + processedInput = extractInputDetails(userInput, "find"); + return new FindCommand(processedInput[0]); + case "nether": + return new NetherCommand(); + case "bye": + return new ExitCommand(); + default: + throw new NetherException("the command: '" + userInput + "' is not in our database."); + } + + } + + /** + * Extracts the {@code Command} from the user's input string. The command is assumed to be the + * first word of the input. + * + * @param userInput The full input string provided by the user. + * @return The command in lowercase (e.g., "todo", "deadline", or "event"). + */ + public String extractCommandWord(String userInput) { + return userInput.split(" ", 2)[0].toLowerCase(); + } + + /** + * Processes the user input into parts, making it easier to instantiate the respective {@code Task} objects. + * Splits the input based on the command and uses regex to identify {@code Task} details. + * + * @param userInput The full input string provided by the user (without leading or trailing whitespaces). + * @param taskType The type of task ("todo", "deadline", or "event"). + * @return A string array containing the task details to be instantiated by Nether class. + * @throws NetherException If the input does not follow the expected format or required details are missing. + */ + + public String[] extractInputDetails(String userInput, String taskType) throws NetherException { + switch (taskType) { + case "todo": + return handleTodoDetails(userInput); + case "deadline": + return handleDeadlineDetails(userInput); + case "event": + return handleEventDetails(userInput); + case "find": + return handleFindDetails(userInput); + default: + throw new NetherException("the command: '" + userInput + "' is not in our database"); + } + } + + /** + * Parses the user input for "todo" commands. + * + * @param userInput The full input string provided by the user. + * @return An array containing the details of the todo task. + * @throws NetherException If the todo task's description is empty. + */ + private static String[] handleTodoDetails(String userInput) { + String[] todoDetails = userInput.split("(?i)todo ", 2); + if (todoDetails.length < 2 || todoDetails[1].trim().isEmpty()) { + throw new NetherException("the description of a todo cannot be empty."); + } + String[] splitByTag = todoDetails[1].split("#", 2); + String description = splitByTag[0].trim(); + String tag = splitByTag.length > 1 ? splitByTag[1].trim() : ""; + return new String[]{description, tag}; + } + + /** + * Parses the user input for "deadline" commands. + * + * @param userInput The full input string provided by the user. + * @return An array containing the description and due date of the deadline task. + * @throws NetherException If either the description or the due date is empty. + */ + private static String[] handleDeadlineDetails(String userInput) { + String[] deadlineDetails = userInput.split("(?i)deadline ", 2); + if (deadlineDetails.length < 2 || deadlineDetails[1].trim().isEmpty()) { + throw new NetherException("the description of a deadline cannot be empty."); + } + String[] splitByTag = deadlineDetails[1].split("#", 2); + String description = ""; + String tag = ""; + String time = ""; + if (splitByTag.length > 1) { + String[] splitByTime = splitByTag[1].split("/by ", 2); + description = splitByTag[0].trim(); + tag = splitByTime[0].trim(); + time = splitByTime[1].trim(); + } else { // goes into this branch if the command does not have a tag + String[] splitByTime = deadlineDetails[1].split("/by ", 2); + if (splitByTime.length < 2 || splitByTime[0].trim().isEmpty() || splitByTime[1].trim().isEmpty()) { + throw new NetherException("the description or date/time of a deadline cannot be empty."); + } + description = splitByTime[0].trim(); + time = splitByTime[1].trim(); + } + return new String[]{description, tag, time}; + } + + /** + * Parses the user input for "event" commands. + * + * @param userInput The full input string provided by the user. + * @return An array containing the description, start time, and end time of event. + * @throws NetherException If the description, start time, or end time is empty. + */ + private static String[] handleEventDetails(String userInput) { + String[] eventDetails = userInput.split("(?i)event ", 2); + if (eventDetails.length < 2 || eventDetails[1].trim().isEmpty()) { + throw new NetherException("the description of an event cannot be empty."); + } + String description = ""; + String tag = ""; + String timeStart = ""; + String timeEnd = ""; + String[] splitByTag = eventDetails[1].split("#", 2); + if (splitByTag.length > 1) { + String[] splitByTime = splitByTag[1].split("/from |/to ", 3); + description = splitByTag[0].trim(); + tag = splitByTime[0].trim(); + timeStart = splitByTime[1].trim(); + timeEnd = splitByTime[2].trim(); + } else { + String[] splitByTime = eventDetails[1].split("/from |/to ", 3); + if (splitByTime.length < 3 || splitByTime[0].trim().isEmpty() || splitByTime[1].trim().isEmpty() + || splitByTime[2].trim().isEmpty()) { + throw new NetherException( + "the description, start time, or end time of an event cannot be empty."); + } + description = splitByTime[0].trim(); + timeStart = splitByTime[1].trim(); + timeEnd = splitByTime[2].trim(); + } + return new String[]{description, tag, timeStart, timeEnd}; + } + + /** + * Parses the user input for "find" commands. + * + * @param userInput The full input string provided by the user. + * @return An array containing the search keyword + * @throws NetherException If the keyword for searching is empty. + */ + private static String[] handleFindDetails(String userInput) { + String[] findDetails = userInput.split("(?i)find", 2); + if (findDetails.length < 2 || findDetails[1].trim().isEmpty()) { + throw new NetherException("please enter a keyword for me to search."); + } + return new String[]{findDetails[1].trim()}; + } + + /** + * Returns the index/number of the {@code Task} stated in the user input. + * Useful for commands like {@code mark} or {@code unmark}. + * + * @param userInput The input string provided by the user. + * @return The task number (index + 1) to be marked/unmarked if successfully parsed; -1 otherwise. + */ + + public int extractTaskNumber(String userInput) { + try { + String[] parts = userInput.split(" "); + return Integer.parseInt(parts[1]); + } catch (Exception e) { + return -1; + } + } +} diff --git a/src/main/java/nether/storage/Storage.java b/src/main/java/nether/storage/Storage.java new file mode 100644 index 0000000000..3fc1dcdf93 --- /dev/null +++ b/src/main/java/nether/storage/Storage.java @@ -0,0 +1,113 @@ +package nether.storage; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +import nether.NetherException; +import nether.task.DeadlineTask; +import nether.task.EventTask; +import nether.task.Task; +import nether.task.TodoTask; + + +/** + * Handles the storage of tasks to and from a file. + * The {@code Storage} class provides functionality to save tasks to a file and load tasks from a file. + */ +public class Storage { + private final String filePath; + + /** + * Constructs a {@code Storage} object with the specified file path. + * + * @param filePath The path to the file where tasks will be saved or loaded from. + */ + public Storage(String filePath) { + this.filePath = filePath; + } + + /** + * Saves the specified list of tasks to the data file. + * Each task is saved in a format defined by {@code Task.toSaveFormat()}. + * + * @param tasks The list of tasks to be saved in the data file. + */ + public void saveTasks(List tasks) { + File file = new File(filePath); + file.getParentFile().mkdirs(); // create the parent directory just in case it doesn't exist yet + + try (FileWriter writer = new FileWriter(file)) { + for (Task task : tasks) { + writer.write(task.toSaveFormat() + System.lineSeparator()); + } + } catch (IOException e) { + System.out.println("Error saving tasks: " + e.getMessage()); + } + } + + /** + * Loads the tasks present in the data file. + * If the file does not exist, an empty list is returned. + * + * @return A list of tasks loaded from the data file. + */ + public List loadTasks() { + List tasks = new ArrayList<>(); + File file = new File(filePath); + + if (!file.exists()) { + return tasks; // return an empty arraylist of tasks if the file doesn't exist yet + } + + try (Scanner scanner = new Scanner(file)) { + while (scanner.hasNextLine()) { + String taskLine = scanner.nextLine(); + Task task = parseTask(taskLine); + + if (task != null) { + tasks.add(task); + } + + } + } catch (Exception e) { + System.out.println("Error loading tasks: " + e.getMessage()); + } + + return tasks; + + } + + /** + * Creates a {@code Task} object based on the data in a line from the task data file. + * + * @param taskLine A line from the task data file in the format used by {@code Task.toSaveFormat()}. + * @return A {@code Task} object corresponding to the line of data. + */ + private static Task parseTask(String taskLine) { + String[] taskParts = taskLine.split("\\|"); + Task task = null; + + switch (taskParts[0]) { + case "T": + task = new TodoTask(taskParts[3], taskParts[2]); + break; + case "D": + task = new DeadlineTask(taskParts[3], taskParts[2], taskParts[4]); + break; + case "E": + task = new EventTask(taskParts[3], taskParts[2], taskParts[4], taskParts[5]); + break; + default: + throw new NetherException("this should have never happened. What is going on.."); + } + + if (taskParts[1].equals("X")) { + task.markAsDone(); + } + return task; + } +} diff --git a/src/main/java/nether/task/DeadlineTask.java b/src/main/java/nether/task/DeadlineTask.java new file mode 100644 index 0000000000..85afd02ef0 --- /dev/null +++ b/src/main/java/nether/task/DeadlineTask.java @@ -0,0 +1,74 @@ +package nether.task; + +import java.time.DateTimeException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +import nether.NetherException; + + +/** + * Represents a task with a deadline, which includes a description and a specific date/time by when it should be + * completed. + * The {@code DeadlineTask} class is a subclass of the {@link Task} class and adds a deadline component to the task. + */ +public class DeadlineTask extends Task { + private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HHmm"; + private static final String DISPLAY_DATE_FORMAT = "MMM dd yyyy, h:mma"; + protected LocalDateTime by; + + /** + * Constructs a {@code DeadlineTask} object with the specified description and deadline date/time. + * + * @param description The description of the deadline task. + * @param by The deadline date and time in the format {@code yyyy-MM-dd HHmm}. + * @throws NetherException If the date/time format is invalid. + */ + public DeadlineTask(String description, String tag, String by) { + super(description, tag); + assert by.matches("\\d{4}-\\d{2}-\\d{2} \\d{4}") : "Date format must be YYYY-MM-DD HHmm"; + this.by = parseDateTime(by); + } + + /** + * Returns a parsed date and time of the deadline. + * @param dateTimeStr The input date and time in the format {@code yyyy-MM-dd HHmm}. + * @return Parsed date and time of the deadline. + * @throws NetherException If the input date/time does not follow the accepted format. + */ + private static LocalDateTime parseDateTime(String dateTimeStr) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT); + try { + return LocalDateTime.parse(dateTimeStr, formatter); + } catch (DateTimeException e) { + throw new NetherException("the date/time format for the deadline is invalid. Please use " + + "the format: " + DATE_TIME_FORMAT + "."); + } + } + + /** + * Returns the string representation of the {@code DeadlineTask} in the format desired for saving into a data file. + * The format is: {@code D|status|description|yyyy-MM-dd HHmm}, where {@code D} indicates a deadline task. + * + * @return A string in the format {@code D|status|description|deadline}. + */ + @Override + public String toSaveFormat() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT); + return "D|" + getStatusIcon() + "|" + this.getTag() + "|" + this.getDescription() + "|" + + this.by.format(formatter); + } + + /** + * Returns the string representation of the {@code DeadlineTask}. + * The format is: {@code [D][status] description (by: MMM dd yyyy, h:mma)}, where {@code [D]} indicates a + * deadline task. + * + * @return A string representation of the {@code DeadlineTask}. + */ + @Override + public String toString() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DISPLAY_DATE_FORMAT); + return "[D]" + super.toString() + " (by: " + this.by.format(formatter) + ")"; + } +} diff --git a/src/main/java/nether/task/EventTask.java b/src/main/java/nether/task/EventTask.java new file mode 100644 index 0000000000..be32dbafeb --- /dev/null +++ b/src/main/java/nether/task/EventTask.java @@ -0,0 +1,79 @@ +package nether.task; + +import java.time.DateTimeException; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +import nether.NetherException; + + +/** + * Represents an event task that includes a description, a start date/time, and an end date/time. + * The {@code EventTask} class inherits from the {@link Task} class and adds specific start and end timings to the task. + */ +public class EventTask extends Task { + protected LocalDateTime startTime; + protected LocalDateTime endTime; + + /** + * Constructs an {@code EventTask} object with the specified description, start, and end date/times. + * + * @param description The description of the event task. + * @param startTime The start date and time of the event in the format {@code yyyy-MM-dd HHmm}. + * @param endTime The end date and time of the event in the format {@code yyyy-MM-dd HHmm}. + * @throws NetherException If the date/time format for the start or end timings is invalid. + */ + + public EventTask(String description, String tag, String startTime, String endTime) { + super(description, tag); + assert startTime.matches("\\d{4}-\\d{2}-\\d{2} \\d{4}") : "Date format must be YYYY-MM-DD HHmm"; + assert endTime.matches("\\d{4}-\\d{2}-\\d{2} \\d{4}") : "Date format must be YYYY-MM-DD HHmm"; + this.startTime = getDateTime(startTime); + this.endTime = getDateTime(endTime); + } + + /** + * Returns a parsed date and time of the event. + * @param timeStr The input date and time in the format {@code yyyy-MM-dd HHmm}. + * @return Parsed date and time for the event. + * @throws NetherException If the input date/time does not follow the accepted format. + */ + private static LocalDateTime getDateTime(String timeStr) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"); + + // Validate the input date/time and then assign them + try { + return LocalDateTime.parse(timeStr.trim(), formatter); + } catch (DateTimeException e) { + throw new NetherException("the date/time format for the event timing is invalid. Please use " + + "the format: yyyy-MM-dd HHmm."); + } + } + + /** + * Returns the string representation of the {@code EventTask} in the format desired for saving into a data file. + * The format is: {@code E|status|description|start|end}, where {@code E} indicates an event task. + * + * @return A string in the format {@code E|status|description|start|end}. + */ + @Override + public String toSaveFormat() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"); + return "E|" + this.getStatusIcon() + "|" + this.getTag() + "|" + this.getDescription() + "|" + + this.startTime.format(formatter) + + "|" + this.endTime.format(formatter); + } + + /** + * Returns the string representation of the {@code EventTask}. + * The format is: {@code [E][status] description (from: start to: end)}, where {@code [E]} indicates an event task. + * + * @return A string representation of the {@code EventTask}. + */ + @Override + public String toString() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy, h:mma"); + return "[E]" + super.toString() + " (from: " + this.startTime.format(formatter) + + " to: " + this.endTime.format(formatter) + ")"; + } +} diff --git a/src/main/java/nether/task/Task.java b/src/main/java/nether/task/Task.java new file mode 100644 index 0000000000..e1e7a5398a --- /dev/null +++ b/src/main/java/nether/task/Task.java @@ -0,0 +1,104 @@ +package nether.task; + +import java.util.Objects; + +import nether.NetherException; + +/** + * Represents a task object model with a description and status. + * The {@code Task} class serves as an abstract base class for different types of tasks, providing methods to manage the + * task's status and description. + */ + +public abstract class Task { + protected String description; + protected boolean isDone; + protected String tag; + + /** + * Constructs (by default) an incomplete {@code Task} object with the specified description. + * + * @param description The description of the task. + */ + public Task(String description, String tag) { + this.description = description; + this.tag = tag; + this.isDone = false; + if (tag.contains(" ")) { + throw new NetherException("a tag should not have any space!"); + } + } + + /** + * Returns the status icon of the task. + * The status icon is represented as "X" if the task is marked as done, or a space if not. + * + * @return A string representing the task's status icon. + */ + public String getStatusIcon() { + return (this.isDone ? "X" : " "); + } + + /** + * Returns the description of the task. + * + * @return A string representing the task's description. + */ + public String getDescription() { + return this.description; + } + + /** + * Returns the tag of the task. + * + * @return A string representing the task's tag. + */ + public String getTag() { + return this.tag; + } + + /** + * Marks the task as done. + */ + public void markAsDone() { + this.isDone = true; + } + + /** + * Marks the task as not done. + */ + public void markAsNotDone() { + this.isDone = false; + } + + /** + * Returns a string representation of the task in a format suitable for saving. + * This method must be implemented by subclasses to provide a format specific to the type of task. + * + * @return A string in the format suitable for saving the task. + */ + public abstract String toSaveFormat(); + + /** + * Returns whether the task is marked as done. + * + * @return {@code true} if the task is done; {@code false} otherwise. + */ + public boolean isDone() { + return this.isDone; + } + + /** + * Returns a string representation of the task. + * The format is: {@code [statusIcon] description}, where {@code statusIcon} is "X" if the task is done. + * + * @return A string representation of the task. + */ + @Override + public String toString() { + return Objects.equals(this.getTag(), "") + ? String.format("[%s] %s", this.getStatusIcon(), this.getDescription()) + : String.format("[%s] %s %s", this.getStatusIcon(), "<" + this.getTag() + ">", this.getDescription()); + } + +} diff --git a/src/main/java/nether/task/TaskList.java b/src/main/java/nether/task/TaskList.java new file mode 100644 index 0000000000..e133dbf5cb --- /dev/null +++ b/src/main/java/nether/task/TaskList.java @@ -0,0 +1,119 @@ +package nether.task; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Represents a list of tasks. + * The {@code TaskList} class provides methods to manage a collection of {@code Task} objects, + * such as adding, deleting, and retrieving tasks. + */ +public class TaskList { + private List tasks; + + /** + * Constructs an empty {@code TaskList}. + */ + public TaskList() { + this.tasks = new ArrayList<>(); + } + + /** + * Constructs a {@code TaskList} with an initial list of tasks. + * This method is used when we are loading tasks from data file. + * + * @param tasks The initial list of tasks. + */ + public TaskList(List tasks) { + this.tasks = tasks; + } + + /** + * Adds a {@code Task} to the task list. + * + * @param task The task to be added to the list. + */ + public void addTask(Task task) { + tasks.add(task); + } + + /** + * Deletes a {@code Task} from the task list by its index. + * + * @param index The index of the task to be removed. + * @throws IndexOutOfBoundsException if the index is out of range. + */ + public void deleteTask(int index) { + tasks.remove(index); + } + + /** + * Retrieves a {@code Task} from the task list by its index. + * + * @param index The index of the task to be retrieved. + * @return The task with the specified index. + * @throws IndexOutOfBoundsException if the index is out of range. + */ + public Task getTask(int index) { + return tasks.get(index); + } + + /** + * Returns the number of tasks in the task list. + * + * @return The number of tasks in the list. + */ + public int getSize() { + return tasks.size(); + } + + /** + * Returns the list of tasks. + * + * @return A {@code List} of {@code Task} objects in the task list. + */ + public List getTasks() { + return tasks; + } + + /** + * Prints out the task list along with its status (done or not done). + */ + public String printList() { + StringBuilder response = new StringBuilder(); + if (tasks.isEmpty()) { // guard case for 0 length list + response.append("There are no tasks in your list"); + return response.toString(); + } + response.append("Here are the tasks in your list:\n"); + for (int i = 0; i < getSize(); i++) { + response.append((i + 1)).append(". ").append(tasks.get(i).toString()).append("\n"); + } + return response.toString(); + } + + /** + * Finds the tasks whose description matches the input string. + * @param searchString The input string given by user. + * @return A list of tasks whose descriptions match the input string. + */ + public TaskList searchTask(String searchString) { + List matchingTasks = tasks.stream() + .filter(task -> task.getDescription().toLowerCase().contains(searchString)) + .collect(Collectors.toList()); + return new TaskList(matchingTasks); + } + + /** + * Finds the tasks whose tag matches the input string. + * @param searchString The input string given by user. + * @return A list of tasks whose tag match the input string. + */ + public TaskList searchTag(String searchString) { + List matchingTasks = tasks.stream() + .filter(task -> task.getTag().toLowerCase().contains(searchString)) + .collect(Collectors.toList()); + return new TaskList(matchingTasks); + } +} diff --git a/src/main/java/nether/task/TodoTask.java b/src/main/java/nether/task/TodoTask.java new file mode 100644 index 0000000000..dcab83dab9 --- /dev/null +++ b/src/main/java/nether/task/TodoTask.java @@ -0,0 +1,39 @@ +package nether.task; + +/** + * Represents a TodoTask, a type of Task that only has a description and status. No timestamps. + * The TodoTask class inherits the Task class + */ +public class TodoTask extends Task { + + /** + * Constructs a TodoTask object. + * + * @param description The description of the task. + */ + public TodoTask(String description, String tag) { + super(description, tag); + } + + /** + * Returns the string representation of the TodoTask in the format desired to save into a data file. + * The format is: T|status|description, where T indicates a TodoTask. + * + * @return A string in the format "T|status|description". + */ + @Override + public String toSaveFormat() { + return "T|" + this.getStatusIcon() + "|" + this.getTag() + "|" + this.getDescription(); + } + + /** + * Returns the string representation of the TodoTask. + * The format is: [T][status] description, where [T] indicates a TodoTask. + * + * @return A string representation of the TodoTask. + */ + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/resources/css/dialog-box.css b/src/main/resources/css/dialog-box.css new file mode 100644 index 0000000000..151f17587b --- /dev/null +++ b/src/main/resources/css/dialog-box.css @@ -0,0 +1,40 @@ +.label { + background: #fad9a7; + -fx-background-color: background; + -fx-border-color: black; + -fx-border-width: 1px; + -fx-background-radius: 1em 1em 0 1em; + -fx-border-radius: 1em 1em 0 1em; + -fx-padding: 6px; + -fx-border-insets: 0px 7px 0px 7px; + -fx-background-insets: 0px 7px 0px 7px; + -fx-text-fill: ladder(background, white 49%, black 50%); +} + +.reply-label { + -fx-background-radius: 1em 1em 1em 0; + -fx-border-radius: 1em 1em 1em 0; +} + +.error-label { + -fx-background-color: #a52732; /* Light red background */ + -fx-border-color: #721c24; /* Light red border */ + -fx-text-fill: white; /* Dark red text for high contrast */ + -fx-background-radius: 1em 1em 0 1em; + -fx-border-radius: 1em 1em 0 1em; + -fx-padding: 6px; + -fx-border-insets: 0px 7px 0px 7px; + -fx-background-insets: 0px 7px 0px 7px; +} + +#displayPicture { + /* Shadow effect on image. */ + -fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.2), 10, 0.5, 5, 5); + + /* Change size of image. */ + -fx-scale-x: 1; + -fx-scale-y: 1; + + /* Rotate image clockwise by degrees. */ + -fx-rotate: 0; +} diff --git a/src/main/resources/css/main.css b/src/main/resources/css/main.css new file mode 100644 index 0000000000..cc4c9a02f3 --- /dev/null +++ b/src/main/resources/css/main.css @@ -0,0 +1,49 @@ +.root { + main-color: rgb(255, 246, 185); /* Create a looked-up color called "main-color" within root. */ + -fx-background-color: main-color; +} + +.text-field { + -fx-background-color: orange; + -fx-font: 16px "Arial"; + -fx-prompt-text-fill: #5c5c5c; + -fx-background-radius: 0; + -fx-border-radius: 0; +} + +.button { + -fx-background-color: darkorange; + -fx-font: italic bold 16px "Arial"; + -fx-background-radius: 0; + -fx-border-radius: 0; +} + +.button:hover { + -fx-background-color: #ffb258; +} + +.button:pressed { + -fx-background-color: #f8c48a; +} + +.scroll-pane, +.scroll-pane .viewport { + -fx-background-color: transparent; +} + +.scroll-bar { + -fx-font-size: 10px; /* Change width of scroll bar. */ + -fx-background-color: main-color; +} + +.scroll-bar .thumb { + -fx-background-color: #ffd19c; + -fx-background-radius: 1em; +} + +/* Hides the increment and decrement buttons. */ +.scroll-bar .increment-button, +.scroll-bar .decrement-button { + -fx-pref-height: 0; + -fx-opacity: 0; +} diff --git a/src/main/resources/images/Nether.jpeg b/src/main/resources/images/Nether.jpeg new file mode 100644 index 0000000000..664a695831 Binary files /dev/null and b/src/main/resources/images/Nether.jpeg differ diff --git a/src/main/resources/images/UserIcon.png b/src/main/resources/images/UserIcon.png new file mode 100644 index 0000000000..07b82ccf35 Binary files /dev/null and b/src/main/resources/images/UserIcon.png differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..86dad28c23 --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..d8e6864d07 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,19 @@ + + + + + + + + + + + +