diff --git a/.gitignore b/.gitignore index 2873e189e1..f3466512d6 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,8 @@ /.idea/ /out/ /*.iml +/*.class +/*.txt # Gradle build files /.gradle/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..bc8c23ea53 --- /dev/null +++ b/build.gradle @@ -0,0 +1,54 @@ +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("xiaobai.Launcher") +} +shadowJar { + archiveFileName = 'xiaobai.jar' +} + + +run{ + standardInput = System.in +} diff --git a/data/xiaobai.txt b/data/xiaobai.txt new file mode 100644 index 0000000000..6e84bb412d --- /dev/null +++ b/data/xiaobai.txt @@ -0,0 +1,2 @@ +[T][ ] banana +[D][ ] banan (by: Feb 23 2023 1009) diff --git a/docs/README.md b/docs/README.md index 8077118ebe..a85cc0809e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,29 +1,147 @@ -# User Guide +# XiaoBai User Guide -## Features +![](Ui.png) -### Feature-ABC +XiaoBai is a loyal dog that simplifies your day by organizing your tasks into a streamlined task list. Whether it's deadlines, events, or simple to-dos, XiaoBai efficiently captures and categorizes your tasks. With its intuitive interface, adding, managing, and tracking tasks is a breeze. Stay on top of your commitments and boost productivity with XiaoBai by your side. -Description of the feature. +## Adding Deadlines -### Feature-XYZ +Adds a deadline to the task list. -Description of the feature. +Format: `deadline NAME /BYDATETIME` -## Usage +Example: `deadline submit report /by 2022-02-28 09:00` -### `Keyword` - Describe action +``` +WOOOoof. I've added this task: +[D][ ] submit report (by:Feb 28 2022 0900) +Now you have 1 tasks in the list. +``` + +## Adding Events + +Adds an event to the task list. + +Format: `event NAME /FROMDATETIME /TODATETIME` + +Example: `event project meeting /from 18/10/2019 1900 /to 18/10/2019 2100` + +``` +WOOOoof. I've added this task: +[E][ ] project meeting (from: Oct 18 2019 1900 to: Oct 18 2019 2100) +Now you have 1 tasks in the list. +``` + +## Adding Todos + +Adds a todo to the task list. + +Format: `todo NAME` + +Example: `todo borrow book` + +``` +WOOOoof. I've added this task: +[T][ ] borrow book +Now you have 1 tasks in the list. +``` + +## Deleting Tasks + +Deletes a task from the task list. + +Format: `delete INDEX` + +Example: `delete 1` + +``` +Woooof. I've removed this task: +[T][ ] borrow book +Now you have 0 tasks in the list. +``` + +## Marking Tasks + +Marks a task as done from the task list. + +Format: `mark INDEX` + +Example: `mark 1` + +If task is already done: +``` +This task has already been marked as done: +[T][X] borrow book +``` + +If task is not done: +``` +WOOF! I've marked this task as done: +[T][X] borrow book +``` -Describe the action and its outcome. +## Unmarking Tasks -Example of usage: +Marks a task as not done from the task list. -`keyword (optional arguments)` +Format: `unmark INDEX` -Expected outcome: +Example: `unmark 1` -Description of the outcome. +If task is already marked as not done: +``` +"This task has already been marked as not done: +[T][ ] borrow book +``` +If task is done: ``` -expected output +WOOF, I've marked this task as not done yet: +[T][ ] borrow book ``` + +## Printing List + +Prints the task list. + +Format: `list` + +Example: `list` + +``` +Here are the 2 tasks in your list +1.[T][ ] borrow book +2.[E][ ] project meeting (from: Oct 18 2019 1900 to: Oct 18 2019 2100) +``` + +## Finding Tasks + +Prints the task with given keyword. + +Format: `find KEYWORD` + +Example: `find book` + +``` +WOOF! I've found these matching tasks in your list: +1.[T][ ] borrow book +``` + +## Sorting Tasks + +Sorts the task list by alphabetical order. + +Format: `sort` + +Example: `sort` + +``` +Here is the sorted list of 2 tasks: +1.[T][ ] borrow book +2.[E][ ] project meeting (from: Oct 18 2019 1900 to: Oct 18 2019 2100) +``` + +## Exiting XiaoBai + +To exit XiaoBai, simply type `bye` and press Enter. +This will close the application and save any changes made to your task list. diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..dfb5d0db57 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/Command.java b/src/main/java/command/Command.java new file mode 100644 index 0000000000..4abec04298 --- /dev/null +++ b/src/main/java/command/Command.java @@ -0,0 +1,41 @@ +package command; + +import xiaobai.XiaoBai; + +/** + * Represents a command issued by the user. + * A command consists of an array of inputs and a corresponding input type. + */ +public class Command { + private String[] inputs; + private XiaoBai.CommandType inputType; + + /** + * Constructs a new Command object with the given inputs and input type. + * + * @param inputs The array of inputs for the command. + * @param inputType The type of input for the command. + */ + public Command(String[] inputs, XiaoBai.CommandType inputType) { + this.inputs = inputs; + this.inputType = inputType; + } + + /** + * Retrieves the input type of this command. + * + * @return The input type of this command. + */ + public XiaoBai.CommandType getInputType() { + return this.inputType; + } + + /** + * Retrieves the array of inputs for this command. + * + * @return The array of inputs for this command. + */ + public String[] getInputs() { + return this.inputs; + } +} diff --git a/src/main/java/comparator/TaskComparator.java b/src/main/java/comparator/TaskComparator.java new file mode 100644 index 0000000000..43fa37cfd6 --- /dev/null +++ b/src/main/java/comparator/TaskComparator.java @@ -0,0 +1,28 @@ +package comparator; + +import java.util.Comparator; + +import task.Task; + +/** + * Comparator for comparing tasks based on their names. + * + * @param the type of tasks to compare, must extend the Task class + */ +public class TaskComparator implements Comparator { + + /** + * Compares two tasks based on their names. + * + * @param t1 the first task to compare + * @param t2 the second task to compare + * @return a negative integer, zero, or a positive integer as the first task is + * less than, equal to, or greater + * than the second. + */ + @Override + public int compare(T t1, T t2) { + + return t1.getName().compareTo(t2.getName()); + } +} diff --git a/src/main/java/exception/XiaoBaiException.java b/src/main/java/exception/XiaoBaiException.java new file mode 100644 index 0000000000..21dacf182c --- /dev/null +++ b/src/main/java/exception/XiaoBaiException.java @@ -0,0 +1,36 @@ +package exception; + +/** + * Represents an exception specific to the XiaoBai application. + * This exception can be thrown when there is an error or unexpected condition + * in the XiaoBai application. + */ +public class XiaoBaiException extends Exception { + + /** + * Constructs a new XiaoBaiException with no detail message. + */ + public XiaoBaiException() { + super(); + } + + /** + * Constructs a new XiaoBaiException with the specified detail message. + * + * @param message The detail message. + */ + public XiaoBaiException(String message) { + super(message); + } + + /** + * Overrides the getMessage() method to return only the error message + * without the exception class name. + * + * @return The error message. + */ + @Override + public String getMessage() { + return super.getMessage(); + } +} diff --git a/src/main/java/parser/Parser.java b/src/main/java/parser/Parser.java new file mode 100644 index 0000000000..925528d279 --- /dev/null +++ b/src/main/java/parser/Parser.java @@ -0,0 +1,83 @@ +package parser; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +import command.Command; +import xiaobai.XiaoBai; + +/** + * Parses user input to create corresponding Command objects. + */ +public class Parser { + private static final String[] DATE_FORMATS = { "yyyy-MM-dd", "dd-MM-yyyy", "MM-dd-yyyy", "dd/MM/yyyy", "MM/dd/yyyy", + "yyyy/MM/dd", "dd MMM yyyy", "MMM dd yyyy", "yyyy MMM dd", "dd MMM yyyy", "yyyy-MM-d", "d-MM-yyyy", + "MM-d-yyyy", "d/MM/yyyy", "MM/d/yyyy", "yyyy/MM/d", "d MMM yyyy", "MMM d yyyy", "yyyy MMM d", + "dd MMM yyyy", "MMM dd yyyy", "dd-MMMM-yyyy", "yyyy-MMM-dd", "yyyy-MMMM-dd", "dd/MMM/yyyy", + "dd/MMMM/yyyy", "yyyy/MMM/dd", "yyyy/MMMM/dd", "d-MMMM-yyyy", "d MMMM yyyy", "dd MMMM yyyy" }; + private static final String[] TIME_FORMATS = { "HH:mm", "HH:mm", "h:mm a", "HHmm", "hh:mm a" }; + + /** + * Parses the user input and returns the corresponding Command object. + * + * @param userInput The user input string to be parsed. + * @return The Command object corresponding to the user input. + */ + public static Command parseCommand(String userInput) { + String[] words = userInput.split(" "); + String commandWord = words[0].toLowerCase(); + + switch (commandWord) { + case "sort": + return new Command(words, XiaoBai.CommandType.SORT); + case "todo": + return new Command(words, XiaoBai.CommandType.TODO); + case "deadline": + return new Command(words, XiaoBai.CommandType.DEADLINE); + case "event": + return new Command(words, XiaoBai.CommandType.EVENT); + case "list": + return new Command(words, XiaoBai.CommandType.LIST); + case "mark": + return new Command(words, XiaoBai.CommandType.MARK); + case "unmark": + return new Command(words, XiaoBai.CommandType.UNMARK); + case "delete": + return new Command(words, XiaoBai.CommandType.DELETE); + case "bye": + return new Command(words, XiaoBai.CommandType.BYE); + case "find": + return new Command(words, XiaoBai.CommandType.FIND); + default: + return new Command(words, XiaoBai.CommandType.UNKNOWN); + } + } + + /** + * Converts a date-time string to a LocalDateTime object. + * + * @param dateTimeString The date-time string to be converted. + * @return The LocalDateTime object representing the parsed date-time, or null + * if the string cannot be parsed. + */ + public static LocalDateTime convertDateTime(String dateTimeString) { + for (String dateFormat : DATE_FORMATS) { + for (String timeFormat : TIME_FORMATS) { + try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(timeFormat + " " + dateFormat); + return LocalDateTime.parse(dateTimeString, formatter); + } catch (DateTimeParseException e) { + + } + try { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat + " " + timeFormat); + return LocalDateTime.parse(dateTimeString, formatter); + } catch (DateTimeParseException e) { + + } + } + } + return null; + } +} diff --git a/src/main/java/storage/Storage.java b/src/main/java/storage/Storage.java new file mode 100644 index 0000000000..02f02717cf --- /dev/null +++ b/src/main/java/storage/Storage.java @@ -0,0 +1,147 @@ +package storage; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; + +import java.util.ArrayList; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.Files; + +import task.TaskList; +import task.Task; +import task.Deadline; +import task.Event; +import task.Todo; + +import exception.XiaoBaiException; + +/** + * Handles the reading from and writing to a file. + */ +public class Storage { + private static final Path FILEPATH = Paths.get("data", "xiaobai.txt"); + + /** + * Constructs a Storage object. + * Creates the necessary directories if they do not exist. + */ + public Storage() { + try { + Files.createDirectories(FILEPATH.getParent()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Writes the contents of a TaskList to the file. + * + * @param list The TaskList containing tasks to be written to the file. + */ + public void writeArrayListToFile(TaskList list) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILEPATH.toFile()))) { + for (Task element : list.getList()) { + writer.write(element.toString()); + writer.newLine(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Loads tasks from the file and returns them as an ArrayList. + * + * @return An ArrayList containing tasks loaded from the file. + * @throws XiaoBaiException If there is an error reading the file. + */ + public ArrayList load() throws XiaoBaiException { + ArrayList taskList = new ArrayList<>(); + try (BufferedReader reader = new BufferedReader(new FileReader(FILEPATH.toFile()))) { + while (reader.ready()) { + String task = reader.readLine(); + char taskType = task.charAt(1); + char taskStatus = task.charAt(4); + boolean isDone; + if (taskStatus == 'X') { + isDone = true; + } else { + isDone = false; + } + String entireTask = task.substring(7); + switch (taskType) { + case 'T': + taskList.add(processLoadingTodo(entireTask, isDone)); + break; + case 'D': + Deadline newDeadline = processLoadingDeadline(entireTask, isDone); + taskList.add(newDeadline); + break; + case 'E': + Event newEvent = processLoadingEvent(entireTask, isDone); + taskList.add(newEvent); + break; + } + } + } catch (IOException e) { + throw new XiaoBaiException("Unable to load txt file"); + } + return taskList; + } + + /** + * Processes a string representing a deadline task loaded from storage. + * Extracts the task details and deadline information, then constructs a + * Deadline object. + * + * @param entireTask The entire string representing the deadline task. + * @param isDone The completion status of the task. + * @return A Deadline object representing the loaded deadline task. + * @throws XiaoBaiException If there is an error parsing the task details. + */ + public Deadline processLoadingDeadline(String entireTask, boolean isDone) throws XiaoBaiException { + int startIndex = entireTask.indexOf("(by:"); + int endIndex = entireTask.length() - 1; + String byDetails = entireTask.substring(startIndex + 5, endIndex); + String taskDetail = entireTask.substring(0, startIndex - 1); + return new Deadline(taskDetail, byDetails, isDone); + } + + /** + * Processes a string representing an event task loaded from storage. + * Extracts the task details and event timing information, then constructs an + * Event object. + * + * @param entireTask The entire string representing the event task. + * @param isDone The completion status of the task. + * @return An Event object representing the loaded event task. + * @throws XiaoBaiException If there is an error parsing the task details. + */ + public Event processLoadingEvent(String entireTask, boolean isDone) throws XiaoBaiException { + int toIndex = entireTask.indexOf("to:"); + int fromIndex = entireTask.indexOf("(from:"); + int toLastIndex = entireTask.length() - 1; + String taskDetail = entireTask.substring(0, fromIndex - 1); + String toText = entireTask.substring(toIndex + 4, toLastIndex); + String fromText = entireTask.substring(fromIndex + 7, toIndex - 1); + return new Event(taskDetail, fromText, toText, isDone); + } + + /** + * Processes a string representing a Todo task loaded from storage. + * Extracts the task details, then constructs a Todo object. + * + * @param entireTask The entire string representing the todo task. + * @param isDone The completion status of the task. + * @return An Todo object representing the loaded todo task. + * @throws XiaoBaiException If there is an error parsing the task details. + */ + public Todo processLoadingTodo(String entireTask, boolean isDone) throws XiaoBaiException { + return new Todo(entireTask, isDone); + } +} diff --git a/src/main/java/task/Deadline.java b/src/main/java/task/Deadline.java new file mode 100644 index 0000000000..94b37716a8 --- /dev/null +++ b/src/main/java/task/Deadline.java @@ -0,0 +1,83 @@ +package task; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +import exception.XiaoBaiException; + +import parser.Parser; + +/** + * Represents a Deadline task, which is a type of task that needs to be + * completed. + * Inherits from the Task class. + */ +public class Deadline extends Task { + private LocalDateTime by; + private String name; + + /** + * Constructs a Deadline task with the given name and deadline. + * + * @param name The name of the Deadline task. + * @param byText The deadline of the task in string format. + * @throws XiaoBaiException If the task name is empty or null, or if the + * deadline is in an invalid format. + */ + public Deadline(String name, String byText) throws XiaoBaiException { + super(name); + this.name = name; + this.by = Parser.convertDateTime(byText); + if (by == null) { + throw new XiaoBaiException("Invalid date format: Deadline dates should be in dd/mm/yyyy HHmm"); + } + } + + /** + * Constructs a Deadline task with the given name, deadline, and completion + * status. + * + * @param name The name of the Deadline task. + * @param byText The deadline of the task in string format. + * @param doneStatus The completion status of the task. + * @throws XiaoBaiException If the task name is empty or null, or if the + * deadline is in an invalid format. + */ + public Deadline(String name, String byText, boolean doneStatus) throws XiaoBaiException { + super(name, doneStatus); + this.name = name; + this.by = Parser.convertDateTime(byText); + if (by == null) { + throw new XiaoBaiException("Invalid date format: Deadline dates should be in dd/mm/yyyy HHmm"); + } + } + + /** + * Retrieves the name of the Deadline task. + * + * @return The name of the Deadline task. + */ + public String getName() { + return this.name; + } + + /** + * Retrieves the deadline of the Deadline task. + * + * @return The deadline of the Deadline task. + */ + public LocalDateTime getBy() { + return this.by; + } + + /** + * Returns a string representation of the Deadline task. + * + * @return A string representation of the Deadline task. + */ + @Override + public String toString() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy HHmm"); + return String.format("[D]%s (by: %s)", super.toString(), by.format(formatter)); + } +} \ No newline at end of file diff --git a/src/main/java/task/Event.java b/src/main/java/task/Event.java new file mode 100644 index 0000000000..da2b06fb74 --- /dev/null +++ b/src/main/java/task/Event.java @@ -0,0 +1,100 @@ +package task; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +import exception.XiaoBaiException; + +import parser.Parser; + +/** + * Represents an Event task, which is a type of task that needs to be completed. + * Inherits from the Task class. + */ +public class Event extends Task { + private LocalDateTime from; + private LocalDateTime to; + private String name; + + /** + * Constructs an Event task with the given name, start date, and end date. + * + * @param name The name of the Event task. + * @param fromText The start date of the event in string format. + * @param toText The end date of the event in string format. + * @throws XiaoBaiException If the task name is empty or null, or if the start + * or end dates are in an invalid format. + */ + public Event(String name, String fromText, String toText) throws XiaoBaiException { + super(name); + this.name = name; + this.to = Parser.convertDateTime(toText); + this.from = Parser.convertDateTime(fromText); + if (from == null) { + throw new XiaoBaiException("Invalid from date format: Event dates should be in dd/mm/yyyy HHmm"); + } else if (to == null) { + throw new XiaoBaiException("Invalid to date format: Event dates should be in dd/mm/yyyy HHmm"); + } + } + + /** + * Constructs an Event task with the given name, start date, end date, and + * completion status. + * + * @param name The name of the Event task. + * @param fromText The start date of the event in string format. + * @param toText The end date of the event in string format. + * @param doneStatus The completion status of the task. + * @throws XiaoBaiException If the task name is empty or null, or if the start + * or end dates are in an invalid format. + */ + public Event(String name, String fromText, String toText, boolean doneStatus) throws XiaoBaiException { + super(name, doneStatus); + this.name = name; + this.to = Parser.convertDateTime(toText); + this.from = Parser.convertDateTime(fromText); + if (from == null) { + throw new XiaoBaiException("Invalid from date format: Event dates should be in dd/mm/yyyy HHmm"); + } else if (to == null) { + throw new XiaoBaiException("Invalid to date format: Event dates should be in dd/mm/yyyy HHmm"); + } + } + + /** + * Retrieves the name of the Event task. + * + * @return The name of the Event task. + */ + public String getName() { + return this.name; + } + + /** + * Retrieves the end date of the Event task. + * + * @return The end date of the Event task. + */ + public LocalDateTime getTo() { + return this.to; + } + + /** + * Retrieves the start date of the Event task. + * + * @return The start date of the Event task. + */ + public LocalDateTime getFrom() { + return this.from; + } + + /** + * Returns a string representation of the Event task. + * + * @return A string representation of the Event task. + */ + @Override + public String toString() { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd yyyy HHmm"); + return String.format("[E]%s (from: %s to: %s)", super.toString(), from.format(formatter), to.format(formatter)); + } +} \ No newline at end of file diff --git a/src/main/java/task/Task.java b/src/main/java/task/Task.java new file mode 100644 index 0000000000..d6a9c18580 --- /dev/null +++ b/src/main/java/task/Task.java @@ -0,0 +1,87 @@ +package task; + +import exception.XiaoBaiException; + +/** + * Represents a task that needs to be done. + */ +public class Task { + private String name; + private boolean isDone; + + /** + * Constructs a Task with the given name and sets its completion status to + * false. + * + * @param name The name of the task. + * @throws XiaoBaiException If the task name is empty or null. + */ + Task(String name) throws XiaoBaiException { + this.isDone = false; + this.name = name; + if (name == null || name.isEmpty() || name.trim().isEmpty()) { + throw new XiaoBaiException("Task name cannot be empty"); + } + } + + /** + * Constructs a Task with the given name and completion status. + * + * @param name The name of the task. + * @param isDone The completion status of the task. + * @throws XiaoBaiException If the task name is empty or null. + */ + Task(String name, boolean isDone) throws XiaoBaiException { + this.isDone = isDone; + this.name = name; + if (name == null || name.isEmpty() || name.trim().isEmpty()) { + throw new XiaoBaiException("Task name cannot be empty"); + } + } + + /** + * Marks the task as Done + */ + public void setDone() { + this.isDone = true; + } + + /** + * Marks the task as not done. + */ + public void setNotDone() { + this.isDone = false; + } + + /** + * Retrieves the name of the task. + * + * @return The name of the task. + */ + public String getName() { + return this.name; + } + + /** + * Retrieves the status of the task. + * + * @return the status of the task. + */ + public boolean getIsDone() { + return this.isDone; + } + + /** + * Returns a string representation of the task. + * + * @return A string representation of the task. + */ + @Override + public String toString() { + if (this.isDone) { + return String.format("[X] %s", this.name); + } else { + return String.format("[ ] %s", this.name); + } + } +} \ 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..a13e56a809 --- /dev/null +++ b/src/main/java/task/TaskList.java @@ -0,0 +1,93 @@ +package task; + +import java.util.ArrayList; + +import comparator.TaskComparator; + +/** + * Represents a list of tasks. + */ +public class TaskList { + private final ArrayList listOfTasks; + + /** + * Constructs an empty TaskList. + */ + public TaskList() { + this.listOfTasks = new ArrayList<>(); + } + + /** + * Sorts the list of tasks based on their names in alphabetical order. + * This method uses a comparator to perform the sorting operation. + */ + public void sort() { + listOfTasks.sort(new TaskComparator<>()); + } + + /** + * Constructs a TaskList with the given list of tasks. + * + * @param taskList The list of tasks to initialize the TaskList. + */ + public TaskList(ArrayList taskList) { + this.listOfTasks = taskList; + } + + /** + * Adds a task to the task list. + * + * @param newTask The task to be added. + */ + public void addTask(Task newTask) { + listOfTasks.add(newTask); + } + + /** + * Retrieves the task at the specified index in the task list. + * + * @param index The index of the task to retrieve. + * @return The task at the specified index. + */ + public Task getTask(int index) { + assert this.getTask(index) != null; + return listOfTasks.get(index); + } + + /** + * Returns the number of tasks in the task list. + * + * @return The number of tasks in the task list. + */ + public int getSize() { + return listOfTasks.size(); + } + + /** + * Removes the task at the specified index from the task list. + * + * @param index The index of the task to remove. + */ + public void removeTask(int index) { + assert this.getTask(index) != null; + listOfTasks.remove(index); + } + + /** + * Returns the list of tasks. + * + * @return The list of tasks. + */ + public ArrayList getList() { + return listOfTasks; + } + + /** + * Checks if the task list is empty. + * + * @return true if the task list is empty, false otherwise. + */ + public boolean isEmpty() { + return listOfTasks.isEmpty(); + } +} diff --git a/src/main/java/task/Todo.java b/src/main/java/task/Todo.java new file mode 100644 index 0000000000..854eccdf5b --- /dev/null +++ b/src/main/java/task/Todo.java @@ -0,0 +1,44 @@ +package task; + +import exception.XiaoBaiException; + +/** + * Represents a todo task, which is a type of task that needs to be completed. + * Inherits from the Task class. + */ +public class Todo extends Task { + + /** + * Constructs a Todo task with the given name. + * + * @param name The name of the todo task. + * @throws XiaoBaiException if the task name is null, empty, or contains only + * whitespace. + */ + public Todo(String name) throws XiaoBaiException { + super(name); + } + + /** + * Constructs a Todo task with the given name and done status. + * + * @param name The name of the todo task. + * @param doneStatus The status of the todo task (true if done, false + * otherwise). + * @throws XiaoBaiException if the task name is null, empty, or contains only + * whitespace. + */ + public Todo(String name, boolean doneStatus) throws XiaoBaiException { + super(name, doneStatus); + } + + /** + * Returns a string representation of the todo task. + * + * @return The string representation of the todo task. + */ + @Override + public String toString() { + return String.format("[T]%s", super.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/ui/Ui.java b/src/main/java/ui/Ui.java new file mode 100644 index 0000000000..833c6921cd --- /dev/null +++ b/src/main/java/ui/Ui.java @@ -0,0 +1,192 @@ + +package ui; + +import java.util.Scanner; + +import task.TaskList; +import task.Task; + +import exception.XiaoBaiException; + +/** + * Represents the user interface of the XiaoBai chatbot application. + * Handles input and output interactions with the user. + */ +public class Ui { + Scanner reader; + + /** + * Constructs a Ui object with a Scanner to read user input from the console. + */ + public Ui() { + this.reader = new Scanner(System.in); + } + + /** + * Displays a farewell message. + * + * @return A string representing the farewell message. + */ + public String showExitMessage() { + StringBuilder outputString = new StringBuilder(); + outputString.append("Woof!! Hope to see you again soon!"); + return outputString.toString(); + } + + /** + * Displays an error message. + * + * @param e The XiaoBaiException indicating the error. + * @return The error message as a string. + */ + public String showErrorMessage(XiaoBaiException e) { + return e.getMessage(); + } + + /** + * Displays a message confirming the deletion of a task. + * + * @param task The task that was deleted. + * @param taskList The updated task list after deletion. + * @return The deletion confirmation message as a string. + */ + public String showDeleteMessage(Task task, TaskList taskList) { + StringBuilder outputString = new StringBuilder(); + outputString.append("Woooof. I've removed this task:\n"); + outputString.append(task.toString() + "\n"); + int len = taskList.getSize(); + outputString.append(String.format("Now you have %d tasks in the list.", len)); + return outputString.toString(); + } + + /** + * Displays a message confirming the addition of a task. + * + * @param task The task that was added. + * @param taskList The updated task list after addition. + * @return The addition confirmation message as a string. + */ + public String showAddTaskMessage(Task task, TaskList taskList) { + StringBuilder outputString = new StringBuilder(); + outputString.append("WOOOoof. I've added this task:\n"); + outputString.append(task.toString() + "\n"); + int len = taskList.getSize(); + outputString.append(String.format("Now you have %d tasks in the list.", len)); + return outputString.toString(); + } + + /** + * Generates a message displaying the sorted list of tasks. + * + * @param taskList The TaskList containing the sorted list of tasks. + * @return A formatted string displaying the sorted list of tasks. + */ + public String showSortMessage(TaskList taskList) { + StringBuilder outputString = new StringBuilder(); + StringBuilder finalString = new StringBuilder(); + int len = taskList.getSize(); + finalString.append(String.format("Woof!! Here is the sorted list of %d tasks:\n", len)); + int counter = 1; + for (Task c : taskList.getList()) { + finalString.append(String.format("%d. %s\n", counter, c.toString())); + counter++; + } + outputString.append(finalString.toString()); + return outputString.toString(); + } + + /** + * Generates a message indicating that the specified task has been marked as + * done. + * If the task is already marked as done, the message reflects this status. + * + * @param task The task to be marked as done. + * @return A string message indicating the status of the task after marking. + */ + public String showMarkMessage(Task task) { + StringBuilder outputString = new StringBuilder(); + if (task.getIsDone()) { + outputString.append("This task has already been marked as done:\n"); + } else { + outputString.append("WOOF! I've marked this task as done:\n"); + } + outputString.append(task.toString()); + return outputString.toString(); + } + + /** + * Generates a message indicating that the specified task has been marked as not + * done. + * If the task is already marked as not done, the message reflects this status. + * + * @param task The task to be marked as not done. + * @return A string message indicating the status of the task after marking. + */ + public String showUnmarkMessage(Task task) { + StringBuilder outputString = new StringBuilder(); + if (task.getIsDone()) { + outputString.append("WOOF, I've marked this task as not done yet:\n"); + } else { + outputString.append("This task has already been marked as not done:\n"); + } + outputString.append(task.toString()); + return outputString.toString(); + } + + /** + * Displays the list of tasks in the task list. + * + * @param taskList The TaskList containing the list of tasks to be displayed. + * @return A formatted string displaying the list of tasks. + */ + public String showPrintListMessage(TaskList taskList) { + StringBuilder outputString = new StringBuilder(); + StringBuilder finalString = new StringBuilder(); + if (taskList.isEmpty()) { + outputString.append("Woof!! There are no tasks in your list"); + } else { + int counter = 1; + for (Task c : taskList.getList()) { + finalString.append(String.format("%d. %s\n", counter, c.toString())); + counter++; + } + int len = taskList.getSize(); + outputString.append(String.format("Woof!! Here are the %s tasks in your list:\n", len)); + outputString.append(finalString.toString()); + } + return outputString.toString(); + } + + /** + * Finds tasks in the given task list that contain the specified string. + * Displays the matching tasks along with their indices. + * + * @param taskList The task list to search in. + * @param findString The string to search for in task names. + */ + public String showFoundTask(TaskList taskList, String findString) { + StringBuilder outputString = new StringBuilder(); + StringBuilder finalString = new StringBuilder(); + finalString.append("WOOF! I've found these matching tasks in your list:\n"); + int counter = 1; + for (Task c : taskList.getList()) { + if (c.getName().contains(findString)) { + finalString.append(String.format("%d. %s\n", counter, c.toString())); + counter++; + } + } + outputString.append(finalString.toString()); + return outputString.toString(); + } + + /** + * Displays an error message when there is an issue loading data into Duke. + * + * @param e The DukeException indicating the loading error. + */ + public void showLoadingError(XiaoBaiException e) { + StringBuilder outputString = new StringBuilder(); + outputString.append(e.getMessage() + "\n"); + System.out.println(outputString.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/xiaobai/DialogBox.java b/src/main/java/xiaobai/DialogBox.java new file mode 100644 index 0000000000..0adcdf408b --- /dev/null +++ b/src/main/java/xiaobai/DialogBox.java @@ -0,0 +1,82 @@ +package xiaobai; + +import java.io.IOException; + +import java.util.Collections; + +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; + +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; + +import javafx.geometry.Pos; + +import javafx.scene.Node; +import javafx.scene.control.Label; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.HBox; + +/** + * An example of a custom control using FXML. + * This control represents a dialog box consisting of an ImageView to represent + * the speaker's face and a label + * containing text from the speaker. + */ +public class DialogBox extends HBox { + @FXML + private Label dialog; + @FXML + private ImageView displayPicture; + + private DialogBox(String text, Image img) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(MainWindow.class.getResource("/view/DialogBox.fxml")); + fxmlLoader.setController(this); + fxmlLoader.setRoot(this); + fxmlLoader.load(); + } catch (IOException e) { + e.printStackTrace(); + } + + dialog.setText(text); + displayPicture.setImage(img); + } + + /** + * Flips the dialog box such that the ImageView is on the left and text on the + * right. + */ + private void flip() { + ObservableList tmp = FXCollections.observableArrayList(this.getChildren()); + Collections.reverse(tmp); + getChildren().setAll(tmp); + setAlignment(Pos.TOP_LEFT); + } + + /** + * Creates and returns a DialogBox representing the user's dialog. + * + * @param text The text to be displayed in the dialog box. + * @param img The image representing the user's face. + * @return The DialogBox representing the user's dialog. + */ + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + /** + * Creates and returns a DialogBox representing the chatbot's dialog. + * This method also flips the dialog box layout. + * + * @param text The text to be displayed in the dialog box. + * @param img The image representing the chatbot's face. + * @return The DialogBox representing the chatbot's dialog. + */ + public static DialogBox getDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/xiaobai/Launcher.java b/src/main/java/xiaobai/Launcher.java new file mode 100644 index 0000000000..9a2dfd4215 --- /dev/null +++ b/src/main/java/xiaobai/Launcher.java @@ -0,0 +1,12 @@ +package xiaobai; + +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/xiaobai/Main.java b/src/main/java/xiaobai/Main.java new file mode 100644 index 0000000000..938996e3ac --- /dev/null +++ b/src/main/java/xiaobai/Main.java @@ -0,0 +1,42 @@ +package xiaobai; + +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 XiaoBai using FXML. + */ +public class Main extends Application { + + private XiaoBai xiaoBai = new XiaoBai(); + + /** + * Starts the application by loading the main FXML file and initializing the + * GUI. + * + * @param stage The primary stage for this application, onto which the + * application scene can be set. + */ + @Override + public void start(Stage stage) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/view/MainWindow.fxml")); + AnchorPane ap = fxmlLoader.load(); + Scene scene = new Scene(ap); + stage.setScene(scene); + fxmlLoader.getController().setXiaoBai(xiaoBai); + stage.setResizable(false); + stage.show(); + stage.setTitle("XiaoBai"); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/xiaobai/MainWindow.java b/src/main/java/xiaobai/MainWindow.java new file mode 100644 index 0000000000..867705c15e --- /dev/null +++ b/src/main/java/xiaobai/MainWindow.java @@ -0,0 +1,67 @@ +package xiaobai; + +import javafx.fxml.FXML; + +import javafx.scene.control.Button; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.image.Image; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.VBox; + +/** + * Controller for MainWindow. Provides the layout for the other controls. + */ +public class MainWindow extends AnchorPane { + @FXML + private ScrollPane scrollPane; + @FXML + private VBox dialogContainer; + @FXML + private TextField userInput; + @FXML + private Button sendButton; + + private XiaoBai xiaoBai; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/User.png")); + private Image xiaoBaiImage = new Image(this.getClass().getResourceAsStream("/images/XiaoBai.png")); + + /** + * Initializes the main window layout. + * Binds the scroll pane to the height of the dialog container. + * Displays a welcome message from XiaoBai upon initialization. + */ + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + String welcomeString = String.format( + "Woof! I'm %s \nWhat can I do for you? \n", XiaoBai.getName()); + dialogContainer.getChildren().add(DialogBox.getDialog(welcomeString, xiaoBaiImage)); + } + + /** + * Sets the instance of XiaoBai for the main window. + * + * @param xiaoBai The instance of XiaoBai to be set. + */ + public void setXiaoBai(XiaoBai d) { + xiaoBai = d; + } + + /** + * Handles user input. + * Creates dialog boxes for the user input and the corresponding response from + * XiaoBai, then appends them to the dialog container. + * Clears the user input after processing. + */ + @FXML + private void handleUserInput() { + String input = userInput.getText(); + String response = xiaoBai.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDialog(response, xiaoBaiImage)); + userInput.clear(); + } +} diff --git a/src/main/java/xiaobai/XiaoBai.java b/src/main/java/xiaobai/XiaoBai.java new file mode 100644 index 0000000000..f559b7be9f --- /dev/null +++ b/src/main/java/xiaobai/XiaoBai.java @@ -0,0 +1,217 @@ + +package xiaobai; + +import ui.Ui; + +import storage.Storage; + +import task.TaskList; +import task.Task; +import task.Deadline; +import task.Event; +import task.Todo; + +import exception.XiaoBaiException; + +import command.Command; + +import parser.Parser; + +/** + * Represents the main logic of the XiaoBai application. + * It handles user input, processes commands, and generates responses + * accordingly. + */ +public class XiaoBai { + private Ui ui; + private Storage storage; + private TaskList taskList; + private static final String BOTNAME = "XiaoBai"; + + /** + * Constructs a new instance of XiaoBai. + * Initializes the UI, storage, and task list components. + * If there's an error loading tasks from storage, a default task list is + * created. + */ + public XiaoBai() { + this.ui = new Ui(); + this.storage = new Storage(); + try { + this.taskList = new TaskList(storage.load()); + } catch (XiaoBaiException e) { + ui.showLoadingError(e); + this.taskList = new TaskList(); + } + } + + /** + * Returns the name of the XiaoBai bot. + * + * @return The name of the bot. + */ + public static String getName() { + return BOTNAME; + } + + /** + * Generates a response to the user input. + * Parses the input, processes commands, and returns a response string. + * + * @param input The user input string. + * @return The response generated by XiaoBai. + */ + public String getResponse(String input) { + try { + Command command = Parser.parseCommand(input); + switch (command.getInputType()) { + case SORT: + taskList.sort(); + return ui.showSortMessage(taskList); + case BYE: + storage.writeArrayListToFile(taskList); + return ui.showExitMessage(); + case TODO: + return processTodoCommand(input); + case LIST: + return ui.showPrintListMessage(taskList); + case DEADLINE: + return processDeadlineCommand(input); + case EVENT: + return processEventCommand(input); + case MARK: + return processMarkCommand(input); + case UNMARK: + return processUnmarkCommand(input); + case DELETE: + return processDeleteCommand(input); + case FIND: + return processFindCommand(input); + case UNKNOWN: + throw new XiaoBaiException("Unknown input"); + default: + throw new XiaoBaiException("Unknown input"); + } + } catch (XiaoBaiException e) { + return ui.showErrorMessage(e); + } + } + + /** + * Represents the types of commands that XiaoBai can process. + */ + public enum CommandType { + TODO, DEADLINE, EVENT, LIST, MARK, UNMARK, DELETE, BYE, UNKNOWN, FIND, SORT + } + + /** + * Processes a todo command, extracts task details, adds the task to the task + * list, + * and returns a message confirming the addition. + * + * @param input The input string containing the todo command and task details. + * @return A message confirming the addition of the todo task. + * @throws XiaoBaiException If task details are empty or if there is an error + * adding the task. + */ + public String processTodoCommand(String input) throws XiaoBaiException { + Todo newTodo = new Todo(input.substring(4)); + taskList.addTask(newTodo); + return ui.showAddTaskMessage(newTodo, taskList); + } + + /** + * Processes a deadline command, extracts task details, adds the task to the + * task list, + * and returns a message confirming the addition. + * + * @param input The input string containing the deadline command and task + * details. + * @return A message confirming the addition of the deadline task. + * @throws XiaoBaiException If task details are empty or if there is an error + * adding the task. + */ + public String processDeadlineCommand(String input) throws XiaoBaiException { + String[] parts = input.substring(8).split(" /"); + Deadline newDeadline = new Deadline(parts[0], parts[1].substring(3)); + taskList.addTask(newDeadline); + return ui.showAddTaskMessage(newDeadline, taskList); + } + + /** + * Processes an event command, extracts task details, adds the task to the task + * list, + * and returns a message confirming the addition. + * + * @param input The input string containing the event command and task details. + * @return A message confirming the addition of the event task. + * @throws XiaoBaiException If task details are empty or if there is an error + * adding the task. + */ + public String processEventCommand(String input) throws XiaoBaiException { + String[] parts = input.substring(5).split(" /"); + Event newEvent = new Event(parts[0], parts[1].substring(5), + parts[2].substring(3)); + taskList.addTask(newEvent); + return ui.showAddTaskMessage(newEvent, taskList); + } + + /** + * Processes a mark command, marks a task as done, and returns a message + * confirming the change. + * + * @param input The input string containing the mark command and task index. + * @return A message confirming the task has been marked as done. + */ + public String processMarkCommand(String input) { + String[] parts = input.split(" "); + int index = Integer.parseInt(parts[1]); + Task task = taskList.getTask(index - 1); + task.setDone(); + return ui.showMarkMessage(task); + } + + /** + * Processes an unmark command, marks a task as not done, and returns a message + * confirming the change. + * + * @param input The input string containing the unmark command and task index. + * @return A message confirming the task has been marked as not done. + */ + public String processUnmarkCommand(String input) { + String[] parts = input.split(" "); + Task unmarkTask = taskList.getTask(Integer.parseInt(parts[1]) - 1); + unmarkTask.setNotDone(); + return ui.showUnmarkMessage(unmarkTask); + } + + /** + * Processes a delete command, removes a task from the task list, and returns a + * message confirming the deletion. + * + * @param input The input string containing the delete command and task index. + * @return A message confirming the task has been deleted. + */ + public String processDeleteCommand(String input) throws XiaoBaiException { + if (taskList.isEmpty()) { + throw new XiaoBaiException("Task List is empty"); + } + String[] parts = input.split(" "); + int deleteIndex = Integer.parseInt(parts[1]) - 1; + Task deletedTask = taskList.getTask(deleteIndex); + taskList.removeTask(deleteIndex); + return ui.showDeleteMessage(deletedTask, taskList); + } + + /** + * Processes a find command, searches for tasks containing the specified string, + * and returns a message displaying the matching tasks. + * + * @param input The input string containing the find command and search string. + * @return A message displaying the matching tasks found. + */ + public String processFindCommand(String input) { + String stringToFind = input.substring(5); + return ui.showFoundTask(taskList, stringToFind); + } +} \ No newline at end of file diff --git a/src/main/resources/images/User.png b/src/main/resources/images/User.png new file mode 100644 index 0000000000..7635bfb943 Binary files /dev/null and b/src/main/resources/images/User.png differ diff --git a/src/main/resources/images/XiaoBai.png b/src/main/resources/images/XiaoBai.png new file mode 100644 index 0000000000..c4d8f4577f Binary files /dev/null and b/src/main/resources/images/XiaoBai.png differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..5c73f1bfc9 --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..b851e5d4b0 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/java/seedu/xiaobai/DeadlineTest.java b/src/test/java/seedu/xiaobai/DeadlineTest.java new file mode 100644 index 0000000000..b05d9511b9 --- /dev/null +++ b/src/test/java/seedu/xiaobai/DeadlineTest.java @@ -0,0 +1,32 @@ +package seedu.xiaobai; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import exception.XiaoBaiException; + +import task.Deadline; + +public class DeadlineTest { + + @Test + public void testDeadlineConstructor_validDateFormat() { + try { + Deadline deadline = new Deadline("Finish report", "12/02/2022 19:11"); + assertEquals("Finish report", deadline.getName()); + assertEquals("2022-02-12T19:11", deadline.getBy().toString()); + } catch (XiaoBaiException e) { + } + } + + @Test + public void testDeadlineConstructor_validTimeFormat() { + try { + Deadline deadline = new Deadline("Finish report", "12/02/2022 1800"); + assertEquals("Finish report", deadline.getName()); + assertEquals("2022-02-12T18:00", deadline.getBy().toString()); + } catch (XiaoBaiException e) { + } + } +} diff --git a/src/test/java/seedu/xiaobai/EventTest.java b/src/test/java/seedu/xiaobai/EventTest.java new file mode 100644 index 0000000000..d8fed414e0 --- /dev/null +++ b/src/test/java/seedu/xiaobai/EventTest.java @@ -0,0 +1,32 @@ +package seedu.xiaobai; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import exception.XiaoBaiException; + +import task.Event; + +public class EventTest { + + @Test + public void testEventConstructor_ToDates() { + try { + Event event = new Event("Birthday party", "12/02/2022 1800", "12/02/2022 2000"); + assertEquals("Birthday party", event.getName()); + assertEquals("2022-02-12T20:00", event.getTo().toString()); + } catch (XiaoBaiException e) { + } + } + + @Test + public void testEventConstructor_FromDates() { + try { + Event event = new Event("Birthday party", "12/02/2022 1800", "12/02/2022 2000"); + assertEquals("Birthday party", event.getName()); + assertEquals("2022-02-12T18:00", event.getFrom().toString()); + } catch (XiaoBaiException e) { + } + } +} diff --git a/tempCodeRunnerFile.python b/tempCodeRunnerFile.python new file mode 100755 index 0000000000..8255d4ec6e --- /dev/null +++ b/tempCodeRunnerFile.python @@ -0,0 +1,8 @@ +def print_board(board): + # start + for i in range(len(board)): + for j in range(len(i)): + print(j + " ") + # end + +print_board([[0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) \ No newline at end of file diff --git a/text-ui-test/EXPECTED.TXT b/text-ui-test/EXPECTED.TXT index 657e74f6e7..1b95c9a680 100644 --- a/text-ui-test/EXPECTED.TXT +++ b/text-ui-test/EXPECTED.TXT @@ -5,3 +5,53 @@ Hello from | |_| | |_| | < __/ |____/ \__,_|_|\_\___| + ___________________________________________________________ + Hello! I'm Yube + What can I do for you? + ___________________________________________________________ + +todo borrow book + ___________________________________________________________ + Got it. I've added this task: + [T][ ] borrow book + Now you have 1 tasks in the list. + ___________________________________________________________ + +list + ___________________________________________________________ + Here are the tasks in your list: + 1. [T][ ] borrow book + ___________________________________________________________ + +deadline return book /by Sunday + ___________________________________________________________ + Got it. I've added this task: + [D][ ] return book (by: Sunday) + Now you have 2 tasks in the list. + ___________________________________________________________ + +event project meeting /from Mon 2pm /to 4pm + ___________________________________________________________ + Got it. I've added this task: + [E][ ] project meeting (from: Mon 2pm to: 4pm) + Now you have 3 tasks in the list. + ___________________________________________________________ + +mark 1 + ___________________________________________________________ + + Nice! I've marked this task as done: + [T][X] borrow book + ___________________________________________________________ + +unmark 1 + ___________________________________________________________ + + OK, I've marked this task as not done yet: + [T][ ] borrow book + ___________________________________________________________ + +bye + ___________________________________________________________ + Bye. Hope to see you again soon! + ___________________________________________________________ \ No newline at end of file diff --git a/text-ui-test/input.txt b/text-ui-test/input.txt index e69de29bb2..24232827c6 100644 --- a/text-ui-test/input.txt +++ b/text-ui-test/input.txt @@ -0,0 +1,9 @@ +todo borrow book +list +deadline return book /by 2/12/2019 1800 +event project meeting /from 18/10/2019 1900 /to 18/10/2019 2100 +deadline submit report /by 2022-02-28 09:00 +mark 1 +unmark 1 +list +bye \ No newline at end of file diff --git a/text-ui-test/runtest.bat b/text-ui-test/runtest.bat index 0873744649..ea1a2d9358 100644 --- a/text-ui-test/runtest.bat +++ b/text-ui-test/runtest.bat @@ -15,7 +15,7 @@ IF ERRORLEVEL 1 ( REM no error here, errorlevel == 0 REM run the program, feed commands from input.txt file and redirect the output to the ACTUAL.TXT -java -classpath ..\bin Duke < input.txt > ACTUAL.TXT +java -classpath ..\bin xiaobai.XiaoBai < input.txt > ACTUAL.TXT REM compare the output to the expected output FC ACTUAL.TXT EXPECTED.TXT diff --git a/text-ui-test/runtest.sh b/text-ui-test/runtest.sh old mode 100644 new mode 100755